Reputation: 19
Please, do not downvote... and if you need more details please ask in comments...!!!
I have a WordPress shortcode. "[something]"
. It loads perfectly if the page is loaded with this shortcode... but my problem starts here:-
I want to load different shortcode on based on different actions. my shortcode is stored in a javascript variable and now I want to load this shortcode from that variable after the Wordpress page is completely loaded...
for an example: the action like clicking a button, or like an input box... the shortcode is going to differ each time...
note: I know shortcodes work through PHP function and PHP is loaded before javascript but is there any way to complete my purpose???
here's my javascript function
function showjob() {
var intrest=document.getElementById("intrest").value;
jQuery.ajax({
method: 'POST',
url: 'jobsloader.php',
data: {
intrest: intrest,
type: 'need'
},
success: function(data)
{
// run recieved shortcode and display it in addcontainer
document.getElementById("addcontainer").innerHTML = data;
}
});
}
this is an example shortcode that might return
[sc_team style="horizontal" team="Karina Marie" columns="3"]
remember shortcode may vary on the basis of value javacript variable "interest"
Upvotes: 0
Views: 1165
Reputation: 54
You will need to use Ajax for this. You can follow the below steps
1. On JS events call an Ajax request
2. Pass the shortcode name in the request parameters like SITE_URL/wp-admin/admin-ajax.php?action=handle_shortcode&short_code_name=name_of_shortcode
3. In Ajax request handler on server use code do_shortcode('short_code_name')
4. Show the content returned by the server in the page.
In themes, function.php file add the following
add_action( 'wp_ajax_nopriv_handle_shortcode', 'handle_shortcode' );
add_action( 'wp_ajax_handle_shortcode', 'handle_shortcode' );
function handle_shortcode( ) {
$shortcode = $_REQUEST['shortcode_name'];
echo do_shortcode( $shortcode );
exit;
}
Then modify your js code like below
function showjob() {
var intrest=document.getElementById("intrest").value;
jQuery.ajax({
method: 'POST',
url: '/wp-admin/admin-ajax.php',
data: {
action: 'handle_shortcode', //You can pass other parameters to be used in shortcode
shortcode_name: intrest
},
success: function(data)
{
// run recieved shortcode and display it in addcontainer
document.getElementById("addcontainer").innerHTML = data;
}
});
}
Upvotes: 0