WordPress code that I could not fully understand

Working on my first WordPress theme, I created a page template for authors based on this tutorial which is itself based on the twenty-fourteen theme.

What I could not understand is this :

$post_count = count_user_posts( $contributor_id );

From this code example.

<?php
// Output the authors list.
$contributor_ids = get_users( array(
  'fields'  => 'ID',
  'orderby' => 'post_count',
  'order'   => 'DESC',
  'who'     => 'authors',
));

foreach ( $contributor_ids as $contributor_id ) :
$post_count = count_user_posts( $contributor_id );
  // Move on if user has not published a post (yet).
  if ( ! $post_count ) {
    continue;
  }
?>

I have checked the Codex for count_user_posts( ) but it appears that the code is not aligned with the documentation as the output of the foreach loop $contributor_id is not only the β€œID” but also β€œpost_count” ,"desc" and "authors".

These are supposed to be the second parameter which is optional is as the Codex specifies below:

$post_type
(array|string) (Optional) Single post type or array of post types to count the number of posts for.
Default value: β€˜post’


So how the values of "post_count" ,"desc" and β€œauthors”. fit in the Codex documentation.

This is quite a specific question
I would ask this on

Wordpress development

at Stack Exchange

1 Like

I did that, got an answer and a comment, I still need to do more research and testing. Possibly ask another question related to PHP.
Here is a link of my question in Stack Exchange

Hey @FakhriAz

From my reading it is returning an object for each WordPress user just as it is supposed to be doing.

The code

if ( ! $post_count ) {
    continue;
  }

is only testing if $post_count is empty, not if it contains only the ID. An object here is just fine as far as this test goes.

However, if after this test you want to add your own code that requires the actual ID then you have to extract the ID from the user object using plain old PHP.

So,

get_avatar( $contributor_id->userID_reference, 132 );

where userID_reference would be replaced by whatever the ID is called inside the object.

1 Like