Execute a short code on a image click?

Not sure to post here or webmasters, I apologize if I got wrong.

Does anyone know of a way to execute a short code on a image click?

Read More

I can not find anything on how to do this

Edit: My apologizes

Yes Shortcode means wordpress shortcode

Related posts

Leave a Reply

3 comments

  1. ==== Template page ====

    <script> 
    function executeShortCode() {
       var url="<?php echo get_template_directory_uri(); ?>/yourAjaxPage.php";
       jQuery.post(url,function(data){
       console.log(data);
       });
    
    
    }
    </script>
    

    ==== Ajax page ====

    //yourAjaxPage.php
    <?php echo do_shortcode('[yourshortcode]'); ?>
    
  2. Because I just couldn’t find answers online to my own question on this, I thought I’d post my solution. Using wp_localize_script to load my shortcodes, here is my example:

    // PHP (in functions.php)
    <?php
    
    add_action( 'wp_enqueue_scripts', 'custom_add_scripts' );
    function custom_add_scripts() {
    wp_register_script( 'my_new_js_callname', plugins_url( '/js/filename.js' , __FILE__ ), array(), '1.0.0', true );
    wp_enqueue_script( 'my_new_js_callname' );
    }
    
    
    add_action ('template_hook', 'custom_function_name');
    function custom_function_name() {
    
    // Because I used if/else statements in my JS, I loaded individual IDs into the array.
    
    $examplea = do_shortcode('[add_to_cart id="118"]');
    $exampleb = do_shortcode('[add_to_cart id="119"]');
    $examplec = do_shortcode('[add_to_cart id="120"]');
    
    $array = array( 
                    'examplea' => $examplea,
                    'exampleb' => $exampleb,
                    'examplec' => $examplec,
            );
    
    
    wp_localize_script( 'my_new_js_callname', 'callword', $array );
    

    Then, on image click or any other JS event you are using do:

    // JS (in filename.js)
    <script>
    document.getElementById('myImg').onclick = function (){
        $("#show").html( callword.examplea );
      }
    </script>
    

    Then the shortcode is executed on my HTML page in there area where I have:

    <div id="show"></div>
    
  3. Get image element by it’s id and attach the handler at onclick event something like

    html

    <img id="myImg" src="" />
    

    JS

    <script>
     document.getElementById('myImg').onclick = function (){
         //execute your short code here.
      }
    </script>