4

Is there a way to output the default value of a wp_customize text field type using the echo get_theme_mod (); without actually going in the Theme Customizer, modifying something and then saving it?

I just read on another stackexchange question that the get_theme_mod will only show something after you save it in Theme Customizer. Not being able to output the default value of a wp_customize setting seems to defy the purpose of using a default value.

So, back to the question: is there a way to automatically display the default value of a wp_customize setting in front-end?

7

Sadly not - all your customize controls are hooked onto customize_register, so they'll only ever come into play when customising the theme for the first time.

get_theme_mod() takes a second argument for a "default" value - yes, it means two instances of data in your code, but it's a half-solution.

I guess a more DRY approach would be a coupling of globals & helper functions:

$my_theme_defaults = array(
    'foo' => 'bar',
    'baz' => 'boo',
);

function my_theme_customize( $wp_customize ) {
    global $my_theme_defaults;

    $wp_customize->add_setting(
        'foo',
        array(
            'default' => $my_theme_defaults['foo'],
        )
    );  
}

function my_theme_mod( $name ) {
    global $my_theme_defaults;

    echo get_theme_mod( $name, $my_theme_defaults[ $name ] );
}
  • That would mean you'll have $my_theme_defaults as global variable, and also put side effects within a file that should contains only functions. – guido Apr 25 '18 at 12:45
  • I'm just demonstrating the concept. You could use an array constant (PHP 5.6+) or a class (properties & methods), or you could refactor my_theme_mod to encapsulate the defaults & a second parameter flag for passing them straight back. – TheDeadMedic Apr 25 '18 at 12:53
3

Actually you can output a default value. The correct way is to set a default for your mod like this:

echo get_theme_mod( 'MOD_ID', 'YOUR DEFAULT OUTPUT' );
  • This does not answer the question. – TheDeadMedic Apr 26 '18 at 11:39

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.