[英]Adding Advanced Custom Fields to Related Posts in Wordpress
我正在尝试向相关帖子功能添加自定义字段值,但是目前完全停留在此位置:
<div class="relatedposts">
<h3>Related posts</h3>
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>4, // Number of related posts to display.
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
while( $my_query->have_posts() ) {
$my_query->the_post();
?>
<div class="relatedthumb">
<a rel="external" href="<? the_permalink()?>">
<?php
$image = wp_get_attachment_image_src(get_field('image'), 'full');
print_r( $image[0] ); ?>
<?php the_title(); ?>
<img src="<?php echo $image[0]; ?>" />
</a>
</div>
<? }
}
$post = $orig_post;
wp_reset_query();
?>
</div>
这大部分都是有效的,因为它是在网上找到的代码,它只是将引用放置到我似乎缺少的自定义字段的位置。 我无法将其变量和print_r放在任何地方以查看结果。
foreach($ tags作为$ individual_tag){$ meta_values = get_post_meta($ post-> ID,'');
if (in_array('VALUE SEARCHING FOR',$meta_values) {
$tag_ids[] = $individual_tag->term_id;
} // if
} // foreach
填写适当的空格,这样可以正确过滤标签。
HTH,
= C =
使用ACF,您可以将帖子ID传递到get_field
和the_field
函数:
$image_id = get_field( 'image', $post -> ID );
如果您使用没有设置帖子ID的函数,则这些函数可能会返回某些其他全局初始化的帖子的字段值。
因此,您的附件图像获取器(在相关帖子WP_Query
循环内部)将类似于
$image = wp_get_attachment_image_src(get_field('image', get_the_ID()), 'full');
确保将您的ACF字段类型设置为image及其所需的变体:ID,图像对象或图像URL。 然后, get_field
将返回图像的附件ID,图像对象或图像URL。
在您的代码示例中,假设wp_get_attachment_image_src
需要附件ID,则返回ID是正确的选择。
编辑:
我刚刚意识到,ACF图像字段可能不会以正常的方式将图像保存到WP附件系统中。 尝试将图像作为一个对象返回,并var_dump
该对象的内容,以查看full
尺寸图像URL所在的位置。
我可能是错的,并且wp_get_attachment_image_src
可能会正常工作。
好的,任何可能发现这有用的人,我都有一个解决方案来显示ACF字段:
<div class="related grid clear">
<h2>Related posts</h2>
<?php
$orig_post = $post;
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
$tag_ids = array();
foreach($tags as $individual_tag) $tag_ids[] = $individual_tag->term_id;
$args=array(
'tag__in' => $tag_ids,
'post__not_in' => array($post->ID),
'posts_per_page'=>9,
'caller_get_posts'=>1
);
$my_query = new wp_query( $args );
if($my_query->have_posts()) {
while($my_query->have_posts()) {
$my_query->the_post();
$image = get_field('hero_image', get_the_ID());
$introduction = get_field('introduction');
?>
<article class="grid-item" data-permalink="<? the_permalink()?>">
<div style="background-image: url(<?php echo $image; ?>);"></div>
<h3><?php the_title(); ?></h3>
<p><?php echo $introduction; ?></p>
</article>
<?
}
}
$post = $orig_post;
wp_reset_postdata();
wp_reset_query();
}
?>
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.