在wordpress中用post对象替换数组中的值
Replacing a value from an array with post object in wordpress
我有一系列不同的帖子和产品:
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/and 产品数组包含整个 post/product 对象,而不仅仅是 ID。我还使用树枝,这使得查询视图内的对象变得困难。所以我尝试的是从后端来做:
// 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 );
希望有人能理解我的问题。非常感谢任何支持。
我认为你的问题是你正在更新 foreach()
循环中的一个临时变量。并且您的更改未存储在您的 $gallerix
数组中。
试试这个:
<?php
foreach ($gallerix as $key => $gallerix_item) {
//...
$gallerix[$key]->linked_product = wc_get_product(...);
//...
}
?>
而不是更改 $gallerix_item
变量。
我有一系列不同的帖子和产品:
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/and 产品数组包含整个 post/product 对象,而不仅仅是 ID。我还使用树枝,这使得查询视图内的对象变得困难。所以我尝试的是从后端来做:
// 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 );
希望有人能理解我的问题。非常感谢任何支持。
我认为你的问题是你正在更新 foreach()
循环中的一个临时变量。并且您的更改未存储在您的 $gallerix
数组中。
试试这个:
<?php
foreach ($gallerix as $key => $gallerix_item) {
//...
$gallerix[$key]->linked_product = wc_get_product(...);
//...
}
?>
而不是更改 $gallerix_item
变量。