LoginSignup
38

More than 5 years have passed since last update.

WordPress 4.4 の新機能や変更点簡易まとめ

Last updated at Posted at 2015-11-27

WordPress 4.4 が 12 月 8 日にリリース予定です。先日 WordPress 4.4 RC 版がリリースされたので、投稿まわりを中心に変更点を追ってみました。間違っているところもあるかもしれませんので、必ず自身でも確認するようにしてください。

追加された主な機能

  • Twenty Sixteen
  • タームメタ (Term metadata)
  • レスポンシブイメージ
  • 他サイトの記事の埋め込み(oEmbed)
  • REST API

投稿(ポスト)

投稿(ポスト)関連の変更点。

追加されたテンプレートタグ

get_the_post_thumbnail_url()

wp-includes/post-thumbnail-template.php:180 行目付近

/**
 * Return the post thumbnail URL.
 *
 * @since 4.4.0
 *
 * @param int|WP_Post  $post Optional. Post ID or WP_Post object.  Default is global `$post`.
 * @param string|array $size Optional. Registered image size to retrieve the source for or a flat
 *                           array of height and width dimensions. Default 'post-thumbnail'.
 * @return string|false Post thumbnail URL or false if no URL is available.
 */
function get_the_post_thumbnail_url( $post = null, $size = 'post-thumbnail' ) {
    $post_thumbnail_id = get_post_thumbnail_id( $post );
    if ( ! $post_thumbnail_id ) {
        return false;
    }
    return wp_get_attachment_image_url( $post_thumbnail_id, $size );
}

the_post_thumbnail_url()

wp-includes/post-thumbnail-template.php:198 行目付近

/**
 * Display the post thumbnail URL.
 *
 * @since 4.4.0
 *
 * @param string|array $size Optional. Image size to use. Accepts any valid image size,
 *                           or an array of width and height values in pixels (in that order).
 *                           Default 'post-thumbnail'.
 */
function the_post_thumbnail_url( $size = 'post-thumbnail' ) {
    $url = get_the_post_thumbnail_url( null, $size );
    if ( $url ) {
        echo esc_url( $url );
    }
}

更新されたテンプレートタグ

wp_page_menu()

wp_page_menu() 関数の第一引数に指定できるパラメーターに、menu_idcontainerbeforeafterwalkerが追加された。

/**
 * Display or retrieve list of pages with optional home link.
 *
 * The arguments are listed below and part of the arguments are for {@link
 * wp_list_pages()} function. Check that function for more info on those
 * arguments.
 *
 * @since 2.7.0
 * @since 4.4.0 Added `menu_id`, `container`, `before`, `after`, and `walker` arguments.
 *
 * @param array|string $args {
 *     Optional. Arguments to generate a page menu. See wp_list_pages() for additional arguments.
 *
 *     @type string          $sort_column How to short the list of pages. Accepts post column names.
 *                                        Default 'menu_order, post_title'.
 *     @type string          $menu_id     ID for the div containing the page list. Default is empty string.
 *     @type string          $menu_class  Class to use for the element containing the page list. Default 'menu'.
 *     @type string          $container   Element to use for the element containing the page list. Default 'div'.
 *     @type bool            $echo        Whether to echo the list or return it. Accepts true (echo) or false (return).
 *                                        Default true.
 *     @type int|bool|string $show_home   Whether to display the link to the home page. Can just enter the text
 *                                        you'd like shown for the home link. 1|true defaults to 'Home'.
 *     @type string          $link_before The HTML or text to prepend to $show_home text. Default empty.
 *     @type string          $link_after  The HTML or text to append to $show_home text. Default empty.
 *     @type string          $before      The HTML or text to prepend to the menu. Default is '<ul>'.
 *     @type string          $after       The HTML or text to append to the menu. Default is '</ul>'.
 *     @type Walker          $walker      Walker instance to use for listing pages. Default empty (Walker_Page).
 * }
 * @return string|void HTML menu
 */

追加された条件分岐タグ

is_post_type_viewable()

そのポストタイプが閲覧可能かチェック。

wp-includes/post.php:1590 行目付近

