How to let users post only once for custom post type (php / WP)?

Rate this post

I need to let users only post once for custom post ‘projects’.

The code below counts the number of the post:

$userid = get_current_user_id();
function count_user_posts_by_type($userid, $post_type = 'projects', $post_status = 'publish') {
global $wpdb; 
$query = "SELECT COUNT(*) FROM $wpdb->posts WHERE post_author = $userid AND post_type = '$post_type' AND post_status = '$post_status'"; 
$count = $wpdb->get_var($query); 
return apply_filters('get_usernumposts', $count, $userid);

And shows correct number with <?php echo count_user_posts_by_type($userid); ?>

My question: I need to combine it with add_action.
So that when the result is 0 the user can post, when the result is !=0 the user cannot post.
The code below is something that I want to implement but it doesn’t work at all and I have no idea how to combine together.
Would you please let me know how to combine codes together?

add_action( 'count-user-posts-by-type', 'count_user_posts_by_type' );
$postcount = count_user_posts_by_type($userid);
if($postcount != 0){
   return ( '' ); 
  } else{
return ( '' );

Thank you.



You can use is_user_logged_in() to check whether the current user is logged in or not. Then you can use the template_redirect hook to perform the check :

function only_post_once_redirect() 
    if( is_user_logged_in() )  {
        $userid = get_current_user_id();    //-- get the user id
        $postcount = count_user_posts_by_type( $userid );   //-- get the count

        if( $postcount != 0 ){      //-- not equal to zero
            wp_redirect( home_url( '' ) ); 
        } else{         //-- equal to zero
            wp_redirect( home_url( '' ) );


add_action( 'template_redirect', 'only_post_once_redirect' );

You may need to add some more login to it, say to check which the user is now or something like that.

Or if you want this check & redirect to happen just after the login, you could try the login_redirect hook.


I believe you have to spend some time polishing your PHP skills. Look for some basic PHP tutorials like this. You will recall everything after you spend an hour or two in those tutorials.

To answer your question(which you asked in comments), you can simply pass the second parameter as string. No need of that $post_type = part in it. Only in function definition (ie, when you define how the function should perform), you write the default values. When you make function calls, you simply pass the values as parameter. No need of the assignments in the parameters.

In short, your function call should be like this:

$postcount = count_user_posts_by_type( $userid2, 'projects' ); 

Since you’ve already mentioned the default value of the second parameter to be projects in your function definition, you can simply use this:

$postcount = count_user_posts_by_type( $userid2 ); 

Leave a Reply

Your email address will not be published.

Back to top button