我正在尝试为相关帖子功能添加自定义字段值,但目前完全陷入困境:
<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 as $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
填写适当的空白,这应该可以正确过滤您的标签。
呵呵,
=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 字段类型设置为图像及其所需的变体:ID、图像对象或图像 URL。 然后,get_field
将返回图像的附件 ID、图像对象或图像 URL。
在代码示例中,返回 ID 是正确的选择,假设wp_get_attachment_image_src
需要附件 ID。
编辑:
我刚刚意识到,ACF图像字段可能不会以WP的正常方式将图像保存到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>