/**
 * Determines whether a post type is considered "viewable".
 *
 * For built-in post types such as posts and pages, the 'public' value will be evaluated.
 * For all others, the 'publicly_queryable' value will be used.
 *
 * @since 4.4.0
 *
 * @param object $post_type_object Post type object.
 * @return bool Whether the post type should be considered viewable.
 */
function is_post_type_viewable( $post_type_object ) {
    return $post_type_object->publicly_queryable || ( $post_type_object->_builtin && $post_type_object->public );
}

is_embed()

wp-includes/query.php:721 行目付近

/**
 * Is the query for an embedded post?
 *
 * @since 4.4.0
 *
 * @global WP_Query $wp_query Global WP_Query instance.
 *
 * @return bool Whether we're in an embedded post or not.
 */
function is_embed() {
    global $wp_query;

    if ( ! isset( $wp_query ) ) {
        _doing_it_wrong( __FUNCTION__, __( 'Conditional query tags do not work before the query is run. Before then, they always return false.' ), '3.1' );
        return false;
    }

    return $wp_query->is_embed();
}

追加されたフィルター/アクションフック

register_post_type_args フィルター

register_post_type()関数に register_post_type_args フィルターが追加。

wp-includes/post.php:1004 行目付近

/**
 * Filter the arguments for registering a post type.
 *
 * @since 4.4.0
 *
 * @param array  $args      Array of arguments for registering a post type.
 * @param string $post_type Post type key.
 */
$args = apply_filters( 'register_post_type_args', $args, $post_type );

get_post_status フィルター

get_post_status()関数に get_post_status フィルターが追加。

wp-includes/post.php:575 行目付近

/**
 * Filter the post status.
 *
 * @since 4.4.0
 *
 * @param string  $post_status The post status.
 * @param WP_Post $post        The post object.
 */
return apply_filters( 'get_post_status', $post->post_status, $post );

pre_delete_post フィルター

wp_delete_post()関数に pre_delete_post フィルターが追加。

wp-includes/post.php:2371 行目付近

/**
 * Filter whether a post deletion should take place.
 *
 * @since 4.4.0
 *
 * @param bool    $delete       Whether to go forward with deletion.
 * @param WP_Post $post         Post object.
 * @param bool    $force_delete Whether to bypass the trash.
 */
$check = apply_filters( 'pre_delete_post', null, $post, $force_delete );

get_page_uri フィルター

get_page_uri()関数に get_page_uri フィルターが追加。

wp-includes/post.php:4298 行目付近

/**
 * Filter the URI for a page.
 *
 * @since 4.4.0
 *
 * @param string  $uri  Page URI.
 * @param WP_Post $page Page object.
 */
return apply_filters( 'get_page_uri', $uri, $page );

wp_post_revision_title_expanded フィルター

wp_post_revision_title_expanded()関数に wp_post_revision_title_expanded フィルターが追加。

wp-includes/post-template.php:1668 行目付近

/**
 * Filter the formatted author and date for a revision.
 *
 * @since 4.4.0
 *
 * @param string  $revision_date_author The formatted string.
 * @param WP_Post $revision             The revision object.
 * @param bool    $link                 Whether to link to the revisions page, as passed into
 *                                      wp_post_revision_title_expanded().
 */
return apply_filters( 'wp_post_revision_title_expanded', $revision_date_author, $revision, $link );

attachment_updated アクション

wp_insert_post()関数に attachment_updated アクションが追加。

wp-includes/post.php:3313 行目付近

/**
 * Fires once an existing attachment has been updated.
 *
 * @since 4.4.0
 *
 * @param int     $post_ID      Post ID.
 * @param WP_Post $post_after   Post object following the update.
 * @param WP_Post $post_before  Post object before the update.
 */
do_action( 'attachment_updated', $post_ID, $post_after, $post_before );

WP_Query

追加されたパラメーター

/**
 * Parse a query string and set query type booleans.
 *
 * @since 1.5.0
 * @since 4.2.0 Introduced the ability to order by specific clauses of a `$meta_query`, by passing the clause's
 *              array key to `$orderby`.
 * @since 4.4.0 Introduced `$post_name__in` and `$title` parameters. `$s` was updated to support excluded
 *              search terms, by prepending a hyphen.
 *
 * @param string|array $query {
 *     @type array        $post_name__in           An array of post slugs that results must match.
 *     @type string       $s                       Search keyword(s). Prepending a term with a hyphen will
 *                                                 exclude posts matching that term. Eg, 'pillow -sofa' will
 *                                                 return posts containing 'pillow' but not 'sofa'.
 *     @type string       $title                   Post title.
 * }
 */

追加されたメンバー変数

WP_Query::$is_embed
/**
 * Set if query is embed.
 *
 * @since 4.4.0
 * @access public
 * @var bool
 */
public $is_embed = false;
WP_Query::$updated_term_meta_cache
/**
 * Whether the term meta cache for matched posts has been primed.
 *
 * @since 4.4.0
 * @access protected
 * @var bool
 */
public $updated_term_meta_cache = false;
WP_Query::$updated_comment_meta_cache
/**
 * Whether the comment meta cache for matched posts has been primed.
 *
 * @since 4.4.0
 * @access protected
 * @var bool
 */
public $updated_comment_meta_cache = false;

追加されたメソッド

WP_Query::is_embed()

wp-includes/query.php:4708 行目付近

/**
 * Is the query for an embedded post?
 *
 * @since 4.4.0
 *
 * @return bool
 */
WP_Query::lazyload_term_meta()

wp-includes/query.php:4855 行目付近

/**
 * Lazy-loads termmeta for located posts.
 *
 * As a rule, term queries (`get_terms()` and `wp_get_object_terms()`) prime the metadata cache for matched
 * terms by default. However, this can cause a slight performance penalty, especially when that metadata is
 * not actually used. In the context of a `WP_Query` instance, we're able to avoid this potential penalty.
 * `update_object_term_cache()`, called from `update_post_caches()`, does not 'update_term_meta_cache'.
 * Instead, the first time `get_term_meta()` is called from within a `WP_Query` loop, the current method
 * detects the fact, and then primes the metadata cache for all terms attached to all posts in the loop,
 * with a single database query.
 *
 * This method is public so that it can be used as a filter callback. As a rule, there is no need to invoke it
 * directly, from either inside or outside the `WP_Query` object.
 *
 * @since 4.4.0
 * @access public
 *
 * @param mixed $check  The `$check` param passed from the 'get_term_metadata' hook.
 * @param int  $term_id ID of the term whose metadata is being cached.
 * @return mixed In order not to short-circuit `get_metadata()`. Generally, this is `null`, but it could be
 *               another value if filtered by a plugin.
 */
WP_Query::lazyload_comment_meta()

wp-includes/query.php:4931 行目付近

/**
 * Lazy-load comment meta when inside of a `WP_Query` loop.
 *
 * This method is public so that it can be used as a filter callback. As a rule, there is no need to invoke it
 * directly, from either inside or outside the `WP_Query` object.
 *
 * @since 4.4.0
 *
 * @param mixed $check     The `$check` param passed from the 'get_comment_metadata' hook.
 * @param int  $comment_id ID of the comment whose metadata is being cached.
 * @return mixed The original value of `$check`, to not affect 'get_comment_metadata'.
 */

追加されたフィルター/アクションフック

content_pagination フィルター

WP_Query::setup_postdata() メソッド内

wp-includes/query.php:721 行目付近

/**
 * Filter the "pages" derived from splitting the post content.
 *
 * "Pages" are determined by splitting the post content based on the presence
 * of `<!-- nextpage -->` tags.
 *
 * @since 4.4.0
 *
 * @param array   $pages Array of "pages" derived from the post content.
 *                       of `<!-- nextpage -->` tags..
 * @param WP_Post $post  Current post object.
 */
$pages = apply_filters( 'content_pagination', $pages, $post );

タクソノミー

タクソノミー関連の変更点。

追加されたフィルター/アクションフック

register_taxonomy_args フィルター

register_taxonomy()関数に register_taxonomy_args フィルターが追加

wp-includes/taxonomy.php:350 行目付近

