如何在 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 插件吗?

在您的页面问答 创建一个包含 2 个字段 repeater fieldQuestion

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','wrapper' => array(
                        'width' => '','default_value' => '','placeholder' => '','prepend' => '','append' => '','maxlength' => '',array(
                    'key' => 'field_60254952fa15f','label' => 'answer','name' => 'answer','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;