I'm working on a gallery of sorts in Wordpress right now and I'm a bit stuck.
The idea is to change the post thumbnail on hover. The replacement image will be coming from a field generated by the Advanced Custom Fields plugin.
Now, I've managed to pull in both URLs and stored them in variables, but I still won't work. It works on a standalone CodePen, but not on the Wordpress site itself.
Wordpress code:
jQuery(document).ready(function() {
var firstthumb = '<?php echo the_post_thumbnail_url(); ?>';
var secondthumb = '<?php if( get_field('multiple_thumbs') ): ?><?php echo the_field('multiple_thumbs'); ?><?php endif; ?>';
jQuery('.member-thumbnail').hover(function() {
jQuery('.attachment-thumbnail').attr('src', secondthumb);
}, function() {
jQuery('.attachment-thumbnail').attr('src', firstthumb);
});
});
And it returns this:
jQuery(document).ready(function() {
var firstthumb = 'http://www.cozeh.com/wp2/wp-content/uploads/2016/01/pic2.png';
var secondthumb = 'http://www.cozeh.com/wp2/wp-content/uploads/2016/01/multiple2.png';
jQuery('.member-thumbnail').hover(function() {
jQuery('.attachment-thumbnail').attr("src", secondthumb);
}, function() {
jQuery('.attachment-thumbnail').attr("src", firstthumb);
});
});
Here's a link to the beta version. And here's the codepen.
Would appreciate any explanation as to why this doesn't work or if you have any alternative solutions.
Edit: Updated code
The problem is that in the codepen you are not wrapping the img
in an a
tag, but you are doing it on the WordPress site. So to make it work in wordpress you need to remove the link that is wrapping the image or change you jQuery code, replacing this code:
jQuery('.member-thumbnail').hover(function() {
...
});
To this one:
jQuery('.member-thumbnail a').hover(function() {
...
});
Marking as solved.
Turns out it wasn't a script issue after all.
WP 4.4.+ was appending srcset
to the images as part of their move to make all images responsive. The img src
was changing but not the srcset
hence the problem.
Found a workaround to disabling the responsive images for now.
And I edited the code so it only affects one of the thumbnails, not every single one.
<?php if ( has_post_thumbnail() ) { ?>
<div class="member-<?php the_ID(); ?>-thumbnail">
<a href="#" data-toggle="modal" data-target="#post-<?php the_ID(); ?>"><?php the_post_thumbnail('thumbnail'); ?></a>
</div>
<script type="text/javascript">
jQuery(document).ready(function() {
var firstthumb = '<?php the_post_thumbnail_url(); ?>';
var secondthumb = '<?php if( get_field('multiple_thumbs') ): ?><?php echo the_field('multiple_thumbs'); ?><?php endif; ?>';
jQuery('.member-<?php the_ID(); ?>-thumbnail').hover(function() {
jQuery('.member-<?php the_ID(); ?>-thumbnail .attachment-thumbnail').attr('src', secondthumb);
}, function() {
jQuery('.member-<?php the_ID(); ?>-thumbnail .attachment-thumbnail').attr('src', firstthumb);
});
});
</script>
Thanks for the input everybody.