/**
 * Filter the arguments for registering a taxonomy.
 *
 * @since 4.4.0
 *
 * @param array  $args        Array of arguments for registering a taxonomy.
 * @param array  $object_type Array of names of object types for the taxonomy.
 * @param string $taxonomy    Taxonomy key.
 */
$args = apply_filters( 'register_taxonomy_args', $args, $taxonomy, (array) $object_type );

taxonomy_labels_{$taxonomy} フィルター

get_taxonomy_labels()関数に taxonomy_labels_{$taxonomy} フィルターが追加。taxonomy_labels_{$taxonomy}フィルターを使用すると、カテゴリーやタグといった管理画面上のメニューや設定画面の表記を変更できる。

wp-includes/taxonomy.php:560 行目付近

/**
 * Filter the labels of a specific taxonomy.
 *
 * The dynamic portion of the hook name, `$taxonomy`, refers to the taxonomy slug.
 *
 * @since 4.4.0
 *
 * @see get_taxonomy_labels() for the full list of taxonomy labels.
 *
 * @param object $labels Object with labels for the taxonomy as member variables.
 */
$labels = apply_filters( "taxonomy_labels_{$taxonomy}", $labels );

以下に、カテゴリー管理画面上の表記をジャンルという表記に変更する例を示します。

/**
 * Change category labels.
 *
 * @param  $labels object
 * @return         object
 */
function kuck1u_change_category_labels( $labels ) {
    $name       = "ジャンル";
    $new_labels = array(
        'name'                  => sprintf( '%s', $name ),
        'singular_name'         => sprintf( '%s', $name ),
        'search_items'          => sprintf( '%sを検索', $name ),
        'all_items'             => sprintf( '%s一覧', $name ),
        'parent_item'           => sprintf( '親%s', $name ),
        'parent_item_colon'     => sprintf( '親%s', $name ),
        'edit_item'             => sprintf( '%sの編集', $name ),
        'view_item'             => sprintf( '%sを表示', $name ),
        'update_item'           => sprintf( '%sを更新', $name ),
        'add_new_item'          => sprintf( '新規%sを追加', $name ),
        'new_item_name'         => sprintf( '新規%s名', $name ),
        'not_found'             => sprintf( '%sが見つかりませんでした。', $name ),
        'no_terms'              => sprintf( '%sなし', $name ),
        'items_list_navigation' => sprintf( '%sリストナビゲーション', $name ),
        'items_list'            => sprintf( '%sリスト', $name ),
        'menu_name'             => sprintf( '%s', $name )
    );
    $new_labels = array_merge( (array)$labels, (array)$new_labels );

    return (object)$new_labels;
}
add_filter( 'taxonomy_labels_category', 'kuck1u_change_category_labels' );

get_terms_defaults フィルター

get_terms()関数に get_terms_defaults フィルターが追加。get_terms_defaults フィルターを使用すると、get_terms()関数の第二引数のデフォルトパラメーターを変更できる。

wp-includes/taxonomy.php:1108 行目付近

/**
 * Filter the terms query default arguments.
 *
 * Use 'get_terms_args' to filter the passed arguments.
 *
 * @since 4.4.0
 *
 * @param array $defaults   An array of default get_terms() arguments.
 * @param array $taxonomies An array of taxonomies.
 */
$args = wp_parse_args( $args, apply_filters( 'get_terms_defaults', $defaults, $taxonomies ) );

デフォルトの値は以下です。WordPress 4.4 から meta_query をサポートしています。

$defaults = array(
    'orderby'                => 'name',
    'order'                  => 'ASC',
    'hide_empty'             => true,
    'include'                => array(),
    'exclude'                => array(),
    'exclude_tree'           => array(),
    'number'                 => '',
    'offset'                 => '',
    'fields'                 => 'all',
    'name'                   => '',
    'slug'                   => '',
    'hierarchical'           => true,
    'search'                 => '',
    'name__like'             => '',
    'description__like'      => '',
    'pad_counts'             => false,
    'get'                    => '',
    'child_of'               => 0,
    'parent'                 => '',
    'childless'              => false,
    'cache_domain'           => 'core',
    'update_term_meta_cache' => true,
    'meta_query'             => ''
);

