• Resolved lezlyprime

    (@lezlyprime)


    I’m trying to write a loop that gets all users & if the user has posts, list the post titles. I’d also like to get a count of users.

    Code:

    <?php
    $args = array(
    	'orderby' => display_name
    );
    // The Query
    $user_query = new WP_User_Query( $args );
    $x = $total-users; //returns 0
    echo '<p>Total users: ' . $x . '</p>';
    // Loop
    if ( ! empty( $user_query->results ) ) {
    	echo '<p>Number of users: ' . count($user_query) . '</p>'; //returns 1
    		foreach ( $user_query->results as $user ) {
    			echo '<p>User name: ' . $user->first_name . '</p>';
    			$args4 = array (
    				'author_name' => $user->display_name,
    				'orderby' => 'title'
    			);
    			//The Query
    			$the_query4 = new WP_Query( $args4 );
    			//The Loop
    			if ( $the_query4->have_posts() ) {
    				echo '<ul>';
    				while ( $the_query4->have_posts() ) {
    					$the_query4->the_post();
    					echo '<li>' . get_the_title() . '</li>';
    			}
    			echo '</ul><br />';
    			} else {
    				echo '<p>No posts were found for ' . $user->display_name . '</p>';
    			}
    		}
    } else {
    	echo '<p>No users were found.</p>';
    }
    ?>

    Output:

    Total users: 0

    Number of users: 1

    User name: Booyah

    Booyah’s post

    User name: Clea

    String Theory

    User name: Lezly

    You Are Here
    Using Time Travel to Manage Your Time
    Politics 101
    HAL
    Candidates? What candidates?

    User name: Zoe

    No posts were found for Zoe Travertine

    ===========

    Problem is, Zoe has five published posts, but my code isn’t getting those. What am I missing?

Viewing 2 replies - 1 through 2 (of 2 total)
  • total_users is a property of the user_query object. Reference it like this: $x = $user_query->total-users;

    Similarly, the number of users is a count of the results array: echo '<p>Number of users: ' . count($user_query->results) . '</p>';

    Finally, the author_name parameter should be the user_nicename instead of display_name:

    'author_name' => $user->user_nicename,
    Thread Starter lezlyprime

    (@lezlyprime)

    That fixed it right up! Thank you!

Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Nested Loop Issues’ is closed to new replies.