我跟随this accepted answer并阅读了the docs,最后我尝试使用ajax
应用逻辑:
在前端:
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>");
}
});
});
在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');
但是,即使我给了相同的标题,它也会始终发布新帖子,这意味着它没有发现标题已经存在,我在做什么错了?
答案 0 :(得分:1)
条件是向后的,get_page_by_title( $post_title ) === null
表示它不存在,您只需要交换then
和else
代码块。
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!";
}