Add Featured Images to Anchor CMS Posts

I’ve been meaning to add featured images to my posts for a while now. I finally sat down this weekend to do it and thought I’d document the process for those of you out there that might benefit.

I use Anchor CMS to run this site, which I’ve mentioned numerous times before. You might want to check out Add Disqus to Your Anchor CMS Blog and (Fairly) Simple Shared Count for more challenging Anchor upgrades.

This is one of the simplest projects to implement; it should only take you a few minutes to complete. Styling the featured image after you have it inserted into your post is the most time-consuming part, and the only thing I won’t get into in this tutorial.

Add a Custom Field

Anchor allows you to add custom fields to either posts or pages. We first should set one up so that we can call upon it in our code.

animated GIF of the process of adding a custom field in Anchor CMS

Watch how easy it is to add a custom field in Anchor CMS.

You’ll want to log into your site’s admin, click on the Extend link in the header, and then Custom Fields. Next click the Create a new field button and select the options you need. For the purposes of this tutorial, we’ll be choosing post and image.

You’ll want to fill out the Unique Key field with what your code will use to call the field. I suggest using hyphens but you can use underscores in place of spaces too. The Label field is what you’ll see in the admin and should be short but useful to you. I like to add ideal or required dimensions in parenthesis so that I can remember later what I intended when setting it up.

Use the Image max width and Image max height fields to have Anchor scale your image down if it’s too big. I’ve found this to only work if both fields are filled out. In the case where you may only be concerned with the width of an image, just use a super high value for the height field.

Finally, click the Save button and you’re done. Your new custom field is ready and waiting for you at the bottom of your posts. You can click the little cloud icon to select an image now or wait until later. It doesn’t matter since nothing will show up on the front-end until we add the necessary code to our theme.

screenshot of new custom field added to post editor

Bring the Custom Field to Life

Open up your editor and find your article.php file in your theme. We’re going to add conditional logic to make sure we don’t cause any errors or display any featured image HTML when there isn’t an image to display.

Pick a spot in your file where you’d like the featured image to display and place the following code there:

<?php $featuredimage = article_custom_field('featured-image'); ?>
<?php if(!empty($featuredimage)): ?>
    <div class="featured-image">
        <img src="<?php echo $featuredimage; ?>" alt="<?php echo article_title(); ?>" />
<?php endif; ?>

The first line assigns the returned custom field value to a variable so we can use it later. Then we wrap our markup in a conditional that effectively says, “if our $featuredimage variable is not empty, use it in the following way.” The closing of the conditional with endif; without using an elseif: or else: means we’re either going to show the featured image with it’s markup, or we won’t show anything.

I’ve placed this code just above my post body content with the featured image URL being used in the src attribute of an <img> tag. So when I have a featured image, it shows up below the title and above the body text. When I don’t have a featured image, nothing is shown between the title and body text. You can use your featured image anywhere you like, even using the URL to add a background image to your whole page.

Make sure you change article_custom_field('featured-image'); in the above code to grab the Unique Key you picked for your custom field. You’ll also want to change the HTML markup to whatever you’re looking to accomplish. For my site, I’ve given the featured image a simple wrapper using a <div> with a class of featured-image so I can style it quickly in my CSS.

Now your featured image will display on your post if it exists. And if it doesn’t exist, the post will look as if there never was a featured image option. Pretty slick.

Endless Possibilities

You can add as many custom fields as you find a use for. And you can customize them to your heart’s content. While there isn’t a Boolean field type yet for getting a checkbox, you could use a simple text field and true/false values for toggling options on and off on your posts. That’s the only limitation I can think of, aside from repeating fields.

You can add just about anything to your site with custom fields. Think about dates, times, extra info, background images, featured images, gallery images, file downloads, etc.

I’ve got a few ideas for displaying the featured images on my homepage and blog landing page too. Using pretty much the same method as described here, I’ll be doing that as soon as I have more posts with featured images.

