Eval string for wordpress “in_category” workaround outside the loop

In WordPress you can´t use “in_category” outside the loop, so I created a function that gives me all the categories my article is in and create a “is_category” if statement out of it.

I put my function in my “functions.php”:

Read More
function inCatAlt($catID){
    $allCats = get_categories('child_of='.$catID);

    $childCats = 'is_category('.$catID.') ';
    foreach($allCats as $childCat){
        $childCats.= 'or is_category('.$childCat->cat_ID.') ';
    };

    $allchildCats = trim(trim($childCats, 'or '));
    return $allchildCats;
}

and call this in my sidebar, single and so on:

echo inCatAlt(13);

which gives me this as a string back:

"is_category(13) or is_category(16) or is_category(15)"

This is exactly what I needed, but now I want to evaluate the string to use it in a if function like this:

if(eval(inCatAlt(13))){
 do something
}

But it doesn´t work.
Do I evaluate it wrong or what is the problem?
If I copy paste the output into the if function it works fine…

Related posts

Leave a Reply

1 comment

  1. I’ll answer what I think is the real question. Your proposed solution is extremely bad practice.

    Try this:

    $post_categories = wp_get_post_categories( $post_id );
    $child_categories = get_categories( array( 'child_of' => $catID ) );
    
    if( count( array_intersect( $post_categories, $child_categories ) ) > 0 )
        // The post exists in one or more of the child categories