How to count current user’s pages?

There are a lot of answers on how to count users posts by using:

<?php
    if ( is_user_logged_in() ) {
        global $wpdb;
    $user = wp_get_current_user();
    $where = get_posts_by_author_sql( 'page', true, $user->ID );
    $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" ); ?>

//option 1
<h2>Hey <?php echo $current_user->display_name ?>, check your page here: {page title with link to page} </h2>

<?php } else { ?>
//option 2
<h2>Welcome <?php echo $current_user->display_name ?>, etc.. text with tags etc.</h2>

<?php } } else { ?>
//option 3
<h2>text with tags etc.</h2>

<?php } ?>

But since users can also create pages, how does one get the count of current user’s pages in a similar situation as the code above?

Related posts

Leave a Reply

1 comment

  1. Look what count_user_posts() does inside and change the post type parameter:

    global $wpdb;
    // 'page' is the important part here
    $where = get_posts_by_author_sql('page', true, $userid);
    $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
    

    Then you change your snippet to:

    global $wpdb;
    $user = wp_get_current_user();
    $where = get_posts_by_author_sql( 'page', true, $user->ID );
    $count = $wpdb->get_var( "SELECT COUNT(*) FROM $wpdb->posts $where" );
    
    if ( $count >= 1 ) {
    
        // echo your text snippet
    
    } else {
    
        // echo your form
    
    }