Nick Gazzillo
Nick Gazzillo

Reputation: 131

WP ACF relationship field returning empty array in functions.php file

I am trying to generate an array in my wp functions.php file that has a designer as the key and all their products as the value. Currently an acf relationship field is used in the product's page to link to the designer's page. This is the code I have tried so far. It works without any problem when placed in my header.php file, but when I place this code block in the functions.php file it is not working because the get_field('designer_products') returns either an empty array or an empty string, but not an array with each designer's wp_post object like it should.

$argsT = array('post_type' =>'product', 'orderby' => 'rand', 'order' => 'ASC');
$loopT = new WP_Query($argsT);
$allDesigners = array();
if ($loopT->have_posts()) {
  while ($loopT->have_posts()) {
    $loopT -> the_post();
    $thisProduct = get_the_title();
    $designerPosts = get_field('designer_product');
    foreach ($designerPosts as $designerPost) {
      $thisDesigner = $designerPost->post_title;
      if ($allDesigners[$thisDesigner]){
        $allDesigners[$thisDesigner] .= " " . $thisProduct;
      } else {
        $allDesigners[$thisDesigner] = $thisProduct;
      }
    }
  }
}

Upvotes: 2

Views: 1471

Answers (2)

Nick Gazzillo
Nick Gazzillo

Reputation: 131

In case anyone finds this in the future, I ended up getting it to work by wrapping my code in a function that returns the array, and then calling the function later and setting it equal to a variable. Previously I was just trying to run the code right away, but it seems that because of the order that wp loads functions.php file, the posts might not have had the information available when the loop was called.

Upvotes: 1

incredimike
incredimike

Reputation: 486

Outside of a page/post "single" template, the get_field function doesn't know which post to reference. You should try passing in the posts ID as the second parameter to the get_field fucntion.

See my edits below (updated):

$loopT = new WP_Query(array('post_type' =>'product', 'orderby' => 'rand', 'order' => 'ASC'));
$allDesigners = array();

if (!empty($loopT->posts)) {
    foreach ($loopT->posts as $product) {
        $product_title = $product->post_title;
        $designer_product = get_field('designer_product', $product->ID);

        foreach ($designer_product as $item) {
            $designer = $item->post_title;

            if ($allDesigners[$designer]){
                $allDesigners[$designer] .= " " . $product_title;
            } else {
                $allDesigners[$designer] = $product_title;
            }
        }
    }
}

Check out the official ACF documentation for get_field() for more details on how this works.

Upvotes: 0

Related Questions