getarchives_where
云策文档标注
概述
getarchives_where 是一个 WordPress 过滤器,用于修改检索存档的 SQL WHERE 子句。它允许开发者自定义存档查询的条件,例如按分类筛选。
关键要点
- 过滤器名称:getarchives_where,用于过滤存档查询的 WHERE 子句。
- 参数:$sql_where(SQL WHERE 子句字符串)和 $parsed_args(参数数组)。
- 相关函数:与 wp_get_archives() 配合使用,用于显示存档链接。
- 版本:从 WordPress 2.2.0 引入。
代码示例
add_filter( 'getarchives_where', 'custom_archive_by_category_where' );
add_filter( 'getarchives_join', 'custom_archive_by_category_join' );
function custom_archive_by_category_where($x) {
global $wpdb;
$current_term_slug = get_query_var( 'news_category' );
if (!empty($current_term_slug)) {
$current_term = get_term_by('slug', $current_term_slug, 'news_category');
if (is_wp_error($current_term) ) {
return $x;
}
$current_term_id = $current_term->term_id;
return $x . " AND $wpdb->term_taxonomy.taxonomy = 'news_category' AND $wpdb->term_taxonomy.term_id IN ($current_term_id)";
}
return $x;
}
function custom_archive_by_category_join( $x ) {
global $wpdb;
return $x . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)";
}注意事项
- 使用 getarchives_where 过滤器时,通常需要同时使用 getarchives_join 过滤器来添加必要的 JOIN 子句,否则查询可能返回空结果。
- 示例代码展示了如何根据自定义分类法(如 news_category)筛选存档,需确保分类法名称和查询变量正确。
原文内容
Filters the SQL WHERE clause for retrieving archives.
Parameters
$sql_wherestring-
Portion of SQL query containing the WHERE clause.
$parsed_argsarray-
An array of default arguments.
Source
$where = apply_filters( 'getarchives_where', $sql_where, $parsed_args );
Changelog
| Version | Description |
|---|---|
| 2.2.0 | Introduced. |
Skip to note 2 content
Khoi Pro
The example of modifying a current query and add your own category id to filter:
add_filter( 'getarchives_where', 'custom_archive_by_category_where' ); add_filter( 'getarchives_join', 'custom_archive_by_category_join' ); // You must add `join` to keep it works. Adding only `where` will return nothing function custom_archive_by_category_where($x) { global $wpdb; $current_term_slug = get_query_var( 'news_category' ); if (!empty($current_term_slug)) { $current_term = get_term_by('slug', $current_term_slug, 'news_category'); if (is_wp_error($current_term) ) { return $x; } $current_term_id = $current_term->term_id; return $x . " AND $wpdb->term_taxonomy.taxonomy = 'news_category' AND $wpdb->term_taxonomy.term_id IN ($current_term_id)"; } return $x; } function custom_archive_by_category_join( $x ) { global $wpdb; return $x . " INNER JOIN $wpdb->term_relationships ON ($wpdb->posts.ID = $wpdb->term_relationships.object_id) INNER JOIN $wpdb->term_taxonomy ON ($wpdb->term_relationships.term_taxonomy_id = $wpdb->term_taxonomy.term_taxonomy_id)"; }Read https://developer.wordpress.org/reference/functions/wp_get_archives/ to see what it should be work together.