How to display a specific category using a custom Query in WordPress?

Hi I want to display a specific category from a custom query in WordPress. My code works fine and it gets the latest 4 posts, but what I want now is to retrieve a specific category. My code is below thanks :

global $wpdb;

$posts = $wpdb-get_results(

    'SELECT ID, post_title AS title, post_excerpt AS excerpt
    FROM '.$wpdb-posts.' 
    WHERE post_type = "post" 
    AND post_status = "publish" 
    ORDER BY post_date DESC 
    LIMIT 4'

);

Topic query Wordpress sql

Category Web


If you still want to do that by $wpdb please try this..

<?php
global $wpdb;

$query = "SELECT p.*, terms.term_taxonomy_id, terms.term_id, terms.slug, terms.name from $wpdb->posts p INNER JOIN 
            ( SELECT rel.object_id , rel.term_taxonomy_id, term.term_id, term.name, term.slug FROM $wpdb->term_relationships rel 
            INNER JOIN (SELECT ttax.term_taxonomy_id, ttax.term_id, t.name, t.slug FROM $wpdb->term_taxonomy ttax
            INNER JOIN $wpdb->terms t ON t.term_id = ttax.term_id
            ) term
            ON rel.term_taxonomy_id = term.term_taxonomy_id ) terms
            ON p.ID = terms.object_id
            WHERE p.post_status = 'publish'
            AND p.post_type = 'post'
            AND terms.slug = 'my-category-slug'"; // just add what field that you wan to filter by (i.e terms.id or terms.slug or terms.name )

$posts = $wpdb->get_results($query, OBJECT);

echo "<pre>";
print_r($posts);

or you can wrap it into function


Why are you using $wpdb to query from database. Use WP_Query or get_posts instead. This is how you can query from WordPress database and get 4 latest posts from category id 24.

<?php

    $args = array(
        'post_type' => 'post',
        'cat' => 24,
        'posts_per_page' => 4,
        'ignore_sticky_posts' => 1
    );

    $my_query = new WP_Query( $args );

    if ( $my_query->have_posts() ) :

        while ( $my_query->have_posts() ) : $my_query->the_post();
            get_template_part( 'content', get_post_format() );
        endwhile;

    endif;

?>

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.