display condition based on post term and status

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;}

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x