タームメタ (Term metadata)

WordPress 4.4 で追加されたタームメタ。タームメタはポストメタのターム版です。カテゴリー(ターム)1 つ 1 つにメタ情報を比較的簡単に追加できるようになりました。

タームメタもポストメタ同様、CRUD の API はしっかりと用意されています。

CRUD 関数名
C add_term_meta( $term_id, $meta_key, $meta_value, $unique )
R get_term_meta( $term_id, $key, $single )
U update_term_meta( $term_id, $meta_key, $meta_value, $prev_value )
D delete_term_meta( $term_id, $meta_key, $meta_value )

追加されたその他の API

update_termmeta_cache()

wp-includes/taxonomy.php:1673 行目付近

/**
 * Updates metadata cache for list of term IDs.
 *
 * Performs SQL query to retrieve all metadata for the terms matching `$term_ids` and stores them in the cache.
 * Subsequent calls to `get_term_meta()` will not need to query the database.
 *
 * @since 4.4.0
 *
 * @param array $term_ids List of term IDs.
 * @return array|false Returns false if there is nothing to update. Returns an array of metadata on success.
 */
update_termmeta_cache( $term_ids );

wp_term_is_shared()

wp-includes/taxonomy.php:4273 行目付近

/**
 * Determine whether a term is shared between multiple taxonomies.
 *
 * Shared taxonomy terms began to be split in 4.3, but failed cron tasks or other delays in upgrade routines may cause
 * shared terms to remain.
 *
 * @since 4.4.0
 *
 * @param int $term_id
 * @return bool
 */
wp_term_is_shared( $term_id );

メディア

WordPress 4.4 で追加された目玉機能 レンスポンシブイメージ。それ関連の API が数点追加されています。

追加されたフィルター/アクションフック

image_get_intermediate_size フィルター

image_get_intermediate_size() 関数に image_get_intermediate_size フィルターが追加。

wp-includes/media.php:675 & 691 行目付近

/**
 * Filter the output of image_get_intermediate_size()
 *
 * @since 4.4.0
 *
 * @see image_get_intermediate_size()
 *
 * @param array        $data    Array of file relative path, width, and height on success. May also include
 *                              file absolute path and URL.
 * @param int          $post_id The post_id of the image attachment
 * @param string|array $size    Registered image size or flat array of initially-requested height and width
 *                              dimensions (in that order).
 */
return apply_filters( 'image_get_intermediate_size', $data, $post_id, $size );

追加された API

wp_get_attachment_image_url()

wp-includes/media.php:864 行目付近

/**
 * Get the URL of an image attachment.
 *
 * @since 4.4.0
 *
 * @param int          $attachment_id Image attachment ID.
 * @param string|array $size          Optional. Image size to retrieve. Accepts any valid image size, or an array
 *                                    of width and height values in pixels (in that order). Default 'thumbnail'.
 * @param bool         $icon          Optional. Whether the image should be treated as an icon. Default false.
 * @return string|false Attachment URL or false if no image is available.
 */
wp_get_attachment_image_url( $attachment_id, $size = 'thumbnail', $icon = false );

wp_get_attachment_image_srcset()

wp-includes/media.php:930 行目付近

/**
 * Retrieves the value for an image attachment's 'srcset' attribute.
 *
 * @since 4.4.0
 *
 * @see wp_calculate_image_srcset()
 *
 * @param int          $attachment_id Image attachment ID.
 * @param array|string $size          Optional. Image size. Accepts any valid image size, or an array of
 *                                    width and height values in pixels (in that order). Default 'medium'.
 * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
 *                                    Default null.
 * @return string|bool A 'srcset' value string or false.
 */
wp_get_attachment_image_srcset( $attachment_id, $size = 'medium', $image_meta = null );

wp_calculate_image_srcset()

wp-includes/media.php:962 行目付近

/**
 * A helper function to calculate the image sources to include in a 'srcset' attribute.
 *
 * @since 4.4.0
 *
 * @param array  $size_array    Array of width and height values in pixels (in that order).
 * @param string $image_src     The 'src' of the image.
 * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
 * @param int    $attachment_id Optional. The image attachment ID to pass to the filter. Default 0.
 * @return string|bool          The 'srcset' attribute value. False on error or when only one source exists.
 */
