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 ana
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:To this one:
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. Theimg src
was changing but not thesrcset
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.
Thanks for the input everybody.