Search code examples
wordpresswordpress-gutenberg

Expanding a query using get_post_field to use an array in functions.php


I'm trying to expand the below query to use an array of page slugs (rather than just the one 'my-page') but can't get it to work, can anyone please explain why?

function alerts_enqueue() {
    $current_screen = get_current_screen(); 
    if('post' === $current_screen->base && get_post_field('post_name',get_the_ID()) === 'my-page') {
       wp_enqueue_script('alert-script',get_stylesheet_directory_uri().'/js/alerts.js',array(),null,true); 
   }
}
add_action('enqueue_block_editor_assets','alerts_enqueue');

Tried using an array object like below with no joy


function alerts_enqueue() {
    $current_screen = get_current_screen(); 
    if('post' === $current_screen->base && get_post_field('post_name',get_the_ID()) === array(['contact-us', 'about-us'])) {
       wp_enqueue_script('alert-script',get_stylesheet_directory_uri().'/js/alerts.js',array(),null,true); 
   }
}
add_action('enqueue_block_editor_assets','alerts_enqueue');

Solution

  • You can achieve it like this:

    function alerts_enqueue() {
        $current_screen = get_current_screen(); 
        if('post' === $current_screen->base && in_array(get_post_field('post_name',get_the_ID()), ['contact-us', 'about-us])) {
           wp_enqueue_script('alert-script',get_stylesheet_directory_uri().'/js/alerts.js',array(),null,true); 
       }
    }
    add_action('enqueue_block_editor_assets','alerts_enqueue');
    

    Explanation:

    • in your attempt you compared the post name with an array of post names
    • a post name is a string and cannot possibly be equal with an array of strings
    • instead you wanted to find out whether your array of post-names contains the post name of your post
    • for this purpose, you can use in_array, which checks whether the needle (which is your post name) is contained by the haystack (which is your array of post names)