mercredi 19 février 2020

Wordpress - show shortcode if user has posts

I've created a shortcode [my-books] that shows up only if the logged in users has submitted 1 or more posts in the 'books' custom post type.

If the user has submitted a post in this post type, then the shortcode returns a button to the 'My Books' dashboard.

Here is my code:

<?php
function user_has_books($user_id) {
  $result = new WP_Query(array(
    'author'=>$user_id,
    'post_type'=>'books',
    'post_status' =>'any, trash, auto-draft',
    'posts_per_page'=>1,
  ));
  return (count($result->posts)!=0);
}

add_shortcode( 'my-books' , 'my_book_listings_func' );
function my_book_listings_func( $atts ) {

  $user = wp_get_current_user();
  $mybooksbutton = '<a class="button" href="'. site_url() . '/listings/books/">My Books</a>';

  if ($user->ID)
    if (user_has_books($user->ID))
      return $mybooksbutton;
}
?>

The code is based on this question answered by @MikeSchinkel

My code works perfectly fine, but since the answer dates back to 2010 - 2011, I'm trying to find out if there is another, better, more efficient way to do this?

(And also, do I need endif; to close the if(user_has_books($user->ID)) call? It seems to work fine without it.)

Aucun commentaire:

Enregistrer un commentaire