Loading shortcode with ajax

You cannot load a file directly like this:

$('.homepage__slider').load('wp-content/themes/mytheme/slider.php');

Also note that WordPress loads jQuery in noConflict mode, so the $ alias does not work.

If you load a file directly none of the WordPress functions will work. You should be using the AJAX API so that everything loads in WordPress context.

You would wrap your processing PHP is a function:

function my_ajax_shortcode_wpse_108874() {
    echo do_shortcode('[metaslider id="8302"]');
    die;
}

Hook that into the AJAX system:

add_action('wp_ajax_my_ajax_shortcode', 'my_ajax_shortcode_wpse_108874()');
add_action('wp_ajax_nopriv_my_ajax_shortcode', 'my_ajax_shortcode_wpse_108874()');

Submit your request to http://site/wp-admin/admin-ajax.php and pass my_ajax_shortcode as an argument when the Javascript makes a request.

var data = {
    action: 'my_ajax_shortcode'
};
jQuery.post(ajax_url, data, function(response) {
    // whatever you need to do; maybe nothing
});

You can set ajax_url similarly to this from the Codex:

add_action( 'admin_enqueue_scripts', 'my_enqueue' );
function my_enqueue($hook) {
    if( 'index.php' != $hook ) return;  // Only applies to dashboard panel

    wp_enqueue_script( 'ajax-script', plugins_url( '/js/my_query.js', __FILE__ ), array('jquery'));

    // in javascript, object properties are accessed as ajax_object.ajax_url, ajax_object.we_value
    wp_localize_script( 'ajax-script', 'ajax_object',
            array( 'ajax_url' => admin_url( 'admin-ajax.php' ), 'we_value' => 1234 ) );
}

Leave a Comment