根据标题和分类术语检查帖子是否存在?

时间:2017-05-09 02:14:26

标签: php mysql wordpress taxonomy term

下面的代码是通过查看wpdb中的标题行来检查帖子是否存在。

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

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

我几天都在努力解决这个问题。

2 个答案:

答案 0 :(得分: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
    }
}

希望这有帮助!

答案 1 :(得分: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
}