个性化阅读
专注于IT技术分析

可以使用PHP”include”来复制WP中的PHP + ACF section吗?

点击下载

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

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

我对WP开发人员和PHP相对较新, 但这是我尝试过的方法:

我创建了一个仅包含employee section的新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; ?>

在我要”include”此section的页面上:

<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用户定义的内容。

我知道’include’函数正在与该测试h1标签一起使用, 但是知道为什么它没有读取下面的php Repeater循环吗?


#1


可能是if(have_rows(’employees’))…等返回了错误, 因为没有” employees”转发器属于循环中定义的post对象。

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

例如, 我们可以做到这一点。 1.创建一个类别为’employees’的帖子2.转到ACF并设置逻辑, 以便该转发器仅出现在类别为’employees’的帖子中3.查询类别为’employees’的帖子对象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(); 

我希望这有帮助。干杯

赞(0)
未经允许不得转载:srcmini » 可以使用PHP”include”来复制WP中的PHP + ACF section吗?

评论 抢沙发

评论前必须登录!