首页 > 解决方案 > 生成动态 term_id - 返回图像字段 - ACF

问题描述

这可行,除了我想$term_id = 22; 动态生成,所以它是每个产品的正确“品牌”。

 <?php
 $taxonomy_prefix = 'brand';
 $term_id = 22;
 $term_id_prefixed = $taxonomy_prefix .'_'. $term_id;
 $brand_logo = get_field( 'brand-logo', $term_id_prefixed );

if ( $brand_logo ) { ?>
<img src="<?php echo $brand_logo['url']; ?>" />
<?php }
?>         

这里的代码适用于文本字段(品牌信息) -$term_id每个帖子都是动态的..希望它进一步澄清我的问题。

<?php 
$terms = get_the_terms( $post->ID , 'brand' ); 
$term_id = $terms[0]->term_id;
the_field('brand info', 'term_'.$term_id); 
?>

标签: phpwordpressadvanced-custom-fields

解决方案


您的问题对生成 term_id 不是很清楚。

您需要确定生成 term_id 的标准。它应该基于 Post Id 或其他一些 ID。

如果你想分配 Post Id,那么你可以这样做

    global $post;

$term_id =  $post->ID;

但是,您可以使用 uniqid() 生成随机数

喜欢,$term_id = uniqid();

或者

您可以将rand()pow( ) 一起使用来实现这一点:

$digits = 3;
echo rand(pow(10, $digits-1), pow(10, $digits)-1);

这将输出一个介于 100 和 999 之间的数字。这是因为 10^2 = 100 和 10^3 = 1000,然后您需要将其减去 1 以使其处于所需范围内。

如果 005 也是一个有效示例,您将使用以下代码用前导零填充它:

$digits = 3;
echo str_pad(rand(0, pow(10, $digits)-1), $digits, '0', STR_PAD_LEFT);

推荐阅读