Display text if current user has written 1 or more posts in a custom post type

I am trying to display different things to new users that have not created a post versus users who have created a post.

I tried this, but it did not work for custom post types (only normal posts) and it does not account for drafts or pending posts:

<?php if (count_user_posts(1)>=1) { blah blah blah } else {Welcome, blah blah blah }; ?>

Related posts

Leave a Reply

3 comments

  1. Hi @Carson:

    A simple function to address what you are asking for might be the function yoursite_user_has_posts() which leverages the built in WP_Query class:

    function yoursite_user_has_posts($user_id) {
      $result = new WP_Query(array(
        'author'=>$user_id,
        'post_type'=>'any',
        'post_status'=>'publish',
        'posts_per_page'=>1,
      ));
      return (count($result->posts)!=0);
    }
    

    You can then call it from your theme like this:

    <?php
    $user = wp_get_current_user();
    if ($user->ID)
      if (yoursite_user_has_posts($user->ID))
        echo 'Thank you for writing!';
      else
        echo 'Get Writing!';
    ?>
    
  2. see Best Collection of Code for your functions.php file:

    function atom_count($user_id, $what_to_count = 'post') {
      global $wpdb;    
      $where = $what_to_count == 'comment' ? "WHERE comment_approved = 1 AND user_id = {$user_id}" : get_posts_by_author_sql($what_to_count, TRUE, $user_id);
      $from = "FROM ".(($what_to_count == 'comment') ? $wpdb->comments : $wpdb->posts);    
      $count = $wpdb->get_var($wpdb->prepare("SELECT COUNT(*) {$from} {$where}"));
      return $count;
    }
    

    if you want this to count all posts, regardless of the type, and status, change get_posts_by_author_sql() with "WHERE post_author = '{$user_id}'"

    didn’t test that, but it should work…

  3. This should do what you want…

    <?php if ( 0 == count_user_posts( get_current_user_id(), "CUSTOMPOSTTYPE" ) && is_user_logged_in() ) { ?>
       Do something if they have no posts
    <?php } elseif ( 0 !== count_user_posts( get_current_user_id(), "CUSTOMPOSTTYPE" ) && is_user_logged_in() ) { ?>    
       Do something else if they do have a post         
    <?php } ?>