如何在WordPress后查询中添加类别筛选器

时间:2013-12-06 06:51:55

标签: php wordpress

我使用此代码

过滤了侧边栏中的帖子
$mostlikequerystr = "
SELECT $wpdb->posts.* 
FROM $wpdb->posts, $wpdb->postmeta
WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id 
AND $wpdb->postmeta.meta_key = 'most_liked' 
AND $wpdb->posts.post_status = 'publish' 
AND $wpdb->posts.post_type = 'post'
ORDER BY $wpdb->postmeta.meta_value DESC
    LIMIT 0 , 10";

此代码工作正常,但现在我想添加类别过滤器..

为此我使用了$ term_id

global $wpdb;
$term_id = get_term_by('slug','trailers');
$term_id->term_id;
echo $term_id;//Prints 12 
$mostlikequerystr="SELECT $wpdb->posts.*  FROM $wpdb->posts,$wpdb->postmeta
INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.$wpdb->taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE ($wpdb->term_taxonomy.term_id = $term_id 
AND $wpdb->posts.ID = $wpdb->postmeta.post_id 
AND $wpdb->postmeta.meta_key = 'most_liked'
AND $wpdb->term_taxonomy.taxonomy = 'categories'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_status = 'publish')
        LIMIT 0 , 10";

        $tariler_post = $wpdb->get_results($mostlikequerystr, 'OBJECT');
         echo $wpdb->show_errors();

但它不适合我,也没有错误...

1 个答案:

答案 0 :(得分:0)

WHERE子句

中缺少条件运算符
WHERE ($wpdb->term_taxonomy.term_id = $term_id here
                                               ^^^^^
    $wpdb->posts.ID = $wpdb->postmeta.post_id 

通过添加AND

来试试这个
$mostlikequerystr = "
SELECT $wpdb->posts.*  FROM $wpdb->posts,$wpdb->postmeta
INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.$wpdb->taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)
WHERE ($wpdb->term_taxonomy.term_id = $term_id 
AND $wpdb->posts.ID = $wpdb->postmeta.post_id 
AND $wpdb->postmeta.meta_key = 'most_liked'
AND $wpdb->term_taxonomy.taxonomy = 'categories'
AND $wpdb->posts.post_type = 'post'
AND $wpdb->posts.post_status = 'publish'
ORDER BY $wpdb->postmeta.meta_value DESC
)
        LIMIT 0 , 10";

如果您正在使用WPDB类尝试捕获错误

<?php $wpdb->show_errors(); ?> 

其他方式可以使用WP的内置函数

$args = array(
'posts_per_page' => 10,
'post_type' => 'post',
'post_status' => 'publish',
'meta_query' => array(
 array(
        'key' => 'most_liked',
        'value' => '',
        'compare' => '!='
    ),
'category__in' => 'id here or skip this argument'
'orderby' => 'meta_value_num',
);
$tariler_post=new WP_Query($args);