Question by WordPress.

Is it possible to display text on the single post page that changes depending on which tag is specified for the post. If the entry refers to a specific TAG, which is specified in the specified associative array, then the corresponding TEXT tag should be displayed. I know in WordPress there is a has_tag() function that checks if a tag is related to this has_tag() .

For example,

 if ( has_tag('TAGNAME') ) { <p>выводиться TEXT для тега TAGNAME </p> elseif ( has_tag('TAGNAME1') ) { <p>выводиться TEXT1 для тега TAGNAME1 </p> 

and so on (different tags and texts everywhere)

But how to do it programmatically? Not to write elseif constructions every time ?! Especially when there are a lot of tags. Is it possible to represent all this as an array?

  $test = array('TAGNAME' => 'TEXT', 'TAGNAME1' => 'TEXT1') 

And so that the verification of the tag through the has_tag method is has_tag , and the necessary text is displayed? But how about to do it?

Thank you in advance.

  • one
    @ user700: you wrote everything yourself! An associative array is a good idea, better than an if tree or switch. - VladD

4 answers 4

switch, case, default, break


 switch ($_GET['test']) { case 0: // if (0==$_GET['test']) { echo "test"; break; // } case 1: //} else if (1==$_GET['test']) { echo "test 1"; break; // } case 2: //} else if (2==$_GET['test']) echo "test 2"; break; // } default: //} else { echo "ignore"; break; // } } 

    Or so:

      <?php $spectags = array('tagname1' => 'Some text', 'tagname2' => 'Another text'); //наш массив особых тегов с текстом $posttags = get_the_tags(); //все теги текушего поста в массивв if ($posttags) { foreach($posttags as $tag) { //для каждого провряем, не входит ли в какую-то из категорий вывода if (array_key_exists($tag->name, $spectags)) { // или if (isset($spectags[$tag->name])) { // так, наверное, даже лучше будет echo '<p>' . $spectags[$tag->name] . '</p>'; } } } ?> 
    • Thank you, really, I thought that it was possible to do this en masse somehow, I don’t know how, for example, to create an associative array and a switch-case-echo-break pattern, and in a loop to form a code, i.e. not to fill it all yourself - user700
    • Look at this option, I do not know how optimal it is - mirus
     $tags = array('tagname' => 'tagvalue'); foreach($tags as $k => $v) { if(has_tag($k)) echo $v; } 


      Try this:

       $tag2text = array('tag1' => 'text1', 'tag2' => 'text2'); function getTextForTag($tag) { if (array_key_exists($tag, $tag2text)) return $tag2text[$tag]; // report error or return default text or whatever } function getTextsForTags($tags) { return array_map("getTextForTag", $tags); }