How to Add Category Filter in WordPress Post Query

I filtered the post’s in my sidebar by using this code,

$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";

This code working perfect , but now i want to add a category filter too..

Read More

for this i used $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();

but its not working for me and no error too …

Related posts

Leave a Reply

1 comment

  1. You are missing with conditional operator in your WHERE clause

    WHERE ($wpdb->term_taxonomy.term_id = $term_id here
                                                   ^^^^^
        $wpdb->posts.ID = $wpdb->postmeta.post_id 
    

    Try this one by adding 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";
    

    If you are using WPDB class try to catch the errors

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

    Other way you can use WP’s built in functions

    $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);