Support » Fixing WordPress » Add data attribute to image in post

  • Hi,

    I’ve been researching how to automatically add a data attribute on each image in my post.

    I’m not sure if I should use the functions.php file or if I should instead use one of my JavaScript file.

    Either, any code snippet would be really helpful.

    Thank you all!

Viewing 3 replies - 1 through 3 (of 3 total)
  • I believe either file should work.
    But if you’re adding in functions.php, make sure to add a condition so it won’t run to all pages.

    Example:

    function custom_js_script() {
    if (is_single()) :
    ?>
    // Your JS code here...
    <?php
    endif;
    }
    add_action('wp_footer', 'custom_js_script');
    
    Thread Starter gmessage

    (@gmessage)

    Hi

    Thank you for your reply.

    Following your answer, this is the code I’ve added but it’s not working:

    function custom_js_script() {
    		if (is_single()) :
    		?>
    		$('img').attr("data-action","zoom");
    		<?php
    		endif;
    	}
    	add_action('wp_footer', 'custom_js_script');

    You have to wrap your JS script with <script>…</script>

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Add data attribute to image in post’ is closed to new replies.