Reputation: 10581
I followed this accepted answer and read the docs, finally I tried to apply the logic using ajax
:
On frontEnd:
var ajax_url = '<?php echo admin_url( 'admin-ajax.php' ); ?>';
$("#publish").on("click", function() {
$.ajax({
url : ajax_url,
type: 'post',
data: {
action: 'data_Publish', portfolioTitle: $("#portfolioTitle").val(), idsInput: $("#idsInput").val()
},
success: function(data) {
console.log(data);
$("#titleSaveModal .modal-body").html("<p>Pubblicato</p>");
}
});
});
On function.php
function data_Publish() {
$post_title = $_POST['portfolioTitle'];
$post = array(
'post_title' => $post_title,
'post_status' => 'publish',
'post_type' => 'page',
'page_template' => 'portoflio.php'
);
if ( get_page_by_title( $post_title ) === null ) {
echo "Already exists!";
} else {
$post_id = wp_insert_post( $post );
add_post_meta($post_id, 'portfolio-ids', $_POST['idsInput'], true);
}
wp_die();
}
add_action('wp_ajax_data_Publish', 'data_Publish');
But even if I give a same title, it will always publish a new post, meaning it is not finding out that title already exists, what am I doing wrong?
Upvotes: 0
Views: 1626
Reputation: 8171
The condition is backwards, get_page_by_title( $post_title ) === null
means it doesn't exist, you just have to swap the then
and else
code blocks.
if ( get_page_by_title( $post_title ) === null ) {
$post_id = wp_insert_post( $post );
add_post_meta($post_id, 'portfolio-ids', $_POST['idsInput'], true);
} else {
echo "Already exists!";
}
Upvotes: 1