LoginSignup
10
10

More than 5 years have passed since last update.

WordPressのカスタムフィールドを検索する

Last updated at Posted at 2015-12-16

手順

  • Advanced Custom Fieldをインストール
  • カスタムポストタイプを作る
  • カスタムフィールドを準備
  • データを入力
  • get_postsに meta_queryオプションで検索する

カスタムポストタイプを作る

functions.php
<?php
function init_func() {
    register_post_type('book', array(
        'labels' => array(
            'name' => '絵本',
        ),
        'public' => true,
        'has_archive' => true,
        'menu_position' => 5,
    ));
}
add_action('init', 'init_func');

テンプレートを作る

archive-book.php
<!doctype html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>絵本一覧</title>
    <?php wp_head(); ?>
</head>
<body>
    <h1>絵本一覧</h1>
    <ul>
        <li>絵本の名前(対象年齢)</li>
    </ul>
    <?php wp_footer(); ?>
</body>
</html>

データを表示する(検索なし)

archive-book.php
...
<ul>
        <?php $books = get_posts(array(
            'post_type' => 'book'
            )); ?>
        <?php foreach ($books as $post): setup_postdata($post); ?>
            <li><?php the_field('bookname'); ?><?php the_field('age'); ?></li>
        <?php endforeach; wp_reset_postdata(); ?>
</ul>

フォームを作る

archive-book.php
    <form action="" method="get">
        <input type="text" name="bookname" placeholder="書名" />
        <input type="submit" value="Submit"/>
    </form>

条件を付け足す

archive-book.php
            'meta_query' => array(
                array(
                    'key' => 'bookname',
                    'value' => $_REQUEST['bookname'],
                    'compare' => 'like',
                    )
                )
10
10
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
10