WordPressな日々

WordPressの制作覚書

アクションフックについて

featured-contentの'do_action( 'twentyfourteen_featured_posts_before' );'と'do_action( 'twentyfourteen_featured_posts_after' );'は、アクション・フックと呼ばれるもので、この場所で任意の関数を実行できる。do_action()に引数はフックの場所を識別する名前。

add_action( 'twentyfourteen_featured_posts_after', 'display_text' );

というように、add_action(フック場所、関数)という形で実行する関数を定義する。

参考: WordPress › Support » featured_posts_before and featured_posts_after

テーマ’TwentyFourteen'で、アクションフックの使用例。

// Include the featured content template.
    <div id="featured-content" class="featured-content">
       <div class="featured-content-inner">
       <?php
        /**
         * Fires before the Twenty Fourteen featured content.
         *
         * @since Twenty Fourteen 1.0
         */
        do_action( 'twentyfourteen_featured_posts_before' );

        $featured_posts = twentyfourteen_get_featured_posts();
        foreach ( (array) $featured_posts as $order => $post ) :
            setup_postdata( $post );

             // Include the featured content template.
            get_template_part( 'content', 'featured-post' );
        endforeach;

        /**
         * Fires after the Twenty Fourteen featured content.
         *
         * @since Twenty Fourteen 1.0
         */
        do_action( 'twentyfourteen_featured_posts_after' );

        wp_reset_postdata();
       ?>
       </div><!-- .featured-content-inner -->
    </div><!-- #featured-content .featured-content -->

フィルターフックについて

フィルターとは間接的に関数を呼び出すしくみ。複数の関数をひとつのフィルターで呼び出すこともできる。

blog1.dd-company.com

apply_filters と add_filter の使用方法。 | WEBデザイン&WEBプログラミング -sei2の日記-

add_filterは、フィルターを追加する関数。

add_filter(フィルターフック名、コールバック関数)

として使うが、コールバック関数に静的クラス・メソッドを使う場合は、

add_filter(フィルターフック名、array (クラス名, メソッド名))

とする。

該当クラス内でadd_filter()を記述する場合は、自クラス名を'CLASS'で参照する。

ちなみに静的クラスではなく、インスタンス内で使う場合は、

add_filter(フィルターフック名、array($this, メソッド名))

とする。

参考:関数リファレンス/add filter - WordPress Codex 日本語版

get_template_part()の使い方

get_template_part()は、任意のテンプレートを読み込む関数。関数リファレンス/get template part - WordPress Codex 日本語版

<?php get_template_part( $slug, $name ); ?>

として使うが、$nameは省略可。

<?php get_template_part( 'content'); ?>

とすると、テーマディレクトリのcontent.phpを読み込む。

子テーマ使用時に、

<?php get_template_part( 'loop', 'index' ); ?>

とすると、

  • 子テーマのloop-index.php
  • 親テーマのloop-indes.php
  • 子テーマのloop.php
  • 親テーマのloop.php

の順に検索して読み込む。

テーマディレクトリのサブディレクトリ内のファイルを読み込むには、

<?php get_template_part( 'partials/content', 'page' ); ?>

のようにする。

テンプレートに変数を渡す

テンプレートに変数を渡すには、

<?php set_query_var( $var, $value ) ?>

を使う。

$var テンプレートでの変数名(クエリキー) $value テンプレートに渡す値