0

I have a shortcode, which contains the post title. This shortcode loads in the frontend the content from a post. Thats works fine:

function title_content($atts, $content = null ) {
   global $wpdb;
   $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s",$content));
   $getpost = get_post($post_id);
   return $getpost->post_content;
}

add_shortcode( 'content', 'title_content');

But I have in different categories posts with the same post title. So this loads sometimes the wrong content, because I don't want to use the post id or post slug in the shortcode.

I just want the the contents from posts with the right category (name "blog"), so I have no conflicts with the same post title anymore.

Has someone an idea, how I can solve this?

1

You can use the function in_category to test if a post is in a certain category. It takes one or more categories and the post as input. So you may differentiate your function like this:

function title_content($atts, $content = null ) {
   global $wpdb;
   $post_id = $wpdb->get_var($wpdb->prepare("SELECT ID FROM {$wpdb->posts} WHERE post_title = %s",$content));
   $getpost = get_post($post_id);
   if (in_category('blog',$getpost)) {
       return $getpost->post_content;
       }
   else {
       ... do something else ...
       }
}
  • Thank you cjbj. This fetch the current category and not the category from the post. I think i must build an other way to fetch the content. So I use the slug with post_name instead until I have it. – Tada Jul 1 '16 at 10:19
  • 1
    in_category gets the category of the current post only if no post object or id is passed. Else you get the category of the specified post, even if it is not the current post. – cjbj Jul 1 '16 at 10:27

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.