How to Check if The Current User is The Post Author in WordPress

[ad_1]

While working on a WooCommerce project recently, my client asked me if there is a way to show a message to seller on their own product items. A simple message like “you are the seller of this item” if the product page is previewed by the seller itself. Typically WooCommerce is a plugin which essentially creates a custom post type for listing products and each product item is like a single WordPress post. So typically I need to find a way to show message if current user and the post author. That makes this task as easy as eating a piece of cake, although finding the right file and exact spot in WooCommerce plugin to insert the message for seller, is bit of a challenge.

In order to insert message for seller (post author) only, I had to create an if statement that checks if the current user is the author of the post or not. So first I had to get the user id of current user by WordPress function get_currentuserinfo() and then I need to match it with the id of current post author. If this condition returns true and both id matches, WordPress prints the message “you are the seller of this item!” for the seller.

So here is the code to achieve this. You can simply use this code in any theme PHP file and to leave personalized messages for post authors.

<?php
    // check if current user is the post author
    global $current_user;
    get_currentuserinfo();
    
    if (is_user_logged_in() && $current_user->ID == $post->post_author)  {
        echo 'You are the seller of this item!';
    }
?>

That’s it!

[ad_2]

Leave a Reply

Random Post Selection ::

Recent Posts

Unlock Unlimited Downloads