treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Change Home Page Image using Advanced Custom Fields

  • Hi,

    Hoping someone can assist with how I would go about using Advanced Custom Fields plugin for WordPress or just using a custom field, for an image I have on my home page, which is currently hardcoded to a file URL within my media library.

    I basically have a home-page-template.php file for my home page where I have created something of the following nature, within it:

      <div id=”home-page-photo”>
        <img src=”http://mydomain.com/uploads/some-image.jpg” />
      </div>
    

    So based on the above code within my home-page-template.php, can someone through the use of Advanced Custom Fields assist me on how to allow a user to change the home page some-image.jpg file to be whatever they like, without the need of physically going into the home-page-template.php file and manually changing this?

    Basically require a means of replacing the

    src=” http://mydomain.com/uploads/some-image.jpg” to

    src=” http://mydomain.com/uploads/another-image.jpg

    basically, whatever the user would like to change it to.

    Can someone please assist with the php code or perhaps point me to an article that would assist me in performing the above requirement.

    Thanks. Tony.

  • I still haven't dug into the ACF plugin, but I do know how to do this with regular custom fields.

    <?php 
      
        $myPic = get_post_meta(get_the_ID(), 'myPic', true);
        // param 1 - feed the current page / post id
        // param 2 - the second param myPic refers to whatever you named your custom field.
        // param 3 - needs to be true to return a string, false to get an array
      
      
        if($myPic != '' || $myPic != null) { 
        // make sure we got something we can use
        ?>
    
    
    <img src="http://mydomain.com/uploads/<?php echo $myPic; ?>" />
    
    <?php } else { 
    
      // do something less cool 
    
    }
    

    This could probably be accomplished using the "Featured Image" for the page unless you're using it else where.

  • Why make the user change the URL to the image when you can just get them to upload a new image themselves?

    Using ACF, you can simply add an image field to your home page and then use the following code in your template:

      <?php
          $home_image = get_field('your_field_name');
    
          if( $home_image ) {
              echo wp_get_attachment_image( $home_image, $size = 'full' );
          } else {
              echo "<img alt=\"\" src=\"path/to/your/default.jpg\">";
          }
      ?>
    

    I'm using wp_get_attachment_image here, but that depends on you selecting 'Image ID' as the 'Return Value' when you create your custom field.

  • Hi,

    Really appreciate the responses – will take a look and let you know how I go.

    Thanks. Tony.