首页 > 解决方案 > PHP 'include' 可以用来复制 WP 中的 PHP + ACF 部分吗?

问题描述

我正在创建一个自定义 WP 主题 - 在网站内,有一个员工部分。使用“高级自定义字段”中继器,我使 WP 用户可以转到页面并添加/更改/删除员工成员。

我希望将此员工部分添加到网站上的其他位置,但只需要在一个位置进行更新 - 而不必进入多个页面进行相同的更改。

我对 WP dev 和 PHP 比较陌生,但这是我尝试过的:

我创建了一个只有员工部分的新 php 文件:

<?php /*  Template Name: StaffSection  */  ?>
<h1>Testing</h1><!-- This line runs fine -->
<?php<!-- None of this runs -->
// check if the repeater field has rows of data
if( have_rows('employees') ):
    // loop through the rows of data
while ( have_rows('employees') ) : the_row(); ?>
    <div class="col-lg-3 col-md-6 gap">
        <a href="<?php the_sub_field('employee-link'); ?>">
            <img class="leadership-img" src="<?php the_sub_field('employee-image'); ?>">
            <h4 class="position"><?php the_sub_field('employee-name'); ?></h4>
        </a>
        <p class="position"><?php the_sub_field('employee-title'); ?></p>
    </div>
<?php endwhile;
else :
// no rows found
endif; ?>

在我想要“包含”此部分的页面上:

<section id="leadership" class="section">
    <div class="container-fluid">
        <div class="wrapper">
            <div class="row leadership-section">
                <?php include 'staff-section.php'; ?>
            </div>
        </div>
    </div>
</section>

在 WP 中,我创建了一个新的 WP 页面并将其链接到我创建的“StaffSection”模板。我在该页面上有“高级自定义字段”来提取 WP 用户定义的内容。

我知道“包含”功能正在使用该测试 h1 标记,但知道为什么它没有读取下面的 php 转发器循环吗?

标签: phpwordpresswordpress-theming

解决方案


可能是if ( have_rows('employees') )... etc etc 正在返回 false,因为没有属于循环中定义的 post 对象的“员工”中继器。

我用来创建跨多个页面显示的字段的一种解决方案是创建辅助查询来检索转发器。

例如,我们可以这样做。1. 创建一个类别为“员工”的帖子 2. 转到 ACF 并设置逻辑,以便转发器仅出现在类别为“员工”的帖子上 3. 查询类别为“员工”的帖子对象 4. 从查询中访问转发器

<?php
$repeater_query = new WP_Query(array('category_name' => 'employees'))
if ($repeater_query->have_posts() ) {
   while ($repeater_query->have_posts() ) {
       $repeater_query->the_post();
       // check if the repeater field has rows of data
if( have_rows('employees') ):
    // loop through the rows of data
while ( have_rows('employees') ) : the_row(); ?>
    <div class="col-lg-3 col-md-6 gap">
        <a href="<?php the_sub_field('employee-link'); ?>">
            <img class="leadership-img" src="<?php the_sub_field('employee-image'); ?>">
            <h4 class="position"><?php the_sub_field('employee-name'); ?></h4>
        </a>
        <p class="position"><?php the_sub_field('employee-title'); ?></p>
    </div>
<?php endwhile;
else :
// no rows found
endif; 
   }
} wp_reset_postdata(); 

我希望这有帮助。干杯


推荐阅读