您应该能够获取当前登录的用户ID,然后使用pre_get_posts 将主页/博客页面上的主查询更改为仅显示该特定用户的帖子。据我所知,你是在专门谈论作者。
您可能还需要检查用户的功能,因为简单的订阅者无法在博客/主页上看到任何帖子,因为他们无法撰写帖子。
A非常简单pre_get_posts 操作将如下所示:(NOTE: 以下内容未经测试
add_action( \'pre_get_posts\', function ( $q )
{
if ( is_user_logged_in() ) { // First check if we have a logged in user before doing anything
if ( $q->is_home() // Only targets the main page, home page
&& $q->is_main_query() // Only targets the main query
) {
// Get the current logged in user
$current_logged_in_user = wp_get_current_user();
// Set the logged in user ID as value to the author parameter
$q->set( \'author\', $current_logged_in_user->ID );
}
}
});
从评论中,似乎每个用户都有一个同名的类别,然后将该特定类别附加到帖子中
为了适应这种情况,您需要执行以下操作
如上所述,获取当前登录用户
然后,您需要使用当前用户提供的与类别匹配的信息。例如,如果\'display_name\' == \'category name\', 然后,如果用户显示名称为Jane Doe, 然后,分配给该名称的类别名称也将被调用Jane Doe
在上述示例中,我们需要按名称获取类别,以便获取类别ID。我们将使用get_term_by() 可以与内置分类法一起使用,如category 或自定义分类法
然后我们可以继续做与原始答案相同的事情
你可以这样做;(我对代码进行了注释,以便您更好地理解和遵循它)
add_action( \'pre_get_posts\', function ( $q )
{
if ( is_user_logged_in() ) { // First check if we have a logged in user before doing anything
if ( $q->is_home() // Only targets the main page, home page
&& $q->is_main_query() // Only targets the main query
) {
// Get the current logged in user
$current_logged_in_user = wp_get_current_user();
/**
* We will now get the term/category object from the user display_name
* You will need to make sure if this corresponds with your term/category
* If not, use the correct info to match
*/
$term = get_term_by(
\'name\', // We will get our term by name as term name == user display_name. Change as needed
$current_logged_in_user->display_name, // Our value to look for will be user display_name
\'category\' // The taxonomy the term belongs to. category is the build in taxonomy
);
if ( $term ) { // Only filter the main query if we actually have a term with the desired name
$q->set( \'cat\', $term->term_id ); // Filter the posts to only show posts from the desired category
}
}
}
});