display condition based on post term and status

The question:

im creating display conditions that i will apply to a series of widgets on the single post template – essentially im trying to only get one of the widgets to display if the condition is met.

in this case – the condition is if the current post term is “term a” and the post status is “draft” or “pending”.

ill apply this code to each widget but change the term that it relates to.

I cant workout what im doing wrong.

Current structure

  • post type = “finals”
  • taxonomy = “des_num”
  • terms = “des_1”, “des_2” etc etc

ive tried

$terms = get_the_terms( $post, 'mytaxonomy' )
$term = array_pop($terms)

Full Code below

global $post;

$stat = get_post_status($post);

$terms = wp_get_post_terms($post);

$term = array('tax_query' => array(
    array(
    //'field' => 'des-1',
    'terms' => $terms
            )
        )
    );

$cstat = false;
$cterm = false;

if ($stat==='draft'){
$cstat=true;}

elseif ($stat==='pending'){
$cstat=true;}

if ($term==='des-1'){
$cterm=true;}

if($cstat && $cterm){
return true;}


The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

You are populating the $term variable with a multidimensional array, but type-and-value checking it (===) against a string.

Second, you say terms are 'des_1' and 'des_1' (with underscore), but are checking for 'des-1' (with dash).

wp_get_post_terms will return an array of term objects, so you should might be better of with has_term() for checking if the term is used on the post.

Tip: this might be better readable (and shorter):

$cstat = in_array( $stat, ["draft", "pending"] )
$cterm = has_term( 'des_1', 'des_num', $post );
return $cstat && $cterm;

or even shorter (but less readable):

return in_array( $stat, ["draft", "pending"] ) && has_term( 'des_1', 'des_num', $post );


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment