Can I use a Shortcode output as an HTML attribute value?

Within a span, the shortcode output works:

span[sola_testimonials_count type='all']/span

Result:
span5,205/span

But as an attribute value, it doesn't get parsed:

span data-value="[sola_testimonials_count type=\'all\']"/span

Result:
span data-value="[sola_testimonials_count type=\'all\']"/span

This is a third-party plug-in, but I obviously have the code and can manipulate it. Is there a way I can get the shortcode to parse as an HTML attribute value? I'm not a Wordpress developer so forgive me if this is an obvious answer.

Many thanks!

Topic shortcode plugins Wordpress

Category Web


This is not exactly what you are asking but maybe can help to find the solution

/* this simulates your shortcode [sola_testimonials_count type='all'] */
function num_sc( $atts ) { return '5,205'; }
add_shortcode( 'num', 'num_sc' );

/* use like this [test]...[/test] to obtain <span data-value="5,205">...</span> */
function test_sc( $atts, $content = null ) {
    remove_filter( 'the_content', 'wpautop' );
    $content = apply_filters( 'the_content', '<span data-value="[num]">' . $content . '</span>' );
    add_filter( 'the_content', 'wpautop' );
    return $content;
}
add_shortcode( 'test', 'test_sc' );

Result

/* INPUT */
AAA [test]this is a test[/test] BBB
/* OUTPUT HTML */
AAA <span data-value="5,205">this is a test</span> BBB

I realize this thread is from January, but I just wanted to briefly point out that, as documented in the codex, shortcodes are allowed inside html attributes.

https://codex.wordpress.org/Shortcode_API#HTML


I am not good at Regex but do_shortcode will basically will not parse any shortcode in the attributes, this might help you out:

add_filter('the_content', function($c){
    $pattern = '/<span\s*(.*?)data-value=["\']?\[(.*?)\]["\']?\s*(.*?)>\s*(.*?)\s*<\/span>/si';
    $c = preg_replace_callback($pattern, function($c){
        return isset( $c[2] ) ? str_replace(
            $c[2],
            do_shortcode("[{$c[2]}]"),
            $c[0]
        ) : array_pop($c);
    }, $c);
    return $c;
});

About

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