ACF | Resources, Documentation, API, How to & Tutorial Articles https://www.advancedcustomfields.com/resources/ Fri, 02 Feb 2024 17:07:24 +0000 en-US hourly 1 https://wordpress.org/?v=6.4.2 Using Context With ACF Blocks https://www.advancedcustomfields.com/resources/using-context-with-acf-blocks/ Wed, 24 Jan 2024 20:20:31 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=465089 ACF Blocks opens the door to more creative building possibilities. One example we previously explored was using InnerBlocks and parent/child relationships, where we nested ACF Blocks inside of each other. Nesting your ACF Blocks organizes your block structure and codebase while allowing for a refined editorial experience. Ready to dive into the code? You can […]

The post Using Context With ACF Blocks appeared first on ACF.

]]>
ACF Blocks opens the door to more creative building possibilities. One example we previously explored was using InnerBlocks and parent/child relationships, where we nested ACF Blocks inside of each other. Nesting your ACF Blocks organizes your block structure and codebase while allowing for a refined editorial experience.

Ready to dive into the code?
You can dive right in by downloading the tt4child.zip! Be sure to have the TwentyTwentyFour theme installed as well as ACF PRO.

ACF 6.0 introduced support for WordPress’s block context. Block context enables higher-level blocks, such as parent blocks, to supply values that descendant blocks within the same structure can utilize. This functionality permits direct child blocks and blocks further down the hierarchy to receive values from a parent block. This process occurs without the necessity for embedding these values directly into the code or establishing a direct link between the parent and descendant blocks.

It is critical to note that block context only flows downward from parent blocks, and it’s not possible to share data upward from child blocks to their parent.

Creating Block Context

Block context is defined in the block’s block.json, just like other block properties and attributes. The relationship of block context relies on there being a block that is the provider and a block that is the consumer of the providing block’s context.

The provider block defines providesContext in its block.json:

Example block that provides context

{
    ...rest of block.json

    "providesContext": {
        "acf/fields": "data"
    },

    ...rest of block.json
}

And the consumer block defines the usesContext in its block.json:

Example block that consumes context

{
    ...rest of block.json

    "usesContext": ["acf/fields"],

    ...rest of block.json
}

Displaying Context Values in ACF Blocks

Once you have established a binding context relationship between your ACF Blocks, you can reference values from the parent block in any nested block by checking and outputting the value in the child block’s template.

<?php echo $context['acf/fields']['an_example_field']; ?>

One thing to note: ACF Blocks use field keys in the block editor, and block data is only hydrated to field names upon saving. Because of this, you should use $context['acf/fields']['field_key'] to get access to the data inside your template if it exists, before defaulting back to $context['acf/fields']['field_name'] if it doesn’t. This supports both backend and frontend output of context data.

Also, whenever the providing parent block’s field value is updated in the editor, the child block that consumes the parent’s context will be automatically re-rendered.

You should also be aware that sharing ACF data with your child blocks will result in sending the complete ACF field data back to the server for rendering previews. This may have performance implications for your blocks in the editor.

Also, ACF automatically passes the postId and postType down through block context by default, which expedites nesting your ACF Block in the Query Loop block.

Conclusion

In summary, ACF Blocks introduces a versatile and powerful way to extend the functionality of the WordPress editor, offering a rich set of features that enhance both the developer and editor experiences. By leveraging InnerBlocks and parent/child relationships, you can structure your content with greater flexibility and precision. The introduction of block context in ACF 6.0 further amplifies this by allowing data to flow seamlessly between blocks, removing the need for direct code embeddings or explicit relationships.

This advancement simplifies the development process and opens up a myriad of creative possibilities for content management and presentation. Whether you are building complex layouts, crafting unique editorial experiences, or providing dynamic content relationships, ACF Blocks equipped with block context capabilities are an invaluable tool in your WordPress development arsenal.

Remember, while the power of ACF Blocks and block context brings great flexibility, it’s important to consider performance implications and the best practices for data management to ensure your site remains fast and responsive. With the right approach, ACF Blocks can transform the way you think about and build with WordPress.

Download the tt4child.zip and dive into the code to see firsthand how ACF Blocks can revolutionize your WordPress projects. Happy coding!

The post Using Context With ACF Blocks appeared first on ACF.

]]>
Extending ACF Blocks With Block Supports https://www.advancedcustomfields.com/resources/extending-acf-blocks-with-block-supports/ Wed, 24 Jan 2024 19:47:24 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=446919 Overview The WordPress Block Supports API offers plenty of features to extend your ACF Blocks. Additional attributes are passed to your block when you opt in to these features. Often, these features enable different parts of the block editor’s user interface and allow your clients to customize corresponding properties like spacing, alignment, or color. This […]

The post Extending ACF Blocks With Block Supports appeared first on ACF.

]]>
Overview

The WordPress Block Supports API offers plenty of features to extend your ACF Blocks. Additional attributes are passed to your block when you opt in to these features. Often, these features enable different parts of the block editor’s user interface and allow your clients to customize corresponding properties like spacing, alignment, or color.

