Adding Bulletproof Text Images With ACF That Work Without ACF

I know what you are thinking. The title does not make sense. ACF images without ACF? Hear me out. Advanced Custom Fields (ACF) is a great plugin that lets people add custom fields into the admin section of WordPress for each post or page. It is very handy. I use this often when I need to add a custom image for each post or a custom block of text to each post.

One example of this is a bit of code I wrote that adds a call to action on every page of the website. You can add a default call to action, or you can upload a custom one for each post.

The problem with using Advanced Custom Fields is that if you were to deactivate the plugin and you are using its functions, it would break your entire website. It is always a good idea to create themes that do not break if you remove plugins. Because of this, I created a way to use these custom fields in a way that works even without having ACF installed.

This is easy to do with text. Just use WordPress’s get_post_meta() function.

get_post_meta( get_the_ID(), 'cta_text', true )

However, when it comes to images, it gets a little trickier. Despite what you choose in the image mode in ACF, when you call the image variable using get_post_meta(), it always gives you the same thing: a post number. To make it work, you have to do a little extra work. You have to get the elements of an image one by one as if you were retrieving them from a WordPress post. Below is a chart on how to get each image attribute.

Src wp_get_attachment_url(get_post_meta( get_the_ID(), ‘cta_image’, true ))
Alt get_post_meta(get_post_meta( get_the_ID(), ‘cta_image’, true ), ‘_wp_attachment_image_alt’, true)
Title get_the_title(get_post_meta( get_the_ID(), ‘cta_image’, true ))

Naturally, you want to make sure that you do some error correction, so that nothing breaks. In this case, it is as simple as adding an if statement around the code testing if the variable exists. For example:

if(get_post_meta( get_the_ID(), 'cta_image', true )) {
	echo wp_get_attachment_url(get_post_meta( get_the_ID(), 'cta_image', true ));
}

The beauty behind this is that it only uses WordPress functions. If you remove any plugins, it would continue to work properly because the variables and images are safely saved in the database. This makes them bulletproof, and future proof, and fire proof, and everything proof.

Let me know if my call to action plug in interests you. I may publish it if there is any interest.

Leave a comment

Your email address will not be published. Required fields are marked *