pre_get_posts

Sponsored Link

このフックはクエリ変数オブジェクトが実行される後に呼び出されますが、実際は実行される前に走ります。

pre_get_postsアクションは、開発者が参照することによって、$queryオブジェクトへのアクセスを提供します(あなたが$queryで行った任意の変更は、元のオブジェクトに直接作られていますー戻り値は必要ありません)。

Sponsored Link

This hook is called after the query variable object is created, but before the actual query is run.

The pre_get_posts action gives developers access to the $query object by reference (any changes you make to $query are made directly to the original object – no return value is necessary).

pre_get_postsのファンクションタグ使用方法

<?php add_action( 'pre_get_posts', 'your_function_name' ); ?>

注意

引数は参照によって引き渡されます

$queryオブジェクトは参照によって関数に引き渡されます。あなたはグローバル変数を宣言したり、値を返す必要はありません。あなたが関数内からオブジェクトに加えた任意の変更は、元の即時に行われます。

The $query object is passed to your function by reference. You do not need to declare globals or return a value. Any changes you make to the object from inside your function are made to the original immediately.

ターゲットクエリを識別する

pre_get_postsを使用するときは、変更しようとしているクエリーに注意してください。便利なツールの1つは is_main_query()です、あなたがメインのクエリーのみ修正しているクエリーである確認するのに役立ちます。

When using pre_get_posts, be aware of the query you are changing. One useful tool is is_main_query(), which can help you ensure that the query you are modifying is only the main query.

管理使用者に対して警告する

このフィルターは管理画面のクエリーに影響を及ぼすために使用することも出来ます。あなたの変更が投稿編集画面に影響を及ぼしているかどうかを確認してください。例えば、!is_admin()である場合も除いて、is_main_query()とis_post_type_archive(‘custom’)がedit.php?post_type=custom画面でクエリーが変更をしているか確認してください。

This filter can also be used to affect admin screen queries. Be sure to check if your modification is affecting your post edit screens. For example, just checking is_main_query() and is_post_type_archive(‘custom’) will change your query for the edit.php?post_type=custom screen, unless you also check for !is_admin()

条件関数について警告

pre_get_postsはWP_Queryがセットアップされる前に実行されます。いくつかのテンプレートタグや条件関数はWP_Query上で頼らないので動作しません。例えば、is_front_page()は動作しませんが、is_home()では動作します。そのようなケースでは、引数としてpre_get_postsフックに渡されるクエリー変数で直接動作させる必要があります(このページ上での例に$query)。

pre_get_posts runs before WP_Query has been setup. Some template tags and conditional functions that rely on WP_Query will not work. For example, is_front_page() will not work, although is_home()will work. In such cases, you will need to work directly with the query vars, which are passed to the pre_get_posts hook as an argument ($query in examples on this page).

オフセットとページネーション

任意のWordPressのクエリーでオフセット引数を使用することは、ページネーションを解除することができます。あなたがオフセットを使用してページネーションを保存する必要がある場合、手動でページネーションを処理する必用があることに留意してください。「オフセットとページネーションを使用するためにカスタムクエリーを作成する」の詳細をCODEXの記事でお読みください。

Using the offset argument in any WordPress query can break pagination. If you need to use offset and preserve pagination, please keep in mind that you will need to handle pagination manually. Read the codex article Making Custom Queries using Offset and Pagination for more information.

メインページでカテゴリーを除外する方法

これはあなたのブログに表示から記事のカテゴリーを除外することができる方法です。例えば、あなたの’home’ブログ上に表示したくない記事に2つのカテゴリーが存在している場合(未分類’1 ‘と別の’1347’)、これらのカテゴリーを省略するためにプラグイン内に次のように使用することが出来ます:

This is how you can exclude categories of posts from displaying in your blog. For example, if you have 2 categories of posts (uncategorized ‘1’ and another ‘1347’) that you don’t want to display on your ‘home’ blog page, you can use the following in your plugin to omit these categories:

function exclude_category( $query ) {
    if ( $query->is_home() &amp;&amp; $query->is_main_query() ) {
        $query->set( 'cat', '-1,-1347' );
    }
}
add_action( 'pre_get_posts', 'exclude_category' );

投稿タイプによって、posts per pageの数を変更する方法

WordPressは、1ループのページ上に表示される投稿数を制御するためのシングルグローバル設定が含まれています(”管理画面内に表示する最大数ブログページ”の下)。
これはケースバイケースの原則上、posts_per_pageの設定を変更/オーバーライドするというアクションフックを作成することが可能です。何と言っても、これはクエリーが実行済である前に実行されます(なのでパフォーマンスコストがありません)。

次の例では、特定の投稿タイプのアーカイブを(‘posts_per_page’)でページサイズをオーバーライドする方法を表示します。

WordPress includes a single global setting for controlling the number of posts that appear on one loop page (under “Blog pages show at most” in the admin”). It is possible to create an action hook that changes / overrides the posts_per_page setting on a case-by-case basis. Best of all, this is done before the query is even executed (so there is no performance cost)!

The following example demonstrates how to override the page size (‘posts_per_page’) for archives of specific post types:

