-1

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

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;
} );
  • I'm happy to discuss the code or attempt a different answer if whomever downvoted has any comments. – phatskat May 2 at 1:36
  • Wow thank you, Sorry but by being a beginner I have no idea where to insert this code. And it would be important for me that not registered users can still see the content. Thank you ver much! – noahlayer May 2 at 16:04
  • You could put this in your theme's functions.php. Also, since the user check passes (! $user_id), unregistered users should have no problem. – phatskat May 8 at 7:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.