0
votes

I'm new to WordPress and am attempting to edit an existing theme (Materialis Pro) to allow me to show the latest posts but refined by category.

I'm edited the shortcode to allow me to pass the category from the editor and I can retrieve this value in the php.

The existing code for showing the latest posts just shows the last 3 posts, I want to add a categoryId into the mix so we only see posts the last 3 posts in category X.

The existing code in the plugin does the following:

 $recentPosts = new WP_Query();
 $recentPosts->query('posts_per_page=' . $post_numbers . ';post_status=publish;post_type=post;ignore_sticky_posts=1;');

From reading online it should just be as simple as passing cat=4 or whatever into that query like this:

$recentPosts->query('cat=4;posts_per_page=' . $post_numbers . ';post_status=publish;post_type=post;ignore_sticky_posts=1;');

But when I do that I'm getting nothing back, no errors, just no posts. Oddly if I add it to the end of the query I get results but it's like it's ignoring the category entirely.

I've successfully gotten the category using the category Id I set in the shortcode like this:

$theCategory = get_the_category_by_ID($attrs['shortcode_catId']);

But I'm unsure how to apply this as a filter or add it to the query. Any pointers are much appreciated.

I really thought this should be fairly straightforward but I was wrong or at least I'm just not seeing the proper way of filtering or sorting by category.

1

1 Answers

1
votes

To be honest, it's the first time I've seen the WP_Query class being used like that so I'm not entirely sure what's going on. Try this instead:

$args = array(
    'cat' => 4,
    'posts_per_page' => $post_numbers,
    'post_status' => 'publish',
    'post_type' => 'post',
    'ignore_sticky_posts' => 1
);
$recentPosts = new WP_Query($args);

if ( $recentPosts->have_posts() ) {
    // ... rest of the code

Alternatively, you can also use the category__in parameter:

$args = array(
    'category__in' => array(4),
    'posts_per_page' => $post_numbers,
    'post_status' => 'publish',
    'post_type' => 'post',
    'ignore_sticky_posts' => 1
);
$recentPosts = new WP_Query($args);

if ( $recentPosts->have_posts() ) {
    // ... rest of the code