admin管理员组

文章数量:1430812

I want to build a blog where every user is allowed to post something (only text) after a successful registration. However, a user should only access other contributions from users who have uploaded at least one contribution themselves. Because I use the Plugin Ultimate Member a later change of the Roles is not possible. Therefore it would be easiest if the whole blog would not be accessible anymore, if the user has not yet uploaded anything. But how can I realize this?

Please answer as soon as possible

Greetings Noah

I want to build a blog where every user is allowed to post something (only text) after a successful registration. However, a user should only access other contributions from users who have uploaded at least one contribution themselves. Because I use the Plugin Ultimate Member a later change of the Roles is not possible. Therefore it would be easiest if the whole blog would not be accessible anymore, if the user has not yet uploaded anything. But how can I realize this?

Please answer as soon as possible

Greetings Noah

Share Improve this question asked Apr 29, 2019 at 18:49 noahnoah 1
Add a comment  | 

1 Answer 1

Reset to default 0

This code will boot out a user if they haven't authored a post. For the purposes of this example, posts with a status of publish are considered "authored".

I've added some comments in the code to walk you through what's going on - please reach out to me if you have any questions.

<?php

// Ensure non-published users can't see what's going on.
add_action( 'init', function() {
    // Don't run in the admin area.
    if ( is_admin() ) {
        return;
    }

    // Only display this on "single" pages.
    if ( ! is_single() ) {
        return;
    }

    $user_id = get_current_user_id();

    // The user isn't a user, bail.
    if ( ! $user_id ) {
        return;
    }

    $query = <<<SQL
SELECT
    COUNT(*) published
FROM
    {$GLOBALS['wpdb']->posts}
WHERE
    post_author = %d
AND
    post_type = %s
AND
    post_status = 'publish'
SQL;

    $result = $GLOBALS['wpdb']->get_results(
        $GLOBALS['wpdb']->prepare(
            $query,
            $user_id,
            'post' // Replace this with your Custom Post Type, if you're not using Post.
        )
    );

    // The current user has author posts, bail.
    if ( ! empty( $result ) ) {
        return;
    }

    // Handle code to kick people out.
    wp_safe_redirect( '/error-page/' );
    exit;
} );

本文标签: phpForbid certain users to access a specific page