How execute shortcode with javascript

Suppose to have this shortcode:

[spu-close class="" text="" align=""]

I want to show this short code when I click on a button this is my html:

 <input class="button b" onclick="openFile(link);"  type="button" value="download" />

and this is my js file:

function openFile(link){
//I want do something like this
    do_shortcode('[spu-close class="" text="" align=""]', false );
   //  

}

I don’t know how I can do this, anyone can help me?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

to execute “ShortCode” which server side-> wordpress ->php ,by JavaScript which client side you will need use AJAX!

you can use some thing like:

1-in your enqueued .js file :

jQuery(document).ready(function($) {
    $('.buttonClass').on('click', function() {
        $.ajax({
            url: Param.doShortCode,
            type: 'POST',
            data: {
                action: 'handle_ajax_shortcode',
            },
            success: function() {
                //do something on success 
            },
            error: function() {
                //do something on error
            }
        })
    })
});

2- in php file :

//localize your script
$Param = array(

  'doShortCode'=>admin_url( 'admin-ajax.php?action=handle_ajax_shortcode' ),

);
wp_localize_script('handle_ajax_shortcode','Param', $Param);

//executes for users that are not logged in.
add_action( 'wp_ajax_nopriv_handle_ajax_shortcode', 'handle_ajax_shortcode' );
//executes for users that are logged in.
add_action( 'wp_ajax_handle_ajax_shortcode', 'handle_ajax_shortcode' );


function handle_ajax_shortcode(){
  //put whatever you want to be execute when JavaScript event is triggered
  do_shortcode( string $content, bool $ignore_html = false )
  // Don't forget to stop execution afterward.
  wp_die();

}

for more information you can check Link1 & Link2 & Link3


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

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x