wp_calculate_image_srcset( $size_array, $image_src, $image_meta, $attachment_id = 0 );

wp_get_attachment_image_sizes()

wp-includes/media.php:1112 行目付近

/**
 * Retrieves the value for an image attachment's 'sizes' attribute.
 *
 * @since 4.4.0
 *
 * @see wp_calculate_image_sizes()
 *
 * @param int          $attachment_id Image attachment ID.
 * @param array|string $size          Optional. Image size. Accepts any valid image size, or an array of width
 *                                    and height values in pixels (in that order). Default 'medium'.
 * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
 *                                    Default null.
 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
 */
wp_get_attachment_image_sizes( $attachment_id, $size = 'medium', $image_meta = null );

wp_calculate_image_sizes

wp-includes/media.php:1144 行目付近

/**
 * Creates a 'sizes' attribute value for an image.
 *
 * @since 4.4.0
 *
 * @param array|string $size          Image size to retrieve. Accepts any valid image size, or an array
 *                                    of width and height values in pixels (in that order). Default 'medium'.
 * @param string       $image_src     Optional. The URL to the image file. Default null.
 * @param array        $image_meta    Optional. The image meta data as returned by 'wp_get_attachment_metadata()'.
 *                                    Default null.
 * @param int          $attachment_id Optional. Image attachment ID. Either `$image_meta` or `$attachment_id`
 *                                    is needed when using the image size name as argument for `$size`. Default 0.
 * @return string|bool A valid source size value for use in a 'sizes' attribute or false.
 */
wp_calculate_image_sizes( $size, $image_src = null, $image_meta = null, $attachment_id = 0 );

wp_make_content_images_responsive()

wp-includes/media.php:1208 行目付近

/**
 * Filters 'img' elements in post content to add 'srcset' and 'sizes' attributes.
 *
 * @since 4.4.0
 *
 * @see wp_image_add_srcset_and_sizes()
 *
 * @param string $content The raw post content to be filtered.
 * @return string Converted content with 'srcset' and 'sizes' attributes added to images.
 */
wp_make_content_images_responsive( $content );

wp_image_add_srcset_and_sizes()

wp-includes/media.php:1245 行目付近

/**
 * Adds 'srcset' and 'sizes' attributes to an existing 'img' element.
 *
 * @since 4.4.0
 *
 * @see wp_calculate_image_srcset()
 * @see wp_calculate_image_sizes()
 *
 * @param string $image         An HTML 'img' element to be filtered.
 * @param array  $image_meta    The image meta data as returned by 'wp_get_attachment_metadata()'.
 * @param int    $attachment_id Image attachment ID.
 * @return string Converted 'img' element with 'srcset' and 'sizes' attributes added.
 */
wp_image_add_srcset_and_sizes( $image, $image_meta, $attachment_id );

_wp_upload_dir_baseurl()

wp-includes/media.php:880 行目付近

/**
 * Caches and returns the base URL of the uploads directory.
 *
 * @since 4.4.0
 * @access private
 *
 * @return string The base URL, cached.
 */
_wp_upload_dir_baseurl();

_wp_get_image_size_from_meta()

wp-includes/media.php:901 行目付近

/**
 * Get the image size as array from its meta data.
 *
 * Used for responsive images.
 *
 * @since 4.4.0
 * @access private
 *
 * @param string $size_name  Image size. Accepts any valid image size name ('thumbnail', 'medium', etc.).
 * @param array  $image_meta The image meta data.
 * @return array|bool Array of width and height values in pixels (in that order)
 *                    or false if the size doesn't exist.
 */
_wp_get_image_size_from_meta( $size_name, $image_meta );

非推奨になった関数

WordPress 4.4 では、以下の 3 つの関数が非推奨となりました。その他の非推奨関数一覧は、wp-includes/deprecated.php をご覧ください。

