WordPressの検索にカスタム投稿も含めるのでR ver.2

以前のここの記事で、function.phpに直接追加するカスタム投稿の方法を示したのでR。

しかし、

カスタム投稿の場合は、検索で引っかからないこともあるのでR。

そこで、ここや、ここを参考に

'exclude_from_search' => false,

をカスタム投稿に追加して、

add_action( 'init', 'custom_post_type' );
function custom_post_type() {
    register_post_type( 'custompost',
        array('labels' =>
                array(
                'name' => __( 'カスタム投稿' ),
                'singular_name' => __( 'カスタム投稿' )
                ),
            'public' => true,
            'menu_position' => 5,
            'hierarchicla' => false,
            'has_archive' => true,
'exclude_from_search' => false,
            'supports' => array('title','editor','thumbnail', 
            'custom-fields','excerpt','author','trackbacks',
            'comments','revisions','page-attributes')          
        )
    );
}

としたのでR。

しかし、

検索でカスタム投稿が引っかからないのでR。

そこで、ここを参考に、function.phpに

function filter_search($query) {
if ($query->is_search) {
$query->set('post_type', array('post', 'custompost'));
};
return $query;
};
add_filter('pre_get_posts', 'filter_search');

を追加すると、できたのでR。

上の追加は、

'exclude_from_search' => false,

がなくても問題なかったのでR。

実は、プラグインで実現したカスタム投稿はここで記事にしていたのでRが、このプラグインに対する検索の解決もここで記事にしていたのでR。

うっかりしていたが、実は、ソースをいじるカスタム投稿でもこの方法は有効だったのでR。そのため、ここでは、ver.2として、記事にしたのでR。





(広告)月額900円(税抜)から、高速・多機能・高安定レンタルサーバー『エックスサーバー』
(広告)WordPressの運用に特化したレンタルサーバー『wpXレンタルサーバー』
(広告)年間920円(税抜)からの格安ドメイン取得サービス─ムームードメイン─




この記事をシェアできます。