How to include Advanced Custom Fields (Free) in a custom WordPress plugin with Composer?

Including ACF Pro in a WordPress project via Composer is already a simple task, but recently, a client project required me to include the free version of Advanced Custom Fields in a plugin I'm working on for them. WordPress Packagist makes this very easy when running Composer on a WordPress installation, but by default, it will install any plugin dependencies in `/wp-content/themes`. In this short tutorial, I'll show you how to include the free version of Advanced Custom Fields in a custom plugin.

Here are the lines of code you need to add to your composer.json file. This will change the plugin's path to: /vendor.

{ "repositories":[ { "type": "composer", "url": "https://wpackagist.org" } ], "extra": { "installer-paths": { "vendor/{$name}/": [ "type:wordpress-plugin" ] } }, "require": { "wpackagist-plugin/advanced-custom-fields": "^5.9" } }

You can install any WordPress plugin with the following command:

composer require "wpackagist/hello-dolly""

ACF also provides guidance on how to include your plugin in your project, Therefore, here is a modified version that works with the previous Composer configuration:

if( ! class_exists( 'ACF' ) ) { // Define path and URL to the ACF plugin. define( 'MY_ACF_PATH', PLUGIN_DIR_PATH . '/vendor/advanced-custom-fields/' ); define( 'MY_ACF_URL', PLUGIN_DIR_URL . '/vendor/advanced-custom-fields/' ); // Include the ACF plugin. include_once( MY_ACF_PATH . 'acf.php' ); // Customize the url setting to fix incorrect asset URLs. add_filter( 'acf/settings/url', function( $url ) { return MY_ACF_URL; } ); // (Optional) Hide the ACF admin menu item. add_filter( 'acf/settings/show_admin', function( $show_admin ) { return false; } ); }

Do you need help with a web project?

Do you need help with a web project? Don't hesitate to contact me. I develop complete and customized solutions with WordPress and PHP, using modern tools and processes, HTML, CSS, SCSS, PHP, JavaScript, Bootstrap, and more. Ready? Send me a message and let's talk about your web project!