This tutorial shows you how to utilize Block Supports with ACF Blocks to give your clients a consistent and easy-to-use experience for managing block settings and styles. We’ll explore how to add Block Support properties, and then show how to ensure your block’s assigned properties are properly output in the final markup.

This tutorial will modify the custom Author Info block used in previous tutorials. However, you should be able to add the code to any ACF Block and obtain similar results. You can download the current version of the Author Info block here: author-info-block-v2.zip

Be sure to check out the previous tutorials:

  1. Using InnerBlocks and Parent/Child Relationships With ACF Blocks

  2. Locking Down Your ACF Blocks With Block Locking

Declaring Block Supports in ACF Blocks

The entry point for declaring your Block Supports is your ACF Blocks block.json. Let’s look at a simple ACF Block example:

{
    "name": "acf/author-info",
    "title": "Author Info",
    "description": "Display an author's info and picture.",
    "icon": "id",
    "acf": {
        "mode": "preview",
        "renderTemplate": "template.php"
    },
    "supports": {
        "align": true,
        "html": false,
        "jsx": true,
        "mode": true
    }
}

Most of the block.json example above should already look familiar. The "supports" key is where we want to focus. Here, we’re declaring our support for certain features. Two features are unique to ACF Blocks and not part of WordPress: jsx and mode.

  • jsx: JSX refers to how ACF renders your block. This property is true by default in ACF Blocks v2, and is required to use features like <InnerBlocks /> and will be required for upcoming features. When enabled, ACF processes your rendered PHP template in JavaScript first, allowing the use of React implemented features.

  • mode: Adding support for mode allows users to toggle between edit and preview modes via a button. This property defaults to true.

By declaring "align": true, we’re enabling our clients to set this block’s alignment to center, left, right, full, or wide.

The Block Editor in WordPress, showing alignment options for a block.

We can limit the options for alignment by passing in specific attributes.

...
"supports": {
    // Declare support for specific alignment options.
    "align": ["left", "right", "full" ]
}

A block in the WordPress block editor, with limited options for alignment.

You can go even further, using the attributes key to pass a default value for many Block Supports.

...
"supports": {
    // Enable all alignment options.
    "align": true
},
"attributes": {
    "align": {
        "type": "string",
        "default": "right"
    }
}

Whenever a client adds this block to the editor, it will automatically be aligned right.

A block in the block editor, with supports set so it automatically aligns to the right.

Alternatively, you can disable the alignment controls and still force a non-default alignment attribute. Set "align": false, and then pass in an attribute with a new default alignment:

...
"supports": {
    // Disable alignment controls.
    "align": false
},
"attributes": {
    "align": {
        "type": "string",
        "default": "wide"
    }
}

Spacing is another Block Support attribute that we can explore as an example. Spacing can include margin, padding, and blockGap, and each exists as sub-properties of spacing.

...
"supports": {
    "spacing": {
        "margin": true, // Enable margin UI control.
        "padding": true, // Enable padding UI control.
        "blockGap": true // Enables block spacing UI control for blocks that use layout.
    }
}

The example above enables all three spacing properties. Of course, we can be more specific on what we want to allow.

...
"supports": {
    "spacing": {
        "margin": ["bottom", "top"], // Enable margin for arbitrary sides.
        "padding": true, // Enable padding for all sides.
        "blockGap": ["horizontal", "vertical"] // Enables axial (column/row) block spacing controls.
    }
}

Again, we can also provide default values for specific properties that we support with the attributes definition. When we opt into specific spacing properties, the definition of the attributes includes the style attribute.

...
"supports": {
    "spacing": {
        "margin": ["bottom", "top"], // Enable margin for arbitrary sides.
        "padding": true, // Enable padding for all sides.
        "blockGap": ["horizontal", "vertical"] // Enables axial (column/row) block spacing controls.
    }
},
"attributes": {
    "style": {
        "type": "object",
        "default": {
            "spacing": {
                "margin": {
                   "bottom": "2rem",
                    "top": "2rem"
                },
                "padding": "2rem" // Assign default value for all sides
            }
        }
    }
}

Above, we’re opting into specific spacing properties in our "supports" definition. In our "attributes" definition, we’re passing default values to each of our properties. There are a lot of Block Support properties, and we encourage you to experiment with them to turn key features of your ACF Blocks on or off. If you use ACF Blocks v2 and define your blocks with block.json, any new supports added by WordPress in future versions are likely to work without any other changes.

Also, remember that declaring support in your block.json will not automatically apply the final properties to your final saved block markup. Once your blocks have attributes assigned, you will want to apply them programmatically to your blocks. We’ll cover how to do this next.

Applying Block Supports to ACF Blocks

Defining Block Support in your ACF Block’s block.json file was the first step. Next, we need to ensure all of the properties our block supports can be output in the final block markup.

This is where the convenience of ACF PRO’s "renderTemplate" definition comes in handy. In your block.json, you can pass the PHP file you want to call for your block’s template:

"acf": {
    "renderTemplate": "template.php"
}

