检查用户作者是否发帖数量?

时间:2018-11-28 作者:MLL

我有这个功能。。。

$user = wp_get_current_user();
if (( in_category(\'Locked\') ) && in_array( \'subscriber\', (array) $user->roles ) ) {
    /* Is subscriber, is in category Locked, has amount of posts */
    echo do_shortcode(\'[shortcode_name]\');

} else if (( in_category(\'Locked\') ) && in_array( \'subscriber\', (array) $user->roles ) ) {
    /* Is subscriber, is in category Locked, has NO amount of posts */
    echo \'<div id="locked">
You are subscriber without number of posts!
</div>\';

} else if ( in_category(\'Locked\') ) {
    /* Is NOT subscriber, is in category Locked, has NO amount of posts */
    echo \'<div id="locked">
Login or register pal!
</div>\';

} else { 
    /* Is NOT subscriber, is NOT in category Locked, has NO amount of posts */
    echo do_shortcode(\'[shortcode_name]\'); 
}
我需要在代码的第一部分应用“has amount of posts”或“check if user is author of numebr of posts”。。。

if (( in_category(\'Locked\') ) && in_array( \'subscriber\', (array) $user->roles ) ) && ?????
如果这种方式不行,我还有一个可能的解决方案,那就是在订阅者发布帖子数量后,自动将用户从订阅者移动到贡献者,但第一个解决方案会更好。

2 个回复
最合适的回答,由SO网友:Krzysiek Dróżdż 整理而成

我想是吧count_user_posts 是您正在寻找的;)

以下是您使用它的方式:

$user_post_count = count_user_posts( $userid , $post_type );
并返回用户在此帖子类型中撰写的已发布帖子数。

另外,如果你想要更高级的计数,get_posts_by_author_sql 可以非常方便。

SO网友:MLL

上面的家伙回答正确,但对于任何需要进一步了解的人,我也会添加完整的代码作为响应。。。

$user = wp_get_current_user();
$user_ID = get_current_user_id();
$user_post_count = count_user_posts( $user_ID );
$my_post_meta = get_post_meta($post->ID, \'shortcode_name\', true);


if (( in_category(\'Locked\') ) && in_array( \'subscriber\', (array) $user->roles ) && $user_post_count == 5 ) {
    /* Is subscriber, is in category Locked, has amount of posts */
    echo do_shortcode(\'[shortcode_name]\');

} else if (( in_category(\'Locked\') ) && in_array( \'subscriber\', (array) $user->roles ) ) {
    /* Is subscriber, is in category Locked, has NO amount of posts */
    echo \'<div id="locked">
You are subscriber without number of posts!
</div>\';
} else if (( in_category(\'Locked\') ) && in_array( \'administrator\', (array) $user->roles ) ) {
    /* Is subscriber, is in category Locked, has power */
echo do_shortcode(\'[shortcode_name]\'); 

} else if ( in_category(\'Locked\') ) {
    /* Is NOT subscriber, is in category Locked, has NO amount of posts */
    echo \'<div id="locked">
Login or register pal!
</div>\';

} else if ( ! empty ( $my_post_meta ) ) { 
    /* Post meta exist */
echo do_shortcode(\'[shortcode_name]\'); 


} else { 

    /* Is NOT subscriber, is NOT in category Locked, has NO amount of posts */
    /* Post meta NOT exist */
    echo do_shortcode(\'[shortcode_name_1]\'); 
}

结束