我建议你pre_get_posts
并更改查询,而不是在模板中启动自己的查询(这样可以保持模板整洁,避免数据库查询翻倍!)。
下面演示了这一点,再加上管理中的奖励设置字段(在“阅读”下),以选择“特殊排序”适用的类别-看看设置API到底有多简单!
/**
* Intercept the query & attach our own parameters if the conditions are met.
*/
function wpse_42457_custom_category_order( $wp_query )
{
if ( ! $wp_query->is_category() ) // save proceeding processing
return;
$special_categories = wp_parse_id_list( get_option( \'sorted_categories\' ) );
if ( $wp_query->is_category( $special_categories ) ) {
// We\'ve got a winner - set our special params.
$wp_query->set( \'meta_key\', \'programnumber\' );
$wp_query->set( \'orderby\', \'meta_value\' );
$wp_query->set( \'order\', \'ASC\' );
}
}
add_action( \'pre_get_posts\', \'wpse_42457_custom_category_order\' );
/**
* Register the sorted categories option & the settings field.
*/
function wpse_42457_admin_init()
{
add_settings_field( \'sorted_categories\', \'Special Categories\', \'wpse_42457_setting_field\', \'reading\', \'default\' );
register_setting( \'reading\', \'sorted_categories\', \'wpse_42457_setting_sanitize\' );
}
add_action( \'admin_init\', \'wpse_42457_admin_init\' );
/**
* Sanitize our checked categories by turning back to a comma-delimited string.
*
* This\'ll save bytes in the options table, plus it can be "unserialized" more
* efficiently with wp_parse_id_list() when it\'s actually needed.
*/
function wpse_42457_setting_sanitize()
{
// wp_terms_checklist uses "post_category" POST name.
if ( isset( $_POST[\'post_category\'] ) )
$value = $_POST[\'post_category\'];
else
$value = array(); // none checked
return implode( \',\', wp_parse_id_list( $value ) );
}
/**
* Display the sorted categories field.
*/
function wpse_42457_setting_field()
{
// Please forgive me for this dirty HTML!
?>
<style>#sorted_categories li li { margin: 0 0 0 15px }</style>
<ul id="sorted_categories">
<?php
wp_terms_checklist( 0, array(
\'selected_cats\' => wp_parse_id_list( get_option( \'sorted_categories\' ) ),
\'checked_ontop\' => false,
\'taxonomy\' => \'category\'
));
?>
</ul>
<?php
}
虽然我总是觉得我应该鼓励其他人为自己采取措施,但事实证明,编写代码要比穿行容易得多——希望这将是一种无教育意义的行为!
你需要把它放到一个自定义插件中,或者你的主题functions.php
.