[英]WP check if custom post title exists before wp_insert_post
我正在尝试在运行 wp_insert_post() 之前进行条件检查(检查是否存在具有相同帖子标题的帖子),但即使找到现有帖子,它仍然接受插入。 我尝试使用 post_exists(),但是这个 function 出于某种原因破坏了整个页面。 我究竟做错了什么?
页脚.php:
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
$args = array(
"post_title" => $footer_email,
"post_type" => 'subscriptions',
"post_status" => 'publish',
);
$query = new WP_Query( $args );
if($query->have_posts()) {
$statusmessage = '<p class="subscription-confirmation">You have already signed up.</p>';
}
else {
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
} // end else
wp_reset_postdata();
} // end if isset footer email
?>
您可以使用post_exists() 。 检查以下内容。
<?php
$statusmessage = '';
if (isset($_POST['footer-email'])){
$footer_email = $_POST['footer-email'];
if( ! post_exists( $footer_email ) ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
} // end if isset footer email
您可以使用get_page_by_title()按标题获取订阅者。
$statusmessage = '';
if ( isset( $_POST['footer-email'] ) ){
$footer_email = $_POST['footer-email'];
$subscribers = get_page_by_title( $footer_email , OBJECT, 'subscribers' );
if( !$subscribers->ID ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
}
或自定义 wpdb 查询。
global $wpdb;
$postid = $wpdb->get_var( "SELECT ID FROM $wpdb->posts WHERE post_title = '" . $footer_email . "'" );
if( !$postid ){
$my_post = array(
'post_title' => "$footer_email",
'post_content' => "$footer_email",
'post_type' => 'subscribers',
'post_status' => 'publish',
);
$post_id = wp_insert_post( $my_post );
$statusmessage = '<p class="subscription-confirmation">You have successfully signed up.</p>';
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.