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?
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?
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.