WordPress.org

Ready to get started?Download WordPress

Forums

Check category outside loop (2 posts)

  1. JOYMachine
    Member
    Posted 1 year ago #

    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 :-(

  2. alchymyth
    The Sweeper & Moderator
    Posted 1 year ago #

    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() ?

Topic Closed

This topic has been closed to new replies.

About this Topic