I’m trying to get the latest 4 posts filtered by category.
My post type are products.
I already tried wp_get_recent_posts, but it doesn’t have an attribute for category filter.
Then i tried with the WP_Query, but is not working too.
$args2 = array(
'post_type' => 'product',
'taxonomy' => 'product_cat',
'category' => '30278'
);
$the_query = new WP_Query($args2);
while ( $the_query->have_posts() ) :
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
endwhile;
It shows me always the same posts.
This is my recent post code:
$args = array('post_type' => 'product',
'numberposts' => 4,
'include' => get_cat_ID($atts['category']),
);
wp_get_recent_posts($args, $atts['category']);
I tried to add in my args include, exclude, category and category name. without results.
I really don’t know how to solve this.
Thank you in advance.
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 on
WP_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.