Get author ID of a post in wordpress

Get author ID of a post in wordpress

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Retrieving Author ID in WordPress Loops

You are attempting to build a data visualization where the chart's labels and counts depend on the specific user currently viewing their profile page. The core challenge here is bridging the gap between PHP, which executes server-side, and JavaScript, which renders client-side. In your current implementation, you have correctly identified that $user_id needs to be populated before being injected into the pieData array. However, the variable name AUTHOR-ID in your script tag is a placeholder that will break your code immediately; it must be replaced with actual data retrieved from WordPress.

To obtain the author ID dynamically on an author archive page, you should rely on the global $authordata object or the global $post object. When WordPress loads an author page, it sets up these globals based on the query parameters. The most robust approach is to check if the global post data exists and extract the author from there. This works because every single post in a loop has an associated post_author, which corresponds to the ID of the user who wrote it.

Here is how you can modify your PHP block to capture that value:

// Option 1: Using the global $post object (Recommended)
global $post;
if ($post && isset($post->post_author)) {
    $user_id = intval($post->post_author);
} else {
    // Fallback logic or error handling if not on a post loop
    $user_id = 0; 
}

// Option 2: Using the dedicated author data global (If using WP_Query)
global $authordata;
if ($authordata && isset($authordata->ID)) {
    $user_id = intval($authordata->ID);
} else {
    // Fallback logic
    $user_id = 0; 
}

In your specific case, since you are looping through categories to count posts for that specific user, using $post->post_author is generally safer. It ensures you are pulling the ID of the author associated with the current page context, regardless of whether the global $authordata object was explicitly initialized by a custom query or the standard get_user_by('slug') logic often found in themes.

Once you have resolved the PHP variable, the next critical step is securing the data transfer to JavaScript. WordPress functions like get_terms() and count(get_posts()) return data that needs to be output as JSON. In your current code snippet, you are echoing strings directly inside a JavaScript array literal (echo "{ value: ... }",). While this works for simple cases, it is brittle. If any of the variables contain quotes or special characters, the generated HTML will break, causing the Chart.js library to fail parsing the data.

The standard pattern in WordPress development is to use json_encode() on your PHP array before echoing it into the script. This ensures proper escaping and formatting.

<script type="text/javascript">
    var pieData = [
        <?php
            global $post;
            if ($post && isset($post->post_author)) {
                $user_id = intval($post->post_author);
            } else {
                $user_id = 0;
            }

            /* Get all categories */
            $categories = get_terms( 'category', array('orderby' => 'count', 'hide_empty' => 0) );

            /* Loop for each category to count the posts of the user */
            foreach($categories as $category) {
                // Generate a random hex color
                $rand = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f');
                $color = '#';
                for($i=0; $i<6; $i++) {
                    $color .= $rand[rand(0, 15)];
                }

                $cat_name = $category->name;
                $cat_id = $category->term_id;
                
                // Ensure count is an integer for JSON safety
                $post_count = count(get_posts(array('cat' => $cat_id, 'post_author' => $user_id)));

                echo "{\n";
                echo "    value: $post_count,\n";
                echo "    color: '$color',\n";
                echo "    label: $user_id\n";
                echo "},";
            }
        ?>
    ];

    var myPie = new Chart(document.getElementById("piec").getContext("2d")).Pie(pieData);
</script>

There is a subtle trade-off to consider with get_posts(). It defaults to returning the full post object, which includes content and meta data. If you are counting items in a loop like this, it is more efficient to use 'fields' => 'ids' in your get_posts() call or simply rely on the count function directly without fetching the objects if only the number matters. However, since you are using count(), the performance difference is negligible for most sites, but keeping the query lightweight is always a good habit.

If you find yourself needing to move beyond standard WordPress loops and require more complex data aggregation or API-like endpoints, you might consider building a custom REST endpoint. For projects that need tighter integration with modern PHP frameworks, exploring how Laravel handles user authentication and data retrieval can offer alternative architectural patterns, as detailed in resources like https://laravelcompany.com. However, for vanilla WordPress themes, sticking to the global variables and json_encode remains the most maintainable path.

Our network