Add theme-color meta tag to head?

I am using the meta tag to define browser bar color on Android and Windows phone. I want to set the theme-color based on category. This is placed in the <head> section inside my header.php file.

<?php 
$post_category  =   get_the_category()['0']->term_id;
if ($post_category == 75) {
    echo "<meta name="theme-color" content="#B7E0D2">";
} 
else {
    echo "<meta name="theme-color" content="#000000">";
}   
?>

But I am getting the white screen of death.

Once I can get that much working I have may have some other issues

  • I want to make sure whether they are posts, pages, or custom posts that this works
  • There are actually about 12 categories. Should I just have a series of else if statements, or is there a more elegant way of doing this?

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

The parser has the problem with usage of ", because it is not possible what is for PHP or for the syntax to echo.
So change them like.

    $post_category  =   get_the_category()['0']->term_id;
    if ($post_category == 75) {
        echo '<meta name="theme-color" content="#B7E0D2">';
    } else {
            echo'<meta name="theme-color" content="#000000">';
    }

In the context of your hint to see only the White Screen, read about debugging in WordPress. If you active them you get information about the problem and that helps you to solve them easier.

To your additional question about statement for the category check. If you have always a different color (string) so works that. Maybe you should use the switch/case possibility. It is more readable.

You should also work in strict mode. You verify an integer value. So set this as type, like $post_category = (int) get_the_category()['0']->term_id;. Also, the strict mode for the comparison === instead of ==.


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