I need to check if Current user is Author to Custom Post Type

I want to write a conditional statement (in pseudo below to explain)

IF current logged in user is 'Author' to a custom-post-type called 'farmers' {
// Do something
} else {
// Do something else
}

My code effort so far is

Read More
<?php
// Global variable for current user ID
$user_ID;

// Create a new WP query object           
$my_query = new WP_Query( array(
'post_type' => 'farmers',
'author' => $user_ID
));

// Get all the current user posts from the query object
$posts = $my_query->posts;

IF $posts = 0 {
// Do something
} else {
// Do Something else
} ?>

User can have the role “Author” in the system, but not necessarily have any posts. So I need to check the condition that this Author actually has a post. I am just not sure how to write that IF statement at the end of the code and looking for some help.

Thanks

Related posts

Leave a Reply

3 comments

  1. For anyone looking to check a specific post you can check if

    get_current_user_id() == get_post($your_post_id)->post_author
    

    Or in the WordPress loop you can check if

    get_current_user_id() == $post->post_author
    

    And for completeness sake, the following answers the original question. This checks if the current user is the author of any post belonging to a custom post type; in this case farmers

    $my_query = new WP_Query( array(
      'post_type' => 'farmers',
      'author' => get_current_user_id()
    ));
    
    if ( $my_query->have_posts() ) {
      // Do something
    } else {
      // Do Something else
    }
    
  2. Use something like this

    $query="select * from posts where type='farmers'";
    $result=mysql_query($query);
    $valid=false;
    if(mysql_num_rows($result)>0){
    $valid=true;
    }
    
    
    if($_SESSION["id"]==$posts["id"]){
    //your code
    }else{
    //your code
    }
    

    or

    if(mysql_num_rows($posts)>0){
    // user have post
     }