• I have this code, its working good, but its gets posts from all categories. I need to get posts only from category ID 2. I tried to add “AND term_taxonomy_id = 2” to my code, but this didint work. Can somebody help me with this, my code:

    <?php //loops all posts
                    $my_query = $wpdb->get_results
                    ("SELECT * FROM <code>{$table_prefix}posts</code>, {$table_prefix}postmeta 
                    WHERE {$table_prefix}posts.post_status = 'publish' 
                    AND {$table_prefix}posts.id = {$table_prefix}postmeta.post_id 
                    AND {$table_prefix}postmeta.<code>meta_key</code> = 'wpcf-data-nuo' ORDER BY if({$table_prefix}postmeta.<code>meta_value</code> = '' or {$table_prefix}postmeta.<code>meta_value</code> is null,1,0), {$table_prefix}postmeta.<code>meta_value</code> ASC LIMIT 12");
                    foreach($my_query as $post) {
                        setup_postdata($post);
                ?>
Viewing 2 replies - 1 through 2 (of 2 total)
  • Moderator bcworkz

    (@bcworkz)

    Categories are a taxonomy, not post meta, so the term relationships table needs to be joined in. Here’s a query I’ve used recently. You should be able to easily adapt it to your needs.

    global $wpdb;
    $query = $wpdb->get_results( "SELECT * FROM $wpdb->posts
        LEFT JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id)
        WHERE $wpdb->term_relationships.term_taxonomy_id = 2
        AND $wpdb->posts.post_type = 'post'
        AND $wpdb->posts.post_status = 'publish'
        GROUP BY $wpdb->posts.ID
        ORDER BY $wpdb->posts.post_date DESC;" );
    Thread Starter modeman

    (@modeman)

    Thanks i did it by your example ??

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘$wpdb get_results – loop from specific category’ is closed to new replies.