WordPress中的钩子posts_where_paged是用于修改数据库查询中的WHERE条件的hook。
使用方式:
1. 在主题或插件的functions.php文件中添加以下代码:
function custom_posts_where_paged($where, $query) {
// 修改$where条件
return $where;
}
add_filter('posts_where_paged', 'custom_posts_where_paged', 10, 2);
2. 在上述代码中,custom_posts_where_paged是自定义的函数名,用于修改$where条件。$where是当前的WHERE条件,$query是当前的查询对象。
3. 使用add_filter函数将custom_posts_where_paged函数添加为posts_where_paged钩子的过滤器。
示例:
以下示例将在首页查询中排除特定的分类文章:
function exclude_category_posts($where, $query) {
if ($query->is_home() && $query->is_main_query()) {
$exclude_category = '1,2,3'; // 要排除的分类ID
$where .= " AND wp_terms.term_id NOT IN ($exclude_category)";
}
return $where;
}
add_filter('posts_where_paged', 'exclude_category_posts', 10, 2);
在上述示例中,exclude_category_posts函数判断当前查询是否是首页的主查询,并且将要排除的分类ID添加到WHERE条件中。
注意事项:
- 使用posts_where_paged钩子时,需要注意当前的查询对象,以避免对不需要修改的查询产生影响。
- 钩子函数的优先级(priority)可以通过add_filter函数中的第三个参数进行调整,默认为10。如果有多个过滤器函数针对同一个钩子,可以通过调整优先级控制执行顺序。
- 钩子函数可以接受不同数量的参数,具体取决于钩子的定义。在使用add_filter函数时,需要指定钩子函数的参数数量。


0 个评论