Once we step into our template.php, we’re passed in several helpful parameters to utilize:

  • $attributes – (array) The block’s attributes.
  • $content – (string) The block’s content as a parse string.
  • $is_preview – (boolean) Check whether or not the block is currently in the editing view.
  • $post_id – (int) The current post being edited or viewed.
  • $wp_block – (WP_Block) The block instance.
  • $context – (array) Any block context information.

WordPress provides us with the handy get_block_wrapper_attributes() function, which we can use to assign our attributes. However, we must be mindful to not try and use this function when ACF Blocks are in preview in the editor, as your blocks will automatically get a wrapper provided by the block editor which could duplicate your attributes. We can use $is_preview to check when we’re in preview mode and avoid confusion.

Let’s look at a specific example. Here is our ACF Block’s block.json definition:

{
    "name": "acf/author-info",
    "title": "Author Info",
    "description": "Display an author's info and picture.",
    "icon": "id",
    "acf": {
        "mode": "preview",
        "renderTemplate": "template.php"
    },
    "attributes": {
        "style": {
            "type": "object",
            "default": {
                "spacing": {
                    "margin": {
                        "bottom": "2rem",
                        "top": "2rem"
                    },
                    "padding": "1rem"
                }
            }
        }
    },
    "supports": {
        "color": true,
        "multiple": false,
        "spacing": {
            "margin": ["bottom", "top"],
            "padding": true
        }
    }
}

Enabling "color": true automatically opts us into some of color’s sub-properties, like "background" and "text". These will allow editors to choose a background color and text color.

We’re passing in a new definition for "multiple": false, which makes sure that this block can only be inserted once in the editor. If an editor tried to insert another copy of our block in the same post, then they would see a grayed-out version of the block in the inserter.

The block editor in WordPress, with the "Author Info" ACF Block greyed out to indicate it is already in the content and cannot be inserted again.

Finally, we’re passing in some "spacing" definitions and setting default values for the desired margin and padding in our "attributes".

When we want to output all this for the final markup and leverage the convenience of get_block_wrapper_attributes() in our "renderTemplate": "template.php" file, we would put:

<?php if ( ! $is_preview ) { ?>
    <div <?php echo wp_kses_data( get_block_wrapper_attributes() ); ?>>
<?php } ?>

    // Block content goes here.

<?php if ( ! $is_preview ) { ?>
    </div>
<?php } ?>

When our editors leverage any of the customization options, they’ll be output in the final markup. It may be a class or style that is output, depending on which features we allow.

The output of an ACF Block, with a devtools panel showing the class and style being output in the block.

Tips for Block Supports and ACF Blocks

There are some special tips to keep in mind when working with Block Supports and ACF Blocks.

Adding, modifying, or removing an attribute from an existing block’s block.json definition will not update the blocks that have already been inserted in your content. It will only impact future versions of the block, including if a user modifies an existing block entry. This is a limitation of how blocks work in WordPress.

ACF Blocks automatically passes a few default Block Supports behind the scenes:

array (
    'align' => true, // Enables alignment
    'html'  => false, // Disables individual block editing in HTML view
    'mode'  => true,
    'jsx'   => true, // Allows ACF to parse JSX to HTML for InnerBlocks
)

This is really just the beginning of what you can do with Block Supports. Some more helpful Block Supports that we want to point out:

By default, all blocks will appear in the inserter, block transforms menu, Style Book, etc. To hide a block from all parts of the user interface so that it can only be inserted programmatically, set inserter to false.

{
…
    "supports": {
        // Hides this block from the inserter.
        "inserter": false
    }
}

By default, all blocks can be converted to reusable blocks, but you may want to disable this ability for certain blocks. If "supports": reusable is set to false, the option to convert the block into a reusable block will not appear.

{
…
    "supports": {
        // Do not allow the block to be converted into a reusable block.
        "reusable": false
    }
}

We’re still just scratching the surface, and WordPress offers a great deal of flexibility for styling and controlling your ACF Blocks with Block Supports. Be sure to check out the full list of Block Supports for more features you can add to your ACF Blocks.

The post Extending ACF Blocks With Block Supports appeared first on ACF.

]]>
The Requirements to Run ACF https://www.advancedcustomfields.com/resources/requirements/ Mon, 22 Jan 2024 10:41:46 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=463701 The minimum requirements to run ACF and ACF PRO are: WordPress 5.8 PHP 7.0 We regularly review our minimum requirements in line with WordPress. We recommend you run the plugin on a site and server with a currently support version of: Latest version of WordPress or the one previous PHP 8.2+ MySQL 8.0 LTS or […]

The post The Requirements to Run ACF appeared first on ACF.

]]>
The minimum requirements to run ACF and ACF PRO are:

  1. WordPress 5.8
  2. PHP 7.0

We regularly review our minimum requirements in line with WordPress.

We recommend you run the plugin on a site and server with a currently support version of:

  1. Latest version of WordPress or the one previous
  2. PHP 8.2+
  3. MySQL 8.0 LTS or 8.2+
  4. Firefox and Webkit-based browsers like Chrome or Safari. Internet Explorer is not supported.

ACF and ACF PRO are compatible all the way up to PHP 8.3.

