首页 > 解决方案 > 在 WordPress 中使用 ACF 转发器显示特定的博客文章

问题描述

我正在尝试在我的 WordPress 网站上创建使用 ACF 归档的简单重复器。我想要得到的是让管理员在文章底部显示“其他有趣的”博客文章。

到目前为止,我已经使用 Wp_Query 创建了一个循环:

<?php
if( have_rows('featured') ): while( have_rows('featured') ) : the_row();    
?>  
    
<div class="container-fluid blog-container medium-container">
<div class="row">
<div class="col-12 blog-one">

<?php
// Get ACF sub field
$get_ids = get_sub_field('article_id');
// Make them display with comma
$show_ids = implode(', ', $get_ids);

   // Featured blog list query
   $blog = new WP_Query( array(
   'posts_per_page' => 5,
   'order' => 'DESC',

   // Display post with specific ID using ACF repeater field inside array
   'post__in' => array($show_ids)
));

...
...
...

<?php endwhile; endif; ?>   

因此,目标是在后端显示管理员包含的数字(帖子 ID) - 将它们放在“post__in”内的数组中。但是我的代码不起作用。任何想法如何解决这个问题?

标签: phpwordpresswoocommerceadvanced-custom-fieldsacfpro

解决方案


高级自定义字段具有发布对象字段类型。您可以将其配置为接受多个帖子,然后它将作为帖子对象数组 (WP_Post) 为您返回。这避免了循环遍历转发器字段以构建查询参数的任何需要。

推荐解决方案

首先,将repeater 字段替换为post object 字段。设置post类型为post,允许null为true,multiple为true。

然后,您可以调整代码以显示这些帖子。

例子:

<?php if ( $featured_posts = get_field( 'featured' ) ) : ?>
    <div class="container-fluid blog-container medium-container">
        <div class="row">
            <div class="col-12 blog-one">
                <?php foreach ( $featured_posts as $post ) {
                    setup_postdata( $post );

                    // Do whatever you need to do to display the post here...
                } ?>
                . . .
<?php endif; 

文档:https ://www.advancedcustomfields.com/resources/post-object/

修复现有代码

如果您更愿意修复已有的代码,则需要重新考虑循环。

每次遍历转发器字段时,您都会进入并获取为帖子输入的 ID(子字段)。您需要先收集所有这些,然后使用它来构建您的查询。

例子:

$posts_ids = [];

if ( have_rows( 'featured' ) ) : while( have_rows( 'featured' ) ) : the_row();
    $post_ids[] = get_sub_field( 'article_id' );
endwhile; endif;

// Let's drop any blank elements and force them all to integers.
$filtered_ids = array_map( 'intval', array_filter( $post_ids ) );

$blog_query = new WP_Query( [
    'post__in' => $filtered_ids,
] );

您可以添加更多检查、清理等。无论哪种方式,让 ACF 为您执行此操作并选择推荐的解决方案仍然要好得多。


推荐阅读