2017-05-09 70 views
1

下面的代码是通过查看wpdb中的标题行来检查帖子是否存在。检查标题和分类术语是否存在帖子?

function post_exists($title) { 
    global $wpdb; 
    return $wpdb->get_row("SELECT * FROM wp_posts WHERE post_title = '" . $title . "'", 'ARRAY_A'); 
} 

如何检查标题和分类术语是否存在帖子?
例如,我有一个自定义分类“genres”和分类术语“horror”。我想检查帖子是否存在帖子标题,还有“恐怖”这个词。

我一直在挣扎着这几天。

回答

0

分类和术语都存储在wp_term_taxonomywp_terms 表,所以你需要加入,然后以获得所需的输出。

我修改了你的函数,如下所示。

function wh_post_exists($title) { 
    global $wpdb; 

    $query = $wpdb->prepare("SELECT posts.ID 
     FROM $wpdb->posts AS posts 
     INNER JOIN $wpdb->term_relationships AS term_relationships ON posts.ID = term_relationships.object_id 
     INNER JOIN $wpdb->term_taxonomy AS term_taxonomy ON term_relationships.term_taxonomy_id = term_taxonomy.term_taxonomy_id 
     INNER JOIN $wpdb->terms AS terms ON term_taxonomy.term_id = terms.term_id 
     WHERE term_taxonomy.taxonomy = 'genres' 
      AND terms.slug = 'horror' 
      AND posts.post_type = 'post' 
      AND posts.post_title = %s", $title); 
    $result = $wpdb->get_row($query, 'ARRAY_A'); 

    //checking error msg 
    if ($wpdb->last_error !== '') { 
     $wpdb->print_error(); 
     die('-- code execution discontinued --'); 
    } 
    if (count($result) > 0) { 
     return TRUE; //exists 
    } else { 
     return FALSE; //does not exists 
    } 
} 

希望这会有所帮助!

0
$result = get_posts(array(
'showposts' => -1, 
'post_type' => 'post', // post Type any even you can use custom post type 
'tax_query' => array(
    array(
    'taxonomy' => 'genres', // Taxonomy name like genres 
    'field' => 'name', 
    'terms' => array('horror')) // Taxonomy term 
), 
'orderby' => 'title', 
'order' => 'ASC')); 

if(!empty($result)){ // Term related Post exist then do code 
} 
相关问题