The post The Requirements to Run ACF appeared first on ACF.

]]>
acf_get_fields() https://www.advancedcustomfields.com/resources/acf_get_fields/ Fri, 05 Jan 2024 21:57:06 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=449732 Retrieves all the fields from a specific field group.

The post acf_get_fields() appeared first on ACF.

]]>
Description

Retrieves all the fields from a specific field group, returning them as an array of field objects. This function should not be confused with get_fields(), which returns an array of field values for a specific post rather than a field group.

Parameters

acf_get_fields( $parent );
  • $parent (mixed) (Required) The field group’s ID or key.

Examples

Basic usage

This example demonstrates how to return an array of fields for a given parent. Note that you will have to replace the field group key shown below with your own.

acf_get_fields('group_6525b4469c71d');

Advanced usage

The following example demonstrates how to retrieve the values in the foreach for every field contained in the field group and then output them for viewing.

$specifications_group_id = 'group_6525b4469c71d'; // Replace with your group ID
$specifications_fields      = array();

$fields = acf_get_fields( $specifications_group_id );

foreach ( $fields as $field ) {
    $field_value = get_field( $field['name'] );

    if ( ! empty( $field_value ) ) {
        $specifications_fields[ $field['name'] ] = $field_value;
    }
}

The post acf_get_fields() appeared first on ACF.

]]>
Installing ACF PRO With Composer https://www.advancedcustomfields.com/resources/installing-acf-pro-with-composer/ Fri, 08 Dec 2023 13:42:06 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=368440 ACF PRO can be installed using Composer, similar to how the free plugin can be installed using WordPress Packagist. Generate API Credentials Visit My Account, navigate to the Licenses​​ tab, and then click Install using Composer for your license. This will reveal a panel where you can generate an auth.json credentials file to be used […]

The post Installing ACF PRO With Composer appeared first on ACF.

]]>
ACF PRO can be installed using Composer, similar to how the free plugin can be installed using WordPress Packagist.

Generate API Credentials

Visit My Account, navigate to the Licenses​​ tab, and then click Install using Composer for your license.

This will reveal a panel where you can generate an auth.json credentials file to be used with Composer.

ACF My Account Licenses screen with Composer installation.

The auth.json file is made up of a username and password field. The username and password are used by Composer to authenticate to our API with HTTP basic authentication.

The username is the ACF PRO license key, and the password is the site URL (including https:// or http://) that the license is active for.


{
  "http-basic": {
    "connect.advancedcustomfields.com": {
      "username": "Dvl2P9fLovYy2oJkdYOPiCrHXcRgGrmk9WR62HdErPasPsV43COx0anwTizc9XFrY8qysqqZ",
      "password": "https://mysite.com"
    }
  }
}

The password can be an existing site that is already active for the license key, and there’s a dropdown of already activated sites that can be selected and will automatically populate the ‘password’ field in the sample auth.json code. Alternatively, you can enter a new site URL in the textbox on the right to populate the auth.json. This site URL will be activated for the license in your account upon Composer installation. Any activation of a new URL will be subject to the activation limits for the license.

If you are using Composer to install your plugins in an automated way for new builds where you don’t know the final site URL, we recommend using an existing production URL that has been activated for the license key.

Using Version Control

If you are using a version control system for your site, we recommend you add the auth.json file to your ignore file, e.g., .gitignore. This prevents the license key from being included in the repository.

Create the .gitignore file in the root of your local Git, if you don’t already have one:

touch .gitignore

Next, add a rule to ignore the auth.json file:

# Exclude auth.json from Git repo
auth.json

Make sure you create the auth.json file on the live server when you deploy your site if you’ve included it in your .gitignore.

Developers working with the site locally will also have to create the auth.json file and add the license key to it before running the Composer install command.

Add Our Repository

Add our repository to your composer.json file:


"repositories": [
    {
        "type":"composer",
        "url":"https://connect.advancedcustomfields.com"
    }
]

Install the Plugin

From the CLI, require ACF PRO using the following command:


composer require wpengine/advanced-custom-fields-pro

Version Constraints

You can use any Composer version constraints, or specify the exact version of the plugin:


"require": {
    "wpengine/advanced-custom-fields-pro": "6.0.7"
}

Customizing Install Locations

We use composer/installers to automatically install our plugin package to wp-content/plugins/. However, you can customize the install location by adding the following to your composer.json file:


"extra": {
    "installer-paths": {
        "wp-content/plugins/{$name}/": ["type:wordpress-plugin"]
    }
}

Installing as an MU Plugin

If you prefer to install ACF PRO as a must use plugin (mu-plugin), to ensure it will always be loaded by WordPress and can’t be deactivated from the admin dashboard like a normal plugin, you can alter the install location by adding the following to your composer.json file:


"extra": {
    "installer-paths": {
        "wp-content/mu-plugins/{$name}/": ["wpengine/advanced-custom-fields-pro"]
    }
}

However, plugin directories inside the mu-plugin directory will not be loaded automatically by WordPress, so you would need to require it manually with an acf.php file in the mu-plugin directory root:


<?php
require_once WPMU_PLUGIN_DIR . '/advanced-custom-fields-pro/acf.php';

As an alternative, there is a package that automatically handles loading directories in the mu-plugin directory.

Example composer.json


{
    "name": "wpengine/composer-test.dev",
    "description": "ACF PRO in a WordPress site",
    "repositories": [
        {
            "type":"composer",
            "url":"https://connect.advancedcustomfields.com"
        }
    ],
    "require": {
        "wpengine/advanced-custom-fields-pro": "^6.0",
    }
}

Build Systems and Environment Variables

Instead of auth.json, you can provide the basic authentication via the COMPOSER_AUTH environment variable if your deployment system does not support adding files pre-build. This should be a json encoded string matching the pattern below:


export COMPOSER_AUTH='{"http-basic": {"connect.advancedcustomfields.com": {"username": "Dvl2P9fLovYy2oJkdYOPiCrHXcRgGrmk9WR62HdErPasPsV43COx0anwTizc9XFrY8qysqqZ", "password": "https://mysite.com"}}}'

If you are using Roots Trellis for deployments, you can make use of the Composer HTTP Basic Authentication feature supported by your Ansible vault.

Troubleshooting

Error codes from Composer downloads match the HTTP standard. For example, 400 means you’ve requested an invalid version, 401 means you’ve provided an invalid license key or site URL, and 402 means your license has no sites left or has expired.

The post Installing ACF PRO With Composer appeared first on ACF.

]]>
ACF Blocks: How to Use Block Locking https://www.advancedcustomfields.com/resources/acf-blocks-how-to-use-block-locking/ Mon, 04 Dec 2023 18:59:13 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=434572 Locking down your ACF Blocks with block locking ensures those blocks can’t be removed or modified in unauthorized ways. You can think of block locking as a safety mechanism, whether you’re using it on a client’s WordPress site or one of your own. In this tutorial, we’ll show you how to use locking to restrict […]