function hwl_home_pagesize( $query ) {
    if ( is_admin() || ! $query->is_main_query() )
        return;

    if ( is_home() ) {
        // Display only 1 post for the original blog archive
        // オリジナルのブログアーカイブに1つの記事だけ表示します。
        $query->set( 'posts_per_page', 1 );
        return;
    }

    if ( is_post_type_archive( 'movie' ) ) {
        // Display 50 posts for a custom post type called 'movie'
        // 'movie'というカスタム投稿タイプの50記事を表示します。
        $query->set( 'posts_per_page', 50 );
        return;
    }
}
add_action( 'pre_get_posts', 'hwl_home_pagesize', 1 );

WP_Queryオブジェクトのサンプル

参考までに、これはこのフックにより表示されたWP_Queryオブジェクト($query)の一例です。詳細につきましては、あなたもWP_QueryのCODEXページで確認することができます。

For reference, this is one possible example of the WP_Query object ($query) exposed by this hook. For more detail, you can also review the WP_Query codex page.

WP_Query Object
(
    [query_vars] => Array
        (
            [page] => 
            [pagename] => blog
            [error] => 
            [m] => 0
            [p] => 0
            [post_parent] => 
            [post_type] =>
            [subpost] => 
            [subpost_id] => 
            [attachment] => 
            [attachment_id] => 0
            [name] => 
            [static] => 
            [page_id] => 0
            [second] => 
            [minute] => 
            [hour] => 
            [day] => 0
            [monthnum] => 0
            [year] => 0
            [w] => 0
            [category_name] => 
            [tag] => 
            [cat] => 
            [tag_id] => 
            [author_name] => 
            [feed] => 
            [tb] => 
            [paged] => 0
            [comments_popup] => 
            [meta_key] => 
            [meta_value] => 
            [preview] => 
            [s] => 
            [sentence] => 
            [fields] => 
            [category__in] => Array
                (
                )

            [category__not_in] => Array
                (
                )

            [category__and] => Array
                (
                )

            [post__in] => Array
                (
                )

            [post__not_in] => Array
                (
                )

            [tag__in] => Array
                (
                )

            [tag__not_in] => Array
                (
                )

            [tag__and] => Array
                (
                )

            [tag_slug__in] => Array
                (
                )

            [tag_slug__and] => Array
                (
                )

        )

    [tax_query] => 
    [meta_query] => 
    [post_count] => 0
    [current_post] => -1
    [in_the_loop] => 
    [comment_count] => 0
    [current_comment] => -1
    [found_posts] => 0
    [max_num_pages] => 0
    [max_num_comment_pages] => 0
    [is_single] => 
    [is_preview] => 
    [is_page] => 
    [is_archive] => 
    [is_date] => 
    [is_year] => 
    [is_month] => 
    [is_day] => 
    [is_time] => 
    [is_author] => 
    [is_category] => 
    [is_tag] => 
    [is_tax] => 
    [is_search] => 
    [is_feed] => 
    [is_comment_feed] => 
    [is_trackback] => 
    [is_home] => 1
    [is_404] => 
    [is_comments_popup] => 
    [is_paged] => 
    [is_admin] => 
    [is_attachment] => 
    [is_singular] => 
    [is_robots] => 
    [is_posts_page] => 1
    [is_post_type_archive] => 
    [query_vars_hash] => 41032f87127fba65fb6743b1e97d8662
    [query_vars_changed] => 
    [thumbnails_cached] => 
    [query] => Array
        (
            [page] => 
            [pagename] => blog
        )

    [queried_object] => stdClass Object
        (
            [ID] => 16
            [post_author] => 1
            [post_date] => 2012-01-31 17:23:57
            [post_date_gmt] => 2012-01-31 17:23:57
            [post_content] => 
            [post_title] => Blog
            [post_excerpt] => 
            [post_status] => publish
            [comment_status] => open
            [ping_status] => open
            [post_password] => 
            [post_name] => blog
            [to_ping] => 
            [pinged] => 
            [post_modified] => 2012-01-31 17:23:57
            [post_modified_gmt] => 2012-01-31 17:23:57
            [post_content_filtered] => 
            [post_parent] => 0
            [guid] => 

関連ファンクションタグ

  • Class: WP_Query – Detailed overview of the WP_Query class
  • Class: $wpdb – Overview of using the $wpdb object
  • Function: get_query_var()
  • Function: query_posts() – Make additional custom queries
  • Function: get_posts() – A specialized function that returns an array of posts
  • Function: get_pages() – A specialized function that returns an array of pages
  • Function: have posts() – A conditional that determines if the query returned any posts
  • Function: the_post() – Used to automatically set up the loop after a query
  • Function: rewind_posts() – Resets the current loop
  • Function: setup_postdata() – Setup query data for individual results within a loop
  • Function: wp_reset_postdata() – Restores the previous query (usually after a loop-within-a-loop)
  • Function: wp_reset_query()
  • Function: is_main_query() – Ensures the query being changed is only the main query
  • Action Hook: pre_get_posts – Modify WordPress queries before they are executed
  • Filter Hook: found_posts – Modify the WP_Query object’s found_posts value
  • Tutorial: Displaying Posts Using a Custom Select Query
  • Tutorial: Making Advanced Taxonomy Queries
  • Tutorial: Making Custom Queries using Offset and Pagination
Sponsored Link