call shortcode in javascript

The question:

I want to display a shortcode through jquery after the DOM is loaded:

This is how I call the shortcode: <?php echo do_shortcode('[plugin]'); ?>

Now, my question is how can I call that shortcode inside a jquery function, because my website is based on jquery/ ajax calls?
Thanks!

The Solutions:

Below are the methods you can try. The first solution is probably the best. Try others if the first one doesn’t work. Senior developers aren’t just copying/pasting – they read the methods carefully & apply them wisely to each case.

Method 1

Javascript code is running in the user’s browser and not on your server (where your wordpress content resides). You could use ajax to call the function which the shortcode is pointing to.

Here is how I handle AJAX calls with WordPress:

1) I use a jQuery ajax function to call the wp-admin/ajax.php

jQuery.ajax({
    url: yourSiteUrl + "/wp-admin/admin-ajax.php",
    dataType: 'json',
    data: {
       'action':'your_ajax',
       'fn':'run_shortcode_function',
       'some_needed_value': jQuery('#input_for_needed_value').val()
       },
    success: function(results){
        //do something with the results of the shortcode to the DOM
    },
    error: function(errorThrown){console.log(errorThrown);}
});// end of ajax

2) This PHP code is located in the functions.php file of your theme or in a custom plugin:

//this is wordpress ajax that can work in front-end and admin areas
add_action('wp_ajax_nopriv_your_ajax', 'your_ajax_function');
add_action('wp_ajax_your_ajax', 'your_ajax_function');
function your_ajax_function(){
     // the first part is a SWTICHBOARD that fires specific functions according to the value of Query Variable 'fn'

     switch($_REQUEST['fn']){
        case 'run_shortcode_function':
           $output = your_ajax_shortcode_function($_REQUEST['some_needed_value']);
           break;
        case 'some_other_function_you_want_to_perform':   
           $output = some_other_function($_REQUEST['first_name'],$_REQUEST['last_name']);
            break;
        default:
          $output = 'No function specified.';
        break;

     }

   // at this point, $output contains some sort of data that you want back
   // Now, convert $output to JSON and echo it to the browser
   // That way, we can recapture it with jQuery and run our success function

          $output=json_encode($output);
         if(is_array($output)){
        print_r($output);
         }
         else{
        echo $output;
         }
         die;

}
your_ajax_shortcode_function($some_needed_value){
     return the_specific_function_that_the_shortcode_was_pointing_to($some_needed_value);
}   

I hope this points you in the right direction.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Comment