The post ACF Blocks: How to Use Block Locking appeared first on ACF.

]]>
Locking down your ACF Blocks with block locking ensures those blocks can’t be removed or modified in unauthorized ways. You can think of block locking as a safety mechanism, whether you’re using it on a client’s WordPress site or one of your own. In this tutorial, we’ll show you how to use locking to restrict the movement and removal of individual blocks, and even patterns and templates.

In our previous tutorial on using ACF Blocks with InnerBlocks and parent/child relationships, we built a custom Author Info block (parent). This custom ACF Block used InnerBlocks to pass a series of nested blocks, which included another custom Author Twitter block (child).

The Author Twitter block was only available as a nested block within its parent Author Info block context. We used "parent": [ "acf/author-info" ] in the Author Twitter’s block.json file to establish this relationship and nested discoverability.

Now, we want to extend this Author Info block to refine the editorial experience for our editors. We want to make sure that they can get right to editing, and not accidentally remove or move a block and mess up the overall layout. This is where block locking is useful.

If you want to follow the steps in this tutorial exactly and already have some experience with ACF Blocks, you can download the plugin created in our last tutorial and add to it as we go.


New to ACF Blocks? Start with our tutorial on creating your first ACF Block!


What is Block Locking?

WordPress provides two types of block locking: template locking and individual block locking. You can utilize either of these, or combine them for sophisticated restrictions on your blocks.

Some other considerations when using block locking in WordPress:

  • Developers can use templateLock in their nested blocks.
  • Developers can lock entire templates with template_lock, even when registering custom post types.
  • Individual blocks can be assigned lock parameters in block markup. Assigned lock parameters can be used on the individual blocks passed into a template. The individual block’s lock overrides the template locking, unless the template locking value is contentOnly.

We highly recommend reviewing this helpful video on The Key to Locking Blocks from Wes Theron of the Make WordPress Training Team, along with the WordPress documentation.

Using InnerBlock Template Locking

Template locking can be accomplished by passing templateLock to the InnerBlocks component. Like this:

<?php
<InnerBlocks templateLock="all" />

Template locking options include the following:

  • contentOnly — Prevents all operations. Additionally, the block types that don’t have content are hidden from the list view and can’t gain focus within the block list. Unlike the other lock types, children can’t override this.
  • all — Prevents all operations. It is not possible to insert new blocks, move existing blocks, or delete blocks.
  • insert — Prevents inserting or removing blocks, but allows moving blocks.

Below are screenshots of what each of these would look like when applied to our Author Info block.

Editor with list view sidebar expanded and showing only nested content blocks with a lock icon. The result of having InnerBlock templateLock=contentOnly.

Author Info block with templateLock="contentOnly" set on InnerBlocks.
All nested blocks that do not contain content are hidden from the list view. Only content is editable.

Editor with list view sidebar expanded and showing all nested blocks with a lock icon. The result of having InnerBlock templateLock=all.

Author Info block with templateLock="all" set on InnerBlocks.
All nested blocks are locked to prevent moving, deleting, or inserting new blocks.

Editor with list view sidebar expanded and showing all nested blocks with a lock icon. Also, edit navigation expanded for nested paragraph block with option to 'Move to' highlighted. The result of having InnerBlock templateLock=insert.

