By default, ACF gives you the ability to show fields based on it being a particular page. While the page that the rule equals is selected based on the name of the page, behind the scenes the condition is met based on the ID of the page.
While this is fine if you’re creating a field group for one website, if you’re looking to use ACF to create and display fields for a particular page template in a plugin – especially if the plugin creates that page on activation – it can cause headaches as every site will assign a different ID to the page that is generated.
Note: This tutorial is assuming that you are including the fields programmatically.
The best way to ensure the fields are displayed on the edit screen of the page created by the plugin is by assigning the rule to the page slug. However, that isn’t possible by default with ACF.
Luckily, assigning the page-slug to the rule isn’t as hard as it might first seem.
See Code Snippet One.
The first thing we do is use the function get_page_by_path(). This function allows us to define a slug for WordPress to look for. If the page exists, it will return an array of information about the post. If it doesn’t, it will return NULL.
We assign the array to a variable, in this case $pagecheck.
We then take $pagecheck and get the object of ID and the value of it to a new variable, in this case $pageid.
All we have to do then is find the location array of the ACF field group and place the variable into the value of the key value. Normally this will be the ID of the page selected – something like: ‘123’ if you’ve selected the rule “Page > is equal to > Page Name.
Remove the number and the quote marks and place the variable (see code snippet 2).
Hey presto, you’re now able to define the page slug of the page you want the field group to be associated with.
This snippet takes the slug and converts it to the ID of that page.
// Convert slug to ID for location value. $pagecheck = get_page_by_path('slug-goes-here'); $pageid = $pagecheck->ID;
Where the location rules are, add the $pageid variable to value. This will call the ID of the page stored in the variable.
'location' => array ( array ( array ( 'param' => 'page', 'operator' => '==', 'value' => $pageid, ), ), ),