WordPress.org

Support

Support » How-To and Troubleshooting » Check category outside loop

Check category outside loop

  • There are few forum posts, but I can’t seem to get what I want.
    As title says, I’m trying to check if post displayed is in certain category to add something at the bottom of that single page. Code I’m trying looks like this:

    function my_function() {
    	global $post;
    	$categories = get_the_category($post->ID);
    	if ( is_single() && $categories[0] == 'wordpress' )
    	echo ' Something here if post is single and in wordpress category';
    }

    Also tried like this, it does make more sense, but still no luck

    function my_function() {
    	global $post;
    	foreach(get_the_category($post->ID) as $category)
    	if ( is_single() && $category->name == 'wordpress' )
    	echo ' Something here if post is single and is in wordpress category';
    }

    In both cases it echoes on both archive and single pages, and does so for all categories 🙁

Viewing 1 replies (of 1 total)
  • Moderator Michael

    @alchymyth

    I tried the second code (with adding <?php my_function(); ?> in footer.php) and it worked as expected;

    where exactly did you add the <?php my_function(); ?> code?

    does your site have any custom queries which are not properly reset with either wp_reset_query() or wp_reset_postdata() ?

Viewing 1 replies (of 1 total)
  • The topic ‘Check category outside loop’ is closed to new replies.