php - 如何在 WordPress 中实现问答块
问题描述
我的网站布局中有“问题和答案”块(它由“h3” - 问题,“p” - 答案组成)。我找到了这样的实现:
- 为页面模板创建自定义字段(问题、答案) - 发布
- 插入到我需要“问题和答案”块的页面,所以它看起来像这样:
<?php $posts = get_posts( array() );
foreach( $posts as $post ){
setup_postdata($post);?>
<div class="table_bg">
<h3 class="question"><?php the_field('question'); ?></h3>
<p class="answer"><?php the_field('answer'); ?></p></div>
<?php}
wp_reset_postdata();?>
但问题是我需要为需要“问题和答案”块的每个页面创建一个新类别的帖子(和帖子本身),例如:
- 页面“主页”-> 将“问题和答案发布到主页”(在“主页的问题和答案”类别中),如果我需要更多,我只能添加 1 个问题和 1 个答案 - 我需要创建新帖子。也许在 Wordpress 中有更好的解决方案?
解决方案
你使用 ACF 插件吗?
在您的页面问答中创建一个repeater field
包含 2 个字段Question
和Answer
<?php
$questions = get_field('questions');
if(!empty($questions)){
foreach ($questions as $key => $question) {
echo '<h3>'.$question['question'].'</h3>';
echo '<p>'.$question['answer'].'</p>';
}
}
?>
如果您使用的是 YOAST SEO 插件,那么有一个古腾堡块可以满足您的需求。 https://yoast.com/how-to-build-an-faq-page/
此 ACF 字段的 PHP 代码
if( function_exists('acf_add_local_field_group') ):
acf_add_local_field_group(array(
'key' => 'group_602549386ffbd',
'title' => 'questions & answers',
'fields' => array(
array(
'key' => 'field_60254947fa15d',
'label' => 'questions',
'name' => 'questions',
'type' => 'repeater',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => '',
),
'collapsed' => '',
'min' => 0,
'max' => 0,
'layout' => 'table',
'button_label' => '',
'sub_fields' => array(
array(
'key' => 'field_6025494cfa15e',
'label' => 'question',
'name' => 'question',
'type' => 'text',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => '',
),
'default_value' => '',
'placeholder' => '',
'prepend' => '',
'append' => '',
'maxlength' => '',
),
array(
'key' => 'field_60254952fa15f',
'label' => 'answer',
'name' => 'answer',
'type' => 'text',
'instructions' => '',
'required' => 0,
'conditional_logic' => 0,
'wrapper' => array(
'width' => '',
'class' => '',
'id' => '',
),
'default_value' => '',
'placeholder' => '',
'prepend' => '',
'append' => '',
'maxlength' => '',
),
),
),
),
'location' => array(
array(
array(
'param' => 'post_type',
'operator' => '==',
'value' => 'page',
),
),
),
'menu_order' => 0,
'position' => 'normal',
'style' => 'default',
'label_placement' => 'top',
'instruction_placement' => 'label',
'hide_on_screen' => '',
'active' => true,
'description' => '',
));
endif;
推荐阅读
- php - Wordpress ajax 仅在包含类别帖子的页面上重复
- python-3.x - 'int' 对象在 lambda 函数内不可订阅
- java - 或者查询不支持spring数据dynamodb
- css - SVG 背景图像顶部有奇怪的线条
- scala - 在播放框架中为复选框动态生成标签
- r - 使用带有变量的 grepl
- linux - 为什么用我自己的 deb 自定义 sources.list 总是找不到 Ubuntu 的 deb
- twitter-bootstrap - Bootstrap 4,不同内容宽度的列之间的间距相等
- python - 无法使用 Pip 安装更新 Python 库
- android - 领域 SyncConfiguration.Builder 已弃用