Get WordPress Posts By Category

Get WordPress Posts By Category

In WordPress a Category is part of a wider system of Taxonomies. A taxonomy is simply ‘a way to group various similar objects or items’. I say this because understanding the various ways to get Categories in WordPress depends what kind of Taxonomy you are trying to get. You can employ different methods of accessing the WordPress Database (via PHP functions) to get these various types of Taxonomies.

Most of the time you will probably be getting a Custom Taxonomy (aka a Category Name which you have created yourself for your own particular purposes) but you may also be trying to get other kinds. We’ll go through all of the examples here in various different WordPress PHP Functions to suit your situation.

Quick Links

Get WordPress Posts by Category using get_posts()

Example 1:

This will get all product posts with category of ‘customTaxonomy’. Change the orange highlighted areas as per your use case. For eg, if you wanted WooCommerce Orders then replace ‘product’ with ‘shop_order’.

$args = array (
    'post_type' => 'product',
    'tax_query' => array (
            'taxonomy' => 'customTaxonomy'
        )
    )
);

$posts = get_posts( $args );

Example 2a:

You could also get the same category of products which area ALSO have a specific ‘tag’ which is another kind of Taxonomy.

d

Example 2b:

This does the same as above 2a example but is less verbose.

$posts = get_posts( 
    array(
        'post_type'      => 'product',
        'customTaxonomy' => 'tagName'
    ) 
);

Get WordPress Posts by Category using WP_Query()

Conveniently enough the WP_Query class in WordPress takes the same arguments as get_posts which means we can simply rewrite our code from the previous section above to use WP_Query Class instead of get_posts().

PROTIP: WP_Query Class in WordPress is great for most use cases but every now and then you will see some sort of bug or it doesn’t quite get what you think it is getting from adding $args and letting it do its magic. This is because it makes certain assumptions to make it work with such a wide range or $args. Thats all good but sometimes you just want to see what kind of RAW SQL query is being run with WP_Query. That said you can use the below code on the object to see the specific SQL it is running…

$args = array(
    'post_type' => 'product', // or 'shop_order' for woocommerce
    'tax_query' => array (
            'taxonomy' => 'customTaxonomy'
        )
    )
);
$results = new WP_Query( $args );
echo $results->request; // this is where you'll see the RAW SQL.

Example 1:

$args = array(
    'post_type' => 'product', // or 'shop_order' for woocommerce
    'tax_query' => array (
            'taxonomy' => 'customTaxonomy'
        )
    )
);
$posts = new WP_Query( $args );

// WP_Query has a loop that is required to access the results
if ( $posts->have_posts() ) {
    echo '<ul>';
    while ( $posts->have_posts() ) {
        $posts->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Example 2a:

This code will use WP_Query to get the Custom Category Name ‘customTaxonomy’ which also have the Tag ‘tagName’.

$args = array(
    'post_type' => 'product', // or shop_order for woocommerce
    'tax_query' => array (
            'taxonomy' => 'customTaxonomy',
            'terms'    => 'tagName'
        )
    )
);
$posts = new WP_Query( $args );

// WP_Query has a loop that is required to access the results
if ( $posts->have_posts() ) {
    echo '<ul>';
    while ( $posts->have_posts() ) {
        $posts->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Example 2b:

This code is functionally the same as Example 2a but is a shorthand version which could be used as an alternative. This code will also use WP_Query to get the Custom Category Name ‘customTaxonomy’ which also have the Tag ‘tagName’.

$args = array(
    'post_type' => 'product', // or shop_order for woocommerce
    'tax_query' => array (
            'taxonomy' => 'customTaxonomy',
            'customTaxonomy' => 'tagName'
        )
    )
);
$posts = new WP_Query( $args );

// WP_Query has a loop that is required to access the results
if ( $posts->have_posts() ) {
    echo '<ul>';
    while ( $posts->have_posts() ) {
        $posts->the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

Get WordPress Posts by Category using RAW SQL

In some certain circumstances you may want to use RAW SQL to get posts. Usually this is when there is the need for a speed advantage in retrieving the data from the Database. To be honest a situation where you need the query to be faster than the other methods shown on this page you would need to be doing a more complicated query than just getting posts by category but the below examples could serve as a basis for creating a more complicated, multi join kind of SQL statement which would be slow in other use cases above.

Example 1:

This will get all info related to posts which have the category name ‘Recipes’. You could add more things to this for eg, published posts only or a post_type but here you have the basic SQL call.

global $wpdb;
$results = $wpdb->get_results( "
        SELECT * FROM " . $wpdb->prefix . "_posts p
LEFT JOIN " . $wpdb->prefix . "_term_relationships rel ON rel.object_id = p.ID
LEFT JOIN " . $wpdb->prefix . "_term_taxonomy tax ON tax.term_taxonomy_id = rel.term_taxonomy_id
LEFT JOIN " . $wpdb->prefix . "_terms t ON t.term_id = tax.term_id
WHERE t.name = 'Recipes'
AND tax.taxonomy = 'category'",
        OBJECT );

foreach($results as $result){
    echo $result->post_title; 
}

Learn WordPress customization throughly with an online course at Udemy

If you are having difficulty understanding this tutorial and then I suggest you start from scratch with WordPress in general. The best way to learn is with a better all around general understanding of WordPress. Check out some of the courses on Udemy related to WordPress. They cover developer level courses and more non-dev CMS editor type tutorials as well.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *