找到并组合了一些似乎适用于类别的代码。因此,如果其他人遇到同样的问题,请留下代码。供参考。-Filter all queries with a specific taxonomy- Adding Custom User Profile data based upon Categories
下面允许用户在此配置文件上选择类别,然后frontpage将允许显示其所选类别。
//create the user category fields
add_action( \'show_user_profile\', \'add_user_categories\' );
add_action( \'edit_user_profile\', \'add_user_categories\' );
function add_user_categories($user ){
?>
<table class="form-table">
<tr>
<th><label for="user_categories"><?php _e("User categories"); ?></label></th>
<td>
<?php
$data = get_the_author_meta( \'user_categories\', $user->ID );
$args = array( \'hide_empty\' =>0, \'taxonomy\'=> \'category\');
$categories= get_categories($args);
if ($categories){
foreach ( $categories as $category ){
if(in_array($category->term_id,(array)$data)) {
$selected = \'checked="checked""\';
} else {
$selected = \'\';
}
echo \'<input name="user_categories[]" value="\'.$category->term_id.\'" \'.$selected.\' type="checkbox"/>\'.$category->name.\'<br/>\';
}
}
?>
</td>
</tr>
</table>
<?php
}
//save the user category fields
add_action( \'personal_options_update\', \'save_user_categories\' );
add_action( \'edit_user_profile_update\', \'save_user_categories\' );
function save_user_categories( $user_id ){
if ( !current_user_can( \'edit_user\', $user_id ) ) { return false; }
update_usermeta( $user_id, \'user_categories\', $_POST[\'user_categories\'] );
}
function my_get_posts( $query ) {
// we only need to modify the query for logged in users
if ( !is_user_logged_in() ) return;
$current_user = wp_get_current_user();
// assuming that the users interest is stored as user_categories meta key
$user_categories = get_user_meta( $current_user->ID, \'user_categories\', true );
$query->set( \'tax_query\', array(
array(
\'taxonomy\' => \'category\',
\'field\' => \'id\',
\'terms\' => $user_categories
)
));
return $query;
}
add_filter( \'pre_get_posts\', \'my_get_posts\' );