I am working on adding some functionality on a WordPress plugin which after a certain click needs to call on some shortcode through ajax.
What I first attempted was to call the shortcode inside of the ajax processing in my functions.php file:
add_action( 'wp_ajax_nopriv_showads', 'showads' );
function showads(){
echo do_shortcode('[myshortcode]');
wp_die();
}
Where I would move the output of the shortcode in the response of the ajax call. This shortcode did not execute at all.
So instead after some research in the “wp_localize_script” function inside of the plugin I would call the shortcode:
wp_localize_script( 'script-handle', 'ajax_object',
array('ajaxurl' => admin_url( 'admin-ajax.php' ),
'adspace' => do_shortcode( '[myshortcode]' )
));
And in the response of the ajax I would move the output of the shortcode.
The problem I’m having at the moment is that as soon as the “wp_localize_script” function is called the output of the shortcode (it should create a google ad) is all stripped.
I’d like to know if there is a way to not have the shortcode output stripped or advice if I’m trying to solve this whole thing the incorrect way.
2 Answers
Try to add ob_start(); and ob_clean(); to showads function, that might be better to not break the output.
function showads(){
ob_start();
echo do_shortcode('[myshortcode]');
$result = ob_clean();
return $result;
exit();
}