Get latest 4 post on a custom post filtered by category

There should be no difference and either custom WP_Query or wp_get_recent_posts should work like a charm in this case. (To be honest, wp_get_recent_posts uses get_posts and this one is based onWP_Query`).

So the problem is not with methods you’re trying to use, but the way you use them…

wp_get_recent_posts

wp_get_recent_posts function takes two arguments:

  • $args – list of arguments that describe the posts you want to get,
  • $output – constant OBJECT, ARRAY_A which describes how the result will be formatted.

So let’s take a look at your call of that function:

$args = array('post_type' => 'product',
    'numberposts' => 4,
    'include' => get_cat_ID($atts['category']),
);
wp_get_recent_posts($args, $atts['category']);

You put $atts['category'] as second argument, so the $output argument is incorrect. And even worse – you put category ID as include argument, which should be a list of posts that should be included…

How to make it work?

$args = array(
    'post_type' => 'product',
    'numberposts' => 4,
    'tax_query' => array(
        array(
            'taxonomy' => 'product_cat',
            'field' => 'term_id',
            'terms' => 30278,
            'operator' => 'IN'
        )
) );
$recent_posts = wp_get_recent_posts( $args );

WP_Query

So why the WP_Query method doesn’t work?

Take a look at possible parameters of WP_Query: https://codex.wordpress.org/Class_Reference/WP_Query

There is no parameter called taxonomy, so this one will be ignored.

There is also no category param, so this one will be ignored too.

And how to make it work? Easy – just use the same $args as in wp_get_recent_posts call above.

Leave a Comment