php - 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 转发器循环吗?
解决方案
可能是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();
我希望这有帮助。干杯
推荐阅读
- java - 在 Eclipse 上创建 Alfresco maven 原型时出错
- angular - CORS - 撤销令牌时没有“访问控制允许来源”
- reactjs - 沿圆圈均匀对齐进度条
- javascript - 如何在没有 onDBLClick 的情况下制作第二个 onclick()
- html - 为什么这段代码不能帮助我实现一个空白井字游戏板?
- jquery - 网站出现 508 错误,但我在任何地方都找不到
- electron - electron-builder 构建过程中 buildResources 文件夹的目的是什么?
- android - Android资源传递给函数时的不同值
- python - 按列有效地对事件日志数据库进行分类
- android - Import Github repositories button disabled when go to import github repo in jFrog/Bintray to upload library