call shortcode in javascript

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.

Leave a Comment