1
votes

I am trying to list posts belonging only to a certain category on the default wordpress blog page. I need to do this by adding a filter/action hook via a plugin. I can not edit the theme template files.

I have done this for recent posts listing using the following code:

add_filter('widget_posts_args', 'my_widget_posts_args');

function my_widget_posts_args($args) {
  return array( 'posts_per_page'      => 10,//set the number you want here
                'no_found_rows'       => true,
                'post_status'         => 'publish',
                'ignore_sticky_posts' => true,
                'cat'                 => 52 //$cat -> term_id//the current category id
               );
}

How do I do the same for the post listing page?

1
what have you done so far? please add the codeinarilo
i am creating simple plugins for filter the posts on blog page. now i need to write code on plugins and filter the post by category on post listing. I have removed from recent post listing using code add_filter( 'widget_posts_args', 'my_widget_posts_args'); function my_widget_posts_args($args) { return array( 'posts_per_page' => 10,//set the number you want here 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, 'cat' => 52 //$cat -> term_id//the current category id ); }Rocky Prajapati
@RockyPrajapati For future reference, when someone asks for code, edit it into the question itself instead of putting it in a comment. It's much more legible that way.Davis Broda

1 Answers

1
votes

I'm assuming that by default wp blog page you mean the frontpage. If not, use is_home in place of is_front_page.

In order to filter the posts by category before the query is run, you need to change the category parameter of the query cat in the pre_get_posts action hook.

Add the following to your plugin code:

add_action('pre_get_posts', 'my_post_filter');

function my_post_filter($query) {
  if($query->is_front_page() && $query->is_main_query()) {
    $query->set('cat', '52');
  }
}

The above can be used in a theme's functions.php as well.