Calling shortcode in wp_localize_script strips result

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.

Topic shortcode ajax ads plugins Wordpress

Category Web


While returning from the function you have to use ob_start() and ob_get_clean() then alone you can get the result in the place where you need.

ob_start():

ob_start — Turn on output buffering

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

ob_get_clean():

ob_get_clean — Get current buffer contents and delete current output buffer

ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean().

The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_CLEANABLE flag. Otherwise ob_get_clean() will not work.

Example:

function event_form()
{
  ob_start();
  include('event_form.php');// You can include or print the short-code over here
  $output = ob_get_clean();
  return $output;
}

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();
}

About

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