0

I'm trying to setup a function that writes a meta tag into the header of my site.

Namely, I've set up a color chooser input like this:

function customizer_options($wp_customize) {

    $wp_customize -> add_setting ( 'chrome_theme', array( 'default' => '' ) );
    $wp_customize -> add_control ( new WP_Customize_Color_Control ( $wp_customize, 'chrome_theme', array(
        'label' => __('Chrome theme color', 'base-theme'),
        'description' => __('Tab color in Chrome for Android', 'base-theme'),
        'section' => 'title_tagline',
        'settings' => 'chrome_theme',
    )));

add_action( 'customize_register', 'customizer_options' );

then, I print the meta tag into my page <head> with this function:

function chrome_theme_meta() {

echo '<meta name="theme-color" content="', get_theme_mod( 'chrome_theme', '' ), '">';

}

add_action('wp_head', 'chrome_theme_meta');

It works as expected, except that it prints the meta tag also when no value is set, and I'd like to prevent this.

How can I check if the chrome_theme setting is set (so, not empty), and fire the chrome_theme_meta only if this is true?

2

Adding an action will fire the function regardless, but you can add an if statement to see if the value has been set. This way the tag will not fire if the value is not set

function chrome_theme_meta() {
$chrome_theme = get_theme_mod( 'chrome_theme', '' );
  if(!empty($chrome_theme){//test to see if a value is set
    echo '<meta name="theme-color" content="', get_theme_mod( 'chrome_theme', '' ), '">';
  }
}
add_action('wp_head', 'chrome_theme_meta');

Alternately, the second (empty) parameter of get_theme_mod( 'chrome_theme', '' ) is a fallback, so you could assign a default value if the setting has not been set.

|improve this answer|||||
  • Thank you; I'm aware of the fallback option, but I want to display this only if a value is manually inserted. – Sekhemty Feb 12 '19 at 19:41
  • Ok, you can test the above code block, it will display only if a value is manually inserted. – MediaFormat Feb 12 '19 at 19:44
  • 1
    I tried your solution, but I'm getting this error Cannot use isset() on the result of an expression (you can use "null !== expression" instead) – Sekhemty Feb 12 '19 at 19:45
  • Right, silly me. Try the updated version. – MediaFormat Feb 12 '19 at 19:47
  • 1
    It worked this time. Thank you, really kind form you. – Sekhemty Feb 12 '19 at 19:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.