1

I have a wordpress page where I want to display a featured image on the header of the homepage, but no other pages. I set up a script to read whether the body tag contains the "home" class and display an image based on that. The code looks like this:

<script>
    if($('body').hasClass("home")) {
    $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
</script>

What's wrong with this script?

6
  • Yes, what's wrong? Any error you encountered?
    – Raptor
    Commented Apr 20, 2015 at 2:38
  • What errors do you get in the browser's console?
    – j08691
    Commented Apr 20, 2015 at 2:42
  • I'm guessing there's a $ is not defined in the console, wordpress is in no-conflict mode by default ?
    – adeneo
    Commented Apr 20, 2015 at 2:44
  • And this looks like something you could do with CSS -> body.home #headshot img {display:inline}
    – adeneo
    Commented Apr 20, 2015 at 2:45
  • or even better, in PHP <?php if ( is_home() ) echo $img; ?>
    – adeneo
    Commented Apr 20, 2015 at 2:46

3 Answers 3

0

Try to wrap your code into function fired on DOM ready:

<script>
    $(function() {
        if($('body').hasClass("home")) {
            $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
        }
    });
</script>

More info

0

jQuery needs to know when to start the function. Start it after the document is ready.

$(document).ready(function(){
    if($('body').hasClass("home")) {
    $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
}
});
0

Did you include jQuery library in your header section? Also some times $ symbol may conflict in wordpress, write full jQuery term when initialize jQuery this way:

jQuery(document).ready(function(){
 if($('body').hasClass("home")) {
 $('#headshot').html('<img src="http://www.kieferslaton.com/wp-content/uploads/2015/04/Headshot1.png" alt="headshot">');
 }
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.