How to allow certain PHP functions when using sanitize_callback in the word press customizer

Hi I am making my own theme in WordPress and setting up some customizer options and I have one for the text in my footer but I would like to still use ? echo date('Y');? in the footer to dynamically change the date so I don't have to keep going in and doing it manually but the sanitizer call-back obviously blocks it is there a way to still be able use that php function in the sanitizer here is my code what I'm using

customizer.php

$wp_customize- add_setting('set_copyright', array(
'type' = 'theme_mod',
'default' = Copyright copy; ?php echo date('Y'); ? . All Rights Reserved,
'sanitize_callback' = 'esc_attr'
));

 $wp_customize- add_control('ctrl_copyright', array(
'label' = 'Copyright Information',
'description' = 'Enter your copyright info',
'section' = 'sec_footer',
'settings' = 'set_copyright',
'type' = 'text',

));

/////

 footer.php

 footer class=main-footer
div class=copy pt-3 pb-3
    div class=container
        div class=row
            div class=col text-center 
                p class=small m-0?php echo do_shortcode( get_theme_mod( 'set_copyright', Copyright copy; ?php echo date('Y'); ? . All Rights Reserved) ) ; ?/p
            /div
        /div
    /div
/div

Topic theme-customizer sanitization theme-development Wordpress

Category Web


This sort of theme mod is only capable of conveying a string into the markup regardless of any sanitization callback - any PHP included within the string will never be interpreted by the PHP engine, short of running the output through eval() which would be extremely dangerous and likely result in the theme failing review for any marketplace.

In this case, since you're running the mod value through shortcodes anyway, I think it would be easiest and provide the best end-user experience to just include a shortcode which outputs the current year, or as a wrapper around the wp_date() function:

function wpse406257_date( $atts, $content ) {
  $atts = shortcode_atts( [
    'format'   => 'F j, Y',
    'timezone' => null,
  ], $atts, 'date' );

  $timestamp = !empty( $content ) ? strtotime( $content ) : null;

  return wp_date( $atts['format'], $timestamp, $atts['timezone'] );
}

add_shortcode( 'date', 'wpse406257_date' );
//...
'default' => 'Copyright © [date format="Y"] . All Rights Reserved'
//...

You could achieve a similar effect without shortcodes by running the string output through str_replace() and swapping out custom placeholders such as {year}.

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.