let's say I have a wordpress shortcode, in a page (not post), like [display id="144,145,146"] and I want to add a link in the page like "click here to sort by views", so I can click the link and a javascript function can change the shortcode, putting different ids. Is it possible?
1 Answer
This is not possible without using AJAX unless you load you load all of the different short code options beforehand.
Preloading Shortcodes:
$('#change-shortcode').on('click', function() {
$('.shortcode-container').toggleClass('hidden');
});
.hidden {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="shortcode-container">[display id="144,145,146"]</div>
<div class="shortcode-container hidden">[display id="147,148,149"]</div>
<br/><br/>
<a id="change-shortcode">Click Here</a>
Fetching Shortcodes with AJAX:
// Add the "fetch_shortcode" AJAX action.
add_action('wp_ajax_nopriv_fetch_shortcode', 'fetch_shortcode');
add_action('wp_ajax_fetch_shortcode', 'fetch_shortcode');
function fetch_shortcode() {
if (isset($_POST['ids'])) {
$ids = implode(',', $_POST['ids']);
// ob_start and ob_get_clean will prevent the shortcode from displaying and instead will return the value to the $html variable.
ob_start();
do_shortcode('[display id="' . $ids . '"]');
$html = ob_get_clean();
wp_send_json_success($html);
}
}
On the front end, you would have this:
<div id="shortcode-container">[display id="144,145,146"]</div>
<br/><br/>
<a id="change-shortcode">Click Here</a>
<script>
$('#change-shortcode').on('click', function() {
// This is where you get to use the 'fetch_shortcode' action name that you created above.
data = {
ids: [147, 148, 149],
action: 'fetch_shortcode'
};
$.ajax({
url: "<?php echo admin_url('admin-ajax.php') ?>",
method: "POST",
data: data
}).done(function(response) {
$('#shortcode-container').html(response.data);
});
});
</script>
2 Comments
Dreg Korig
and is it possible to use Ajax without editing the plugin? (which is not mine)
Noah
@DregKorig Yes, you can use Ajax without editing the plugin. See my answer above.