【问题标题】:how to filter the posts of wordpress default post listing by using hook / filter on plugin or function.php page?如何使用插件或function.php页面上的钩子/过滤器过滤wordpress默认帖子列表的帖子?
【发布时间】:2017-12-30 21:22:13
【问题描述】:

我正在尝试在默认的 wordpress 博客页面上列出仅属于某个类别的帖子。我需要通过插件添加过滤器/动作钩子来做到这一点。我无法编辑主题模板文件。

我已使用以下代码为最近的帖子列表完成此操作:

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
               );
}

我如何为帖子列表页面做同样的事情?

【问题讨论】:

  • 到目前为止你做了什么?请添加代码
  • 我正在创建简单的插件来过滤博客页面上的帖子。现在我需要在插件上编写代码并在帖子列表中按类别过滤帖子。我已使用代码 add_filter('widget_posts_args', 'my_widget_posts_args'); 从最近的帖子列表中删除function my_widget_posts_args($args) { return array( 'posts_per_page' => 10,//在这里设置你想要的数字 'no_found_rows' => true, 'post_status' => 'publish', 'ignore_sticky_posts' => true, 'cat ' => 52 //$cat -> term_id//当前类别id ); }
  • @RockyPrajapati 供将来参考,当有人要求提供代码时,请将其编辑到问题本身而不是放在评论中。这样更清晰。

标签: wordpress post filter hook


【解决方案1】:

我假设默认情况下 wp 博客页面是指首页。如果不是,请使用is_home 代替is_front_page

为了在查询运行之前按类别过滤帖子,您需要在pre_get_posts 操作挂钩中更改查询cat 的类别参数。

将以下内容添加到您的插件代码中:

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');
  }
}

以上也可以用在主题的functions.php中。

【讨论】:

  • 这可能会回答这个问题,但也请简要说明您的代码做了什么以及为什么它可以解决最初的问题。
  • 添加说明。
猜你喜欢
  • 2011-02-11
  • 1970-01-01
  • 2020-12-20
  • 2012-02-01
  • 2020-03-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多