wp_title()関数も一旦は非推奨になったようですが、WordPress 4.4 では見送りになったようです。ただ、今後のことを考えると、add_theme_support( 'title-tag' );を使用するようにした方がよいかもしれません。

  • post_permalink()
  • wp_get_http()
  • force_ssl_login()

なうい wp_title

非推奨になった関数でも少し触れたましたが、wp_title()関数が一旦は非推奨関数になりました。今後もしかしたら完全に非推奨になるかもしれません。そうなった時に慌てないよう、なうい wp_title の使用方法に変更しましょう !

いままではテーマファイルの header.php で以下のようにしていたと思います。

<title><?php wp_title( '|', true, 'right' ); ?></title>

なうい wp_title では、header.php に HTML の title タグや wp_title()関数は書かず、functions.php にadd_theme_support( 'title-tag' )と書きます。以下にadd_theme_support( 'title-tag' )の使用例を示します。

function mytheme_setup() {
    add_theme_support( 'title-tag' );
}
add_action( 'after_setup_theme', 'mytheme_setup' );

このようにすることで、WordPress が自動的に title タグを出力してくれます。title タグは wp_head アクションが実行された時に出力されます。WordPress デフォルトのアクションとして wp_head アクションに登録されている_wp_render_title_tag()が title タグを出力している本体です。

/**
 * Displays title tag with content.
 *
 * @ignore
 * @since 4.1.0
 * @since 4.4.0 Improved title output replaced `wp_title()`.
 * @access private
 */
function _wp_render_title_tag() {
    if ( ! current_theme_supports( 'title-tag' ) ) {
        return;
    }

    echo '<title>' . wp_get_document_title() . '</title>' . "\n";
}

_wp_render_title_tag()関数は、現在設定されているテーマが title-tag をサポートしていたら HTML の title タグを出力するというだけの極めてシンプルな内容です。

各ページで出力されるページタイトルをカスタマイズしたい場合は、_wp_render_title_tag()関数内で使用されているwp_get_document_title()関数内にあるフィルターフックを使用してカスタマイズします。使用できるフィルターフックは以下の通りです。

wp_get_document_title() 関数のフィルターフック

pre_get_document_title

title タグのタイトル全部を変更したい場合は、このフィルターを使用します。

pre_get_document_title フィルターは、wp_get_document_title()関数の先頭で宣言されていています。このフィルターを使用して、空以外の文字列をセットすると、wp_get_document_title()関数はその値を即座に返します。

function my_pre_get_document_title( $title ) {
    if ( is_page( 'gochiwp' ) ) {
        $title = "ご注文は WordPress ですか????";
    }

    return $title;
}
add_filter( 'pre_get_document_title', 'my_pre_get_document_title' );

document_title_separator

サイト名とページタイトルの区切りに使用されている記号を変更したい場合は、このフィルターを使用します。

function my_document_title_separator( $sec ) {
    $sec = "|";

    return $sec;
}
add_filter( 'document_title_separator', 'my_document_title_separator' );

document_title_parts

サイト名とページタイトルを逆にしたい/ページタイトルだけ変更したい場合は、このフィルターを使用します。

このフィルターの値は、連想配列になっている点に注意が必要です。

並び順 キー バリュー
0 $title['title'] 現在閲覧しているページのページタイトル
1 $title['page'] 現在閲覧しているページのページ数(ページ分割やアーカイブページのページネーション)
2 $title['tagline'] サイトのディスクリプション(ホームページまたはフロントページの時のみセットされる)
3 $title['site'] サイト名

各キーは必ず存在しているわけではありません。ページに応じたキーとバリューがセットされます。この配列を PHP のimplode()関数で連結し title タグの文言を生成しています。

以下に、サイトタイトルを必ず先頭に表示するようにする例を示します。

function my_document_title_parts( $title ) {
    $parts = $title;

    if ( !is_home() && !is_front_page() ) {
        $site = array( 'site' => $parts['site'] );
        unset( $parts['site'] );

        $parts = array_merge( $site, $parts );
    }

    return $parts;
}
add_filter( 'document_title_parts', 'my_document_title_parts' );

参考記事

こちらも合わせてどうぞ !

WordPress でビジネスサイトを作る時にオススメなテーマ 2015 冬

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
38