WordPress actions and filters are wonderful because they allow plugin, theme and core developers to offer large amounts of customization with very little effort.
WordPress actions let you append your own functionality at a specific process
WordPress filters allow you to change and modify data as it is processed
Mike is making a burger, and he offers to add/modify the layers as you wish.
THE BREAKDOWN
As we can see do_action function lets you put anything between the layers, and apply filter lets you change what the layer is. Now, lets use the burger analogy with the code:
WordPress Hook: Action
Mike, Please add pickles before lettuce
add_action('before_vegetable', 'my_custom_layer_before_vegetable');
function my_custom_layer_before_vegetable(){
echo 'I am the pickles layer';
}
Then you can add pickles and coriander before lettuce
add_action('before_vegetable', 'pickles_layer_before_vegetable', 1);
function pickles_layer_before_vegetable(){
echo 'I am the pickles layer';
}
add_action('before_vegetable', 'coriander_layer_before_vegetable', 2);
function coriander_layer_before_vegetable(){
echo 'I am the coriander layer';
}
Notes: the number 1 & 2 stand for priority, if you wanted coriander to appear above pickles then you just need to switch the priority.
WordPress Hook: Filter
Nathan comes, Hi Mike, I don’t want lettuce on my burger, please use pickles instead
add_filter('vegetable_filter', 'change_vegetable_filter' );
function change_vegetable_filter( $default ){
return 'I am the pickles layer';
}
I want a crispy patty
add_filter('patty_filter', 'make_it_crispy');
function make_it_crispy( $meat ){
$cooked = deep_fry_task( $meat );`
return $cooked;
}
This is an example of how to delete images from the media library when they are removed from a gallery field
This is an example of how to use the acf image field as user avatar wordpress. Please make use that the return format of the image field is set to url.
This is an example of how to create a custom location rule to add fields to specific term. For more info on the same, please read more here. For those looking to do this and other custom rules here is some code for this specific case.
This is an example of how to add fields to WC attributes.
This is an example of how to change fields dynamically on role selection change ACF role-based conditions on user new / edit forms
This is an example of how to update All ACF Post Fields. You can call this function by hooking into init
.
add_action( 'init', 'mass_update_posts' );
You can add the action and function, load the website once, and then comment it out so it doesn’t load again.
This is another custom location rule example. This rule lets you choose a field group to be used only in the in the admin or on a front end form.
acf/fields/post_object/query filter examples