我想要一个代码来检查帖子创建时帖子标题是否重复(已经存在(将帖子ID添加到标题中。我有一段代码用于将post-id添加到标题中,它在之上的php5.6中运行良好
add_filter('title_save_pre','auto_generate_post_title');
function auto_generate_post_title($title) {
global $post;
if (isset($post->ID)) {
if (empty($_POST['post_title']) && 'post' == get_post_type($post->ID)){
// get the current post ID number
$id = get_the_ID();
// add ID number with order strong
$title = $title .' - ' .$id;} }
return $title;
}
但我需要一个额外的条件来检查帖子标题是否已经存在。
假设我有一个标题为"最好的三明治"的帖子,当我想创建一个新的标题为"最佳三明治"并且帖子id为216时,新标题应该是:"最佳三明治-216">
您可以使用以下标题检索所有帖子:
$numberOfPostsWithThisTitle = count(get_posts([ "post_type" => "post", "s" => $title] );
这将检查现有的帖子,并且只有在标题发布时才会在末尾附加帖子id。
add_filter('title_save_pre','he_auto_generate_post_title');
function he_auto_generate_post_title($title) {
global $post, $wpdb;
if (isset($post->ID) && $post->post_type == 'post'){
// create array from the title
$new_title = explode('-', $post->post_title);
//query database to find all published posts with same title in beginning.
$existing_titles = $wpdb->get_results("SELECT ID, post_title FROM {$wpdb->prefix}posts WHERE post_title LIKE '{$title}%' and post_status = 'publish'");
foreach ($existing_titles as $existing_title){
// loop through results and find a match
$check = explode('-', $existing_title->post_title);
if ($check[0] == $title) {
// add ID number with order strong
$title = $new_title[0] .' - ' .$post->ID;
}
}
}
return $title;
}
设置一个具有标题名称的变量,在这种情况下,我在POST上得到以下内容,这是我想要检查的标题:
$_POST['portfolioTitle']
然后在查询你所有的帖子时,你做
if ( get_page_by_title( $_POST['portfolioTitle'] ) === null ) {