创建URL重写规则与使用URL查询变量对循环查询排序完全不同。
在担心前者之前,我建议先解决后者。
首先,您需要注册URL查询变量,例如functions.php
):
function mytheme_loop_sort_queryvars( $qvars ) {
$qvars[] = \'loop_orderby\';
$qvars[] = \'loop_order\';
return $qvars;
}
add_filter( \'query_vars\', \'mytheme_loop_sort_queryvars\' );
因此,现在您已经注册了查询变量,可以使用它们修改默认的循环查询。
首先,准备查询变量,例如(在适当的模板文件中):
<?php
// Orderby Query Filter
$loop_orderby = \'\';
// Array of valid \'orderby\' parameters, for validating the URL query string
$valid_loop_orderbys = array( \'ID\', \'author\', \'title\', \'date\', \'modified\', \'parent\', \'rand\', \'comment_count\', \'menu_order\' ); //note: excluding \'meta_value\', for simplicity
// Do something only if the query var is set
if ( isset( $wp_query->query_vars[\'loop_orderby\'] ) ) {
// Make sure that only a valid \'orderby\' parameter is used
// If URL string value isn\'t valid, use default \'date\'
$title_filter = ( in_array( $wp_query->query_vars[\'loop_orderby\'], $valid_loop_orderbys ) ? $wp_query->query_vars[\'loop_orderby\'] : \'date\' );
}
// Order Query Filter
$loop_order = \'\';
// Array of valid \'order\' paramters, for validating the URL query string
$valid_loop_orders = array( \'ASC\', \'DESC\' );
// Do something only if the query var is set
if ( isset( $wp_query->query_vars[\'loop_order\'] ) ) {
// Make sure that only a valid \'order\' parameter is used
// If URL string value isn\'t valid, use default \'DESC\'
$title_filter = ( in_array( $wp_query->query_vars[\'loop_order\'], $valid_loop_orders ) ? $wp_query->query_vars[\'loop_order\'] : \'DESC\' );
}
?>
现在,使用查询变量修改循环。首先,设置自定义参数数组:
<?php
$custom_orderby_query_args = array();
if ( \'\' != $filter_loop_orderby ) {
$custom_orderby_query_args[\'orderby\'] = $filter_loop_orderby;
}
if ( \'\' != $filter_loop_order ) {
$custom_orderby_query_args[\'order\'] = $filter_loop_order;
}
?>
现在,将自定义参数数组与默认循环查询参数合并:
<?php
// Globalize the default query
global $wp_query;
// Merge arguments
$customized_query_args = array_merge( $wp_query->query, $custom_orderby_query_args );
// Modify the query output
query_posts( $customized_query_args );
?>
注意:您必须准确地确定如何应用URL查询字符串。这段代码只在查询字符串就位后使用它们。