Author Info block with templateLock="insert" set on InnerBlocks.
All nested blocks are locked from being removed or having new blocks inserted. Existing blocks can be moved.

Unlocking One Nested Block

For our Author Info block, we want to offer editors the option to remove the author’s biography paragraph, but everything else should remain locked from being removed. We’ll start by locking all the blocks down with templateLock="all" attribute on our InnerBlocks component, and then we’ll use individual locking properties to unlock the one nested block we want to allow them to remove. We’ll make all of our changes to the Author’s Info template.php file, in the author-info directory of the custom plugin we created in our tutorial on InnerBlocks.

For now, we’ll update our InnerBlocks code as follows:

<?php
<InnerBlocks templateLock="all" />

Next, we’ll have to update our individual nested block to allow removal. So, if editors choose to remove the author’s biography paragraph then they have the ability.

How to Use Individual Block Locking

Individual block locking takes priority and overrides template locking, unless templateLock="contentOnly" is used. This hides all blocks that do not have content from the list view, and allows editors to update only the nested content block.

However, we previously decided to apply templateLock="all". To update the individual Paragraph block nested within our passed template, we just need to target it with an additional lock parameter. Here is our abbreviated nested code before applying the parameter:

array(
    'core/paragraph',
    array(
        'style'    => array(...),
        'fontSize' => 'small',
        'content'  => 'Ea qui voluptate irure nulla aliquip nulla anim laborum exercitation eu incididunt.',
    ),
    array(),
),

And here it is after, with our lock applied:

array(
    'core/paragraph',
    array(
        'style'    => array(...),
        'fontSize' => 'small',
        'content'  => 'Ea qui voluptate irure nulla aliquip nulla anim laborum exercitation eu incididunt.',
        'lock'     => array(
            'remove' => false,
        ),
    ),
    array(),
),

With the 'remove' => false above, we’re stating that the nested Paragraph block should be allowed to be removed. Yes, the false is confusing, but this is how ya do it! 😉

Now we have our desired control of the block, with both template locking and individual block locking in place.

Author Info block example with lines pointing to differentiated blocks.

Author Info block example with lines pointing to differentiated blocks.

Next Steps and Considerations

This tutorial shows how you can use block and template locking to set editorial conditions and prevent unauthorized removal or modification of your ACF Blocks, but there is a lot of room left to explore.

There is another element to curating your editorial experience, which can be utilized when placing your blocks within patterns. If you plan to leverage your ACF Blocks in the context of patterns, then you’ll want to check out content-only block locking.

You could also extend your block content control strategy by preventing certain roles or users from locking and unlocking blocks. Be sure to check out how to restrict locking and unlocking for roles, specific users, or even post types.

If you’ve been following along, your final, full plugin code should match our version: author-info-block-v2.zip

In the next tutorial, we’ll show you how to use WordPress global styles and block styles with your ACF Blocks, providing a consistent and easy to use experience when managing settings and styles.

The post ACF Blocks: How to Use Block Locking appeared first on ACF.

]]>
How to Include ACF in a Plugin or Theme https://www.advancedcustomfields.com/resources/how-to-include-acf-in-a-plugin-or-theme/ Thu, 23 Nov 2023 17:10:56 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=447991 To include ACF or ACF PRO within your plugin or theme, first make sure you are following the rules and conditions, and then download the appropriate ACF plugin files and copy them into your plugin or theme. We recommend using the folder includes/acf within your codebase. Next, use the following code as a starter to […]

The post How to Include ACF in a Plugin or Theme appeared first on ACF.

]]>
To include ACF or ACF PRO within your plugin or theme, first make sure you are following the rules and conditions, and then download the appropriate ACF plugin files and copy them into your plugin or theme.

We recommend using the folder includes/acf within your codebase.

Next, use the following code as a starter to customize and include the ACF plugin in your plugin or theme.

Detecting if the ACF Plugin Is Installed

A user of your plugin or theme might also be using ACF for their site build. In that case, you should not proceed with bundling ACF or ACF PRO if the plugin is detected.

Use the following code to check if ACF or ACF PRO is installed:

if ( is_plugin_active( 'advanced-custom-fields/acf.php' ) || is_plugin_active( 'advanced-custom-fields-pro/acf.php' ) ) {
    return;
}

If the ACF or ACF PRO plugin is detected, you should not proceed with the following instructions.

Bootstrap the Bundled ACF

You will need to tell your plugin or theme to load the ACF files from where they are stored in your codebase:

// Define path and URL to the ACF plugin.
define( 'MY_ACF_PATH', get_stylesheet_directory() . '/includes/acf/' );
define( 'MY_ACF_URL', get_stylesheet_directory_uri() . '/includes/acf/' );

// 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', 'my_acf_settings_url');
function my_acf_settings_url( $url ) {
    return MY_ACF_URL;
}

Disabling the ACF Admin

Your users should not be able to manage ACF field groups, fields, or options pages. Therefore you are required to hide the ACF admin pages and menu using the following code:


// Hide the ACF admin menu item. add_filter('acf/settings/show_admin', '__return_false');