How did your site turn out? Where are you using custom fields on your site? Tell me in the comments below.

  • anchor-cool-cms

    How can I add IMG-SRC to the regular post and show images without uploading them to the hosting?

    • Andrew Miguelez

      Peice of cake! If you want to hotlink to images already online, simply swap out the field type for text instead of image. Then when you populate the field on a post, use the URL for the image hosted elsewhere.

      Keep in mind that hotlinking images isn’t a very good practice. You never know when the image will be removed. Whenever possible, make a local copy of the image you want to use.

      Either way, happy custom-field-ing!

  • Chris

    I followed your instructions, on the edit post page after selecting an image to upload and pressing save it tells me the changes were saved, only there is no image display on the site and when I refresh the edit post page the image filename in the ‘featured image’ box is gone? I also cannot find the image on the server anywhere. Where are they being uploaded to, does this need to be set up first? Might be an issue with upload, please help.

    • Andrew Miguelez

      Hey, Chris. I’m pretty sure if the image file name doesn’t show up in the field on the edit page, it’s not uploaded. As you confirmed by checking the server, the image isn’t being uploaded. It should be in the `/content/` folder.

      I’m thinking one of three things is happening.
      1- Your server isn’t allowing the file to upload.
      2- Your browser isn’t compatible with the upload script, or JS is broken on the page.
      3- You are hitting save before the image has finished uploading.

      Try to figure out what it is in reverse. First try selecting an image to upload, and wait a minute before saving because there is no progress bar so we don’t know when it’s done. (If the image is huge, it may never upload, so try with a smaller image too.)

      Second, try a different browser. I know this works in Firefox and Chrome with the latest version of Anchor (v0.9.2). I don’t know if it works in IE. Also, check to see if there are any JS errors on the page. This could break the upload script because it’s AJAX.

      Third, if it’s neither of those issues, your server might be at fault. Share what host and platform you’re on and maybe we can find others who solved a similar issue.

      • Chris

        It was a bug with Chrome, worked in Firefox 🙁 I spent hours trying to work out why the images wouldn’t upload to the content folder. Just a browser thing, I’ll report it.

        • Andrew Miguelez

          Which version of Anchor are you running? Also, where are you reporting it?

          Thanks for sharing your findings.

  • Buenas buenas

    Thanks 🙂

  • Hello,
    thanks for such awesome tutorial, but I’ve got a little problem: when I click save on already saved blog post (update it) the image will disappear (I have to upload file every time I want to save/edit the post) – I think this is the problem with AnchorCMS itself but maybe You know how to fix it?
    I’ve added also a thread at AnchorCMS forum, but I think it’s not very active lately:

    • Andrew Miguelez

      What version of Anchor are you using? The last I used it, I was running 0.9.2. I don’t remember running into your issue so I’m not sure where to look for a solution.

      • I’m running currently 0.12.1 Anchor version – does it mean that probably it has more bugs than previous versions? :/

        • Andrew Miguelez

          I don’t know but I’d recommend looking at the open issues on the github repository and ask @_craigchilds on Twitter. He is one of the only people still working on the development of Anchor.

  • k.lary

    This is a great tutorial! Thank you so much for explaining in so much detail. I experienced some funkiness trying to get the uploaded image to show up on the post screen which I think might have been a browser or server caching issue since after switching back and forth between home page, post page and admin and refreshing several times, it finally started appearing consistently)

    I haven’t implemented this yet, but my site is album reviews and I am thinking of how to have a rating system that will display a certain number of stars. After reading your article I am thinking I could add a custom ‘rating’ field (numeric value 1-5) . If I create 5 star images (one star, two stars,….) named star1.jpg, star2,jpg, star3.jpg etc, I can add a conditional if-rating-field-is-not-empty to the article.php file that will display the appropriate image by dynamically creating the imagename using the value in the rating field. (something like (not checked for syntax/path) <img src=/content/star.jpg>.

    • Andrew Miguelez

      I’m glad you found the tutorial useful. Your logic for the rating system is sound, but I would suggest using one image and showing it as a repeating background for the stars. You would then insert a class name to an element (span or div) with the value from the field. Example below…

      <?php $rating = article_custom_field(‘rating’); ?>
      <span class=”rating rating-<?php echo $rating; ?>”><?php echo $rating; ?> star rating</span>

      • k.lary

        ah, interesting – your suggestion is a bit simpler. I’m not sure if a repeating background image will resize dynamically the way I’d like but I’ll try it and see how it works. thanks for the suggestion.

        • Andrew Miguelez

          CSS3 offers background image sizing controls. You can scale the star image to fit vertically in its container while still allowing it to repeat horizontally. Good luck.