Search code examples
wordpressadvanced-custom-fields

Why function with get_field returns NULL?


I don't understand why a function with get_field inside returns an error, while get_field without the function works fine.

$args = [
    'taxonomy'      => 'product_cat',
    'parent'         => 88,
];

$prod_cats = get_terms( $args );

function getImageId(){
    var_dump( get_field( 'image', $prod_cats[0] ) );
}

getImageId(); // NULL
var_dump( get_field( 'image', $prod_cats[0] ) ); // int(1854)

I expect getImageId() to return int(1854).


Solution

  • I think the variable $prod_cats is not in the same scope as the function getImageId. Inside the function, $prod_cats is also not defined, and therefore it is NULL. Try passing the $prod_cats as an argument to the function:

    $args = array(
        'taxonomy' => 'product_cat',
        'parent'   => 88,
    );
    
    $prod_cats = get_terms( $args );
    
    function getImageId( $prod_cats ) {
        var_dump( get_field( 'image', $prod_cats[0] ) );
    }
    
    getImageId( $prod_cats ); // int(1854)