在wordpress中用post对象替换数组中的值

时间:2018-01-12 18:18:20

标签: php arrays wordpress advanced-custom-fields

我有一系列不同的帖子和产品:

array (size=2)
   0 => 
      array (size=2)
         'acf_fc_layout' => string 'post'
         'linked_post' => int 6802
   1 => 
      array (size=2)
         'acf_fc_layout' => string 'product'
         'linked_product' => int 5140

我现在的问题是我希望post /和product数组包含整个post / product对象而不仅仅是ID。我也使用twig,这使得查询视图内的对象变得困难。所以我试过的是从后端做到这一点:

// Getting the array of Posts and Products
$gallerix = get_field('gallerix_layout', 'options');

// Trying to overwrite the value in the loop
foreach ($gallerix as $gallerix_item) {

    if ( $gallerix_item->acf_fc_layout == 'product' ) {

       $gallerix_item->linked_product = wc_get_product( $gallerix_item->linked_product );

    } elseif ( $gallerix_item->acf_fc_layout == 'post' ) {

       $gallerix_item->linked_post = get_post( $gallerix_item->linked_post );

    }
}

// Pass the array to Timber/Twig
$context['gallerix'] = $gallerix;

// Render twig template
Timber::render( 'views/template.twig', $context );

希望有人理解我的问题。非常感谢任何支持。

1 个答案:

答案 0 :(得分:1)

我认为您的问题是您正在更新foreach()循环中的临时变量。并且您的更改未存储在$gallerix数组中。

试试这个:

<?php
foreach ($gallerix as $key => $gallerix_item) {
   //...
   $gallerix[$key]->linked_product = wc_get_product(...);
   //...
}
?>

而不是更改$gallerix_item变量。