Including Fields Definitions

Along with the plugin files itself, you will also need to include the field group and option pages definitions. We recommend either registering your field groups with PHP, or including a local JSON folder of the JSON file exports of your field groups and option pages.

The post How to Include ACF in a Plugin or Theme appeared first on ACF.

]]>
Including ACF Within a Plugin or Theme https://www.advancedcustomfields.com/resources/including-acf-within-a-plugin-or-theme/ Thu, 23 Nov 2023 15:55:00 +0000 https://www.advancedcustomfields.com/resources/including-acf-within-a-plugin-or-theme/ Introduction The Advanced Custom Fields plugin is a powerful tool for developing bespoke websites and web-apps. Although designed primarily for individual use, it may also be used as a framework by both plugin and theme authors to power their free and premium products. This guide outlines the rules and terms for including ACF within your […]

The post Including ACF Within a Plugin or Theme appeared first on ACF.

]]>
Introduction

The Advanced Custom Fields plugin is a powerful tool for developing bespoke websites and web-apps. Although designed primarily for individual use, it may also be used as a framework by both plugin and theme authors to power their free and premium products.

This guide outlines the rules and terms for including ACF within your plugin or theme.

Rules

We do not allow bundling ACF or ACF PRO inside your own product as is, so ACF can be used by your users. It is should only be used to allow you to create fields and other ACF features required for your product.

When talking about a WordPress product, we can consider it as either a plugin, theme, premium plugin, or premium theme.

Our rules differ based on if your product is considered free or premium, and not whether it is a plugin or theme.

Please see the following table of rules that govern the inclusion of our plugins.

ACF ACF PRO
Include in a free plugin ✅ ❌
Include in a free theme ✅ ❌
Include in a premium plugin ✅ ✉️
Include in a premium theme ✅ ✉️
Include in an “ACF” plugin ❌ ❌
Share license key information ❌ ❌
Use as a selling point ❌ ❌


If you would like to include ACF PRO in your premium theme or plugin, please contact us to discuss the right subscription for you.

Marketing

Although we love the idea of you empowering your customers with intuitive publishing controls, we don’t love the idea of you advertising this to boost sales.

When including ACF PRO within your premium theme or premium plugin, please do not advertise this in your marketing material. For example, stay away from messages like “This theme also includes ACF PRO – normally $$$ – for free!”

Fields

You should provide field definitions (PHP or JSON) inside your plugin and disable the ACF menu. Your users should not be able to create new field groups or fields.

Support

Your customers shouldn’t contact us directly for support. They should contact you, and then you can contact us for help if you find there’s a problem with ACF.

Notes about “ACF” plugins

We do not allow ACF or ACF PRO to be included in any type of “ACF” extension or plugin. For example, a plugin named “ACF PRO Kit” that extends the plugin with extra features may not include ACF PRO. In this case, the “ACF PRO Kit” plugin should require ACF PRO to be installed.

Learn how to include ACF or ACF PRO in a theme or plugin.

The post Including ACF Within a Plugin or Theme appeared first on ACF.

]]>
How to Update https://www.advancedcustomfields.com/resources/how-to-update/ Thu, 23 Nov 2023 15:12:56 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=94891 This guide shows how to update the Advanced Custom Fields and Advanced Custom Fields PRO plugins on your website. Updates can be applied by either of the two methods shown below. One Click Update   The Advanced Custom fields plugin can be updated via the ‘Plugins’ page found in your WordPress website admin area. Updates […]

The post How to Update appeared first on ACF.

]]>
This guide shows how to update the Advanced Custom Fields and Advanced Custom Fields PRO plugins on your website. Updates can be applied by either of the two methods shown below.

One Click Update

The Plugins admin screen in WordPress, showing a new version of ACF is available and the "update now" button.

 

The Advanced Custom fields plugin can be updated via the ‘Plugins’ page found in your WordPress website admin area. Updates will appear when available and can be applied by clicking the update now button.

This method is also available for ACF PRO, but only when an active license is present. The license key can be entered on the ‘ACF -> Updates’ admin page.

If your license has not been activated and an update is available, you will be notified when viewing the ‘Plugins’ page. For more information, please see our guide to activating ACF PRO.

Manual Update

You may also apply plugin updates manually through the ‘Plugins’ page in the WordPress admin. Click Add New Plugin, and then Upload Plugin to start the process. The new version will overwrite the old, while leaving your fields and settings intact. You can download the Advanced Custom Fields plugin files from the WordPress repository page and the ACF PRO plugin files from your account.

Plugin updates can also be applied by copying and pasting the plugin files into your 'wp-content/plugins‘ folder. There is no loss or change to data whilst modifying the plugin’s files, making it safe to delete and re-upload the plugin folder.

Notes

Some updates may trigger a prompt to upgrade the database. The logic to check if a database upgrade is required runs in the admin area after a new version number is detected and is therefore fully compatible with both the update methods listed above.

Save

