Post

Speed Coding Custom WordPress ACF Blocks

When it comes to speed coding custom Wordpress that use an ACF based block based page builder system. Discovering object oriented programming was a real game changer.

Using Object Orientated Programming (OOP) with your WordPress Advanced Custom Fields (ACF) is a match made for impatient web developers like me. I’m aware that a web project has so many critical aspects tjat I want to be coding at maximum efficiency and reusing code snippets effectively.

This way we can keep template files cleaner by allocating much of the logic into the php class files. Reduce your code bloat and keep template files readable.

  • It promotes dryer code, less spagetti code.
  • The classes can be reused from project to project
  • speeds up code output for common ui elements

Add your ACF code to a method

Discovering this simple technique was a real game changer for me. For years i was looking for a way to reduce repetitive coding tasks. OOP was my saviour in this regard.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<?php

/**
 * acf image field class declaration
 */
class AcfImage
{

   /**
      * acf field name must be called 'image'
      * pass in the css class
      */
   public function my_image($css_class)
   {
   $image = get_sub_field( 'image' ); ?>
			<?php if ( $image ) : ?>
				<img class = " <?php $css_class; ?>" src="<?php echo esc_url( $image['url'] ); ?>" alt="<?php echo esc_attr( $image['alt'] ); ?>" />
			<?php endif; ?>
   <?php
   }
}

/**
 * output the image with custom css class
 */

//initiat
$my_image = new AcfImage('banner__image');

//output
$my_image->my_image('css_class');

The block class

Now the above code is simple but it but it can be expanded upon. What if we had a class called block and within block we had methods for all your standard web development patterns

  • image
  • title
  • text
  • link
  • banner
  • slideshow
  • cards
  • blog_news_feed

The idea is you can keep reusing the block class from project to project. Initiating Objects as you need them.

Acf block page builder

See the acf block page builder in action

This post is licensed under CC BY 4.0 by the author.

Comments powered by Disqus.