xyz
xyz

Reputation: 2300

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?

I can not find anything on how to do this

Edit: My apologizes

Yes Shortcode means wordpress shortcode

Upvotes: 1

Views: 3121

Answers (3)

aleks1217
aleks1217

Reputation: 87

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>

Upvotes: 1

Arka
Arka

Reputation: 591

==== 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]'); ?>

Upvotes: 1

Suman Bogati
Suman Bogati

Reputation: 6349

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>

Upvotes: 0

Related Questions