The post How to Update appeared first on ACF.

]]>
License Activations https://www.advancedcustomfields.com/resources/license-activations/ Wed, 15 Nov 2023 13:43:05 +0000 https://www.advancedcustomfields.com/?post_type=resource&p=444112 ACF PRO has always required a license to use PRO features and this will shortly be enforced in the plugin. Sites without an active license will display a warning in the ACF screens as of ACF 6.2.3, and will have the following restrictions in place starting with ACF 6.2.4. Activating your ACF PRO license key […]

The post License Activations appeared first on ACF.

]]>
ACF PRO has always required a license to use PRO features and this will shortly be enforced in the plugin. Sites without an active license will display a warning in the ACF screens as of ACF 6.2.3, and will have the following restrictions in place starting with ACF 6.2.4.

Activating your ACF PRO license key on a site enables automatic plugin updates and gives access to the premium features.

How it Works

The editor experience for ACF fields, ACF Blocks, and Options Pages will not change, and your site editors will be able to use all features as they do now. The following restrictions will only apply to ACF’s admin screens for editing field groups.

Until a valid license key has been activated for the site, it won’t be possible to create new or edit existing PRO fields (Gallery, Repeater, Flexible Content, or Clone), or use the premium features such as Options Pages and ACF Blocks.

If you previously activated a license and the subscription has expired, you will not be able to create new PRO fields, but you will be able to edit existing PRO field definitions.

To be clear, the editing and display of field data anywhere outside of the ACF admin screens will be unaffected by the status of the license.

The use of ACF on a site is in 3 different areas, and to clarify how these changes affect those areas take a look at the following table:

ACF Admin Editing Posts Displaying Data
Where you create and edit field groups, fields, and Options Pages in the ACF admin screen using PRO field types Where content editors enter field values and ACF Blocks when editing posts, pages & custom post types How the field values are rendered on the front end of the site by the theme or a page builder
Valid license activated 🟢 No impact 🟢 No impact 🟢 No impact
Expired license activated 🟢 Can edit existing ACF PRO fields, ACF Blocks, and Options Pages
🟠 Cannot create new ACF PRO fields, ACF Blocks, and Options Pages
🟢 No impact 🟢 No impact
No license activated 🟠 Cannot edit existing ACF PRO fields, ACF Blocks, and Options Pages
🟠 Cannot create new ACF PRO fields, ACF Blocks, and Options Pages
🟢 No impact 🟢 No impact

Development & Staging Activations

ACF PRO licenses have a limit on the number of production sites they can be activated on. However, we allow unlimited activations on development and staging sites. We detect if a site is a development or staging site using the following ruleset:

  • Dev: Is URL a single segment? (localhost)
  • Dev: Is URL an IP address? (192.168.0.1)
  • Dev: Does the URL contain a dev related segment? (dev.website.com, website.dev.cc)
  • Dev: Does the URL contain a dev-related subdomain? (test., testing., sandbox., dev., local.)
  • Dev: Does the URL contain a dev-related TLD? (.local, .loc, .localhost, .test)​​
  • Stage: Does the URL contain a stage-related subdomain? (stage., staging.)
  • Stage: Does the URL contain a stage-related parent? (sitename.wpengine.com, sitename.wpenginepowered.com, staging-sitename.kinsta.cloud, sitename.flywheelstaging.com)
  • Prod: All other URLs.

If your development or staging URL uses a different format then it will be classified as a production site and will count towards your license limit. To avoid that, please alter your URL or upgrade your subscription to a license with a larger site limit.

Any sites served in a subdirectory will be the root domain for its site type. For example, https://mysite.com/staging would be treated as a production URL.

Composer Installations

For users who install ACF via Composer, we recommend you define your license key in code.

ACF automatically activates your license when downloading the plugin via Composer for the site URL you provide in your auth.json file, and this will now be checked by the plugin to ensure the URL you provided is correct for that site before you can use PRO features.

Alternatively, you’ll need to activate ACF as usual by entering a key manually in the ‘Updates’ page of ACF’s admin.

Multisite Installations

If you have purchased an ACF PRO license to use on a WordPress multisite network, you must ensure that you have activated your license key for the main site of the network to enable automatic updates of the plugin.

If you purchased a license on or after 1st Feb 2024, you are required to activate your license key on any subsite which has the ACF PRO activated and you intend to use it on. Therefore, your license needs to have enough activations available for the subsites you require. You’ll also need to activate ACF on the network’s main site in order to receive automatic updates.

If you purchased a license before 1st Feb 2024, you do not need to activate the license key on individual subsites, just the main site of the network. The updates page will not be visible on any subsites.

Bundling ACF PRO With Other Plugins

If you have bundled ACF PRO with your theme or plugin, you must ensure that the bundling has been done as the bundling documentation has always required so your users aren’t impacted by these restrictions.

The bundling should be done as follows:

  • The ‘ACF’ menu should be removed, so your users can’t create fields
  • The field groups, fields, and options pages for your theme or plugin should be defined using PHP or JSON
  • The ACF ‘Updates’ page where the license key can be activated should be hidden
  • If a later version of ACF PRO is installed on the site, the bundling code should not execute

Learn more about the way to bundle ACF PRO in a third-party plugin or theme.

The post License Activations appeared first on ACF.

]]>