【问题标题】:Check if post exists by title and taxonomy term?按标题和分类术语检查帖子是否存在?
【发布时间】:2017-05-09 02:14:26
【问题描述】:

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

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

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

我已经为此苦苦挣扎了几天。

【问题讨论】:

    标签: php mysql wordpress taxonomy


    【解决方案1】:

    分类和术语存储在wp_term_taxonomy 和wp_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
        }
    }
    

    希望这会有所帮助!

    【讨论】:

      【解决方案2】:
      $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
      }
      

      【讨论】:

        猜你喜欢
        • 2018-09-11
        • 1970-01-01
        • 2021-06-09
        • 2022-01-03
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-10-10
        • 1970-01-01
        相关资源
        最近更新 更多