>  기사  >  CMS 튜토리얼  >  질문과 답변 시스템을 자동으로 생성하는 WordPress 플러그인을 개발하는 방법

질문과 답변 시스템을 자동으로 생성하는 WordPress 플러그인을 개발하는 방법

王林
王林원래의
2023-09-05 15:52:461169검색

질문과 답변 시스템을 자동으로 생성하는 WordPress 플러그인을 개발하는 방법

Q&A 시스템을 자동으로 생성하는 WordPress 플러그인을 개발하는 방법

소개:
현대 인터넷 시대에 Q&A 웹사이트가 점점 더 인기를 얻고 있습니다. 질문과 답변에 대한 사용자의 요구를 충족시키기 위해 이 기사에서는 질문과 답변 시스템을 자동으로 생성하는 WordPress 플러그인을 개발하는 방법을 소개합니다. 이 플러그인을 사용하면 Q&A 플랫폼을 쉽게 만들어 웹사이트를 더욱 대화형이고 매력적으로 만들 수 있습니다.

1단계: 사용자 정의 게시물 유형 만들기(Post Type)
워드프레스에서 사용자 정의 게시물 유형은 기본 게시물과 페이지를 확장할 수 있는 기능입니다. "질문"이라는 사용자 정의 데이터 유형을 만들어야 합니다.

function create_question_post_type() {
  $labels = array(
    'name' => 'Questions',
    'singular_name' => 'Question',
    'add_new' => 'Add New',
    'add_new_item' => 'Add New Question',
    'edit_item' => 'Edit Question',
    'new_item' => 'New Question',
    'view_item' => 'View Question',
    'search_items' => 'Search Questions',
    'not_found' => 'No questions found',
    'not_found_in_trash' => 'No questions found in trash',
    'parent_item_colon' => '',
    'menu_name' => 'Questions'
  );

  $args = array(
    'labels' => $labels,
    'public' => true,
    'has_archive' => true,
    'rewrite' => array('slug' => 'questions'),
    'supports' => array('title', 'editor', 'author')
  );

  register_post_type('question', $args);
}

add_action('init', 'create_question_post_type');

2단계: 질문과 답변을 위한 메타 필드 만들기
질문 카테고리, 답변 작성자 등과 같은 추가 정보 필드를 질문과 답변에 추가해야 합니다. 메타필드를 추가하면 질문과 답변을 편집할 때 이러한 추가 정보 필드를 추가하고 관리할 수 있습니다.

function add_question_meta_fields() {
  add_meta_box('question_category', 'Category', 'question_category_callback', 'question', 'side', 'default');
}

function question_category_callback($post) {
  $value = get_post_meta($post->ID, 'question_category', true);
  echo '<input type="text" name="question_category" value="' . esc_attr($value) . '" />';
}

function save_question_meta_fields($post_id) {
  if (array_key_exists('question_category', $_POST)) {
    update_post_meta(
      $post_id,
      'question_category',
      sanitize_text_field($_POST['question_category'])
    );
  }
}

add_action('add_meta_boxes_question', 'add_question_meta_fields');
add_action('save_post_question', 'save_question_meta_fields');

3단계: Q&A 시스템 템플릿 만들기
질문과 답변을 표시하려면 Q&A 시스템 템플릿을 만들어야 합니다. WordPress의 템플릿 파일(예: single-question.php)을 사용하여 이를 달성할 수 있습니다.

<?php /* Template name: Question Template */ ?>

<?php get_header(); ?>

<div id="primary">
  <main id="main" class="site-main" role="main">

    <?php while (have_posts()): the_post(); ?>

      <article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
        <header class="entry-header">
          <h1 class="entry-title"><?php the_title(); ?></h1>
        </header>

        <div class="entry-content">
          <?php the_content(); ?>
        </div>

        <?php $answers = get_post_meta(get_the_ID(), 'answers', true); ?>
        <?php if (!empty($answers)): ?>
          <section class="answers">
            <h2>Answers</h2>
            <ul>
              <?php foreach ($answers as $answer): ?>
                <li><?php echo $answer; ?></li>
              <?php endforeach; ?>
            </ul>            
          </section>
        <?php endif; ?>
      </article>

    <?php endwhile; ?>

  </main>
</div>

<?php get_sidebar(); ?>
<?php get_footer(); ?>

4단계: Q&A 제출 및 표시 양식 만들기
사용자가 질문과 답변을 제출하고 데이터베이스에 저장할 수 있는 프런트 엔드 양식을 만들어야 합니다. 그런 다음 이러한 질문과 답변을 템플릿에 표시해야 합니다.

function question_form_shortcode() {
  ob_start(); ?>

  <form id="question-form" method="post">
    <label for="question-title">Question Title</label>
    <input type="text" id="question-title" name="question-title" required>

    <label for="question-content">Question Content</label>
    <textarea id="question-content" name="question-content" required></textarea>

    <label for="answer-content">Your Answer</label>
    <textarea id="answer-content" name="answer-content" required></textarea>

    <input type="submit" value="Submit">
  </form>

  <?php return ob_get_clean();
}

add_shortcode('question_form', 'question_form_shortcode');

function save_question_and_answer() {
  if (isset($_POST['question-title']) && isset($_POST['question-content']) && isset($_POST['answer-content'])) {
    $question_title = sanitize_text_field($_POST['question-title']);
    $question_content = wp_kses_post($_POST['question-content']);
    $answer_content = wp_kses_post($_POST['answer-content']);

    $question_id = wp_insert_post(array(
      'post_title' => $question_title,
      'post_content' => $question_content,
      'post_type' => 'question',
      'post_status' => 'publish'
    ));

    $answers = get_post_meta($question_id, 'answers', true);
    $answers[] = $answer_content;
    update_post_meta($question_id, 'answers', $answers);
  }
}

add_action('init', 'save_question_and_answer');

결론:
이 기사의 지침에 따라 질문 및 답변 시스템을 자동으로 생성하는 WordPress 플러그인을 개발할 수 있습니다. 이 플러그인을 사용하면 Q&A 플랫폼을 쉽게 생성하여 상호작용성과 매력을 높일 수 있습니다. 사용자와 웹사이트에 맞게 추가 기능을 추가하고 스타일을 맞춤설정할 수 있습니다. 귀하의 개발 성공을 기원합니다!

위 내용은 질문과 답변 시스템을 자동으로 생성하는 WordPress 플러그인을 개발하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.