Search code examples
phpwordpressadvanced-custom-fieldsacfpro

Using an ACF text field to display metatag on specific pages. Can't get the acf field to return correctly in functions.php


I am in the process of implementing ios smart banners on our site, however we only want it to display on selected pages. I have set up an ACF text field, where I have the page IDs as a comma separated string ( eg: 1234, 1235, 1236, 1237 ).

In the functions.php file I have created the following function to add the metatag to the correct pages:

function enable_app_banner()
{
    $enabledpages = the_field('allowed_pages', 'options');
    
    if (is_page([$enabledpages])) {
        echo '<meta name="apple-itunes-app" content="app-id=12345678">';
    }
}
add_action('wp_head', 'enable_app_banner');

However this is not getting me the result I require, annoyingly it works when hardcoding in the values into the array as such;

if (is_page([1234, 1235, 1236])) {
        echo '<meta name="apple-itunes-app" content="app-id=12345678">';
    }

Any assistance would be greatly appreciated!


Solution

  • As you mentioned you setup an ACF text field which gives you a comma separated string ( eg: 1234, 1235, 1236, 1237 ). but is_page() method accepts array of IDs.

    You have to convert the string into array first. Use explode() method to do so:

    function enable_app_banner() {
      $enabledpages = the_field('allowed_pages', 'options');
      // Using explode method to convert comma separated string into an array.
      $enabledPagesArray = explode(', ', $enabledpages);
    
      if (is_page($enabledPagesArray)) {
        echo '<meta name="apple-itunes-app" content="app-id=12345678">';
      }
    }