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;
}
}
}
}