2016-08-13 7 views
0

カテゴリのカスタムページと、その子で指定されたカテゴリの単一ページを作成したいと思います。まずカテゴリと単一ページのためのカスタムページをワードプレスでその子と一緒に指定する方法

は、私が使用してきました。このコード

if (in_category('blog')){ 
include (TEMPLATEPATH . '/single-blog.php'); 
}elseif(in_category('projects')){ 
    include (TEMPLATEPATH . '/single-projects.php'); 
} 
else{ 
    include (TEMPLATEPATH . '/single-default.php'); 
} 

をカスタム単一のページを作成し、それがコードにちょうどspecifed ctegoryのために正常に動作し、カテゴリの子どもたちをサポートしていません。

例:blogまたはchildren of blogという投稿の1ページにはsingle-blog.phpを使用したいと思います。

第2のカテゴリページについては、カテゴリの投稿のリストについて上記で説明したのと同じことをしたいと思います。

例:ブログカテゴリまたはその子に関連する投稿のリストをcategory-blog.phpに表示したいと思います。

どうすればいいですか?あなたの質問の最初の部分については

答えて

1

、あなたはおそらくcat_is_ancestor_ofを探しているので、あなたはこのような何か書きたい:の部分については

function is_ancestor_of($ancestor_category) { 
    $categories = get_the_category(); // array of current post categories 
    foreach ($categories as $category) { 
     if (cat_is_ancestor_of($ancestor_category, $category)) return true; 
    } 
    return false; 
} 

$ancestor_category = get_category_by_slug('blog'); 
if (in_category('blog') || is_ancestor_of($ancestor_category)) { 
    // include 
} 

を、私はあなたがしたいことを理解し同じことをするが、アーカイブページにする。あなたがカテゴリの配列を持っていないので、その場合には、それは少し簡単です:

$archive_category = get_category(get_query_var('cat')); // current archive category 
$ancestor_category = get_category_by_slug('blog'); 
if (is_category('blog') || cat_is_ancestor_of($ancestor_category, $archive_category) { 
    // include 
} 

EDIT、これはあなたのために働くなら、私に教えてください - ここでは、代替オプションがあります(テストしていません)は、少なくとも直接的には - foreachループを使用しません。それがより高い性能であるかどうかわからない。

$ancestor_category = get_category_by_slug('blog'); 
$children_categories = get_categories(array ('parent' => $ancestor_category->cat_ID)); // use 'child_of' instead of 'parent' to get all descendants, not only children 

$categories = get_the_category(); // array of current post categories 

if (in_category('blog') || ! empty(array_intersect($categories, $children_categories)) { 
    // include 
} 
+0

ありがとうございます。それは魅力のように機能しますが、少しパフォーマンスが低いのでforeachを使用しない別の方法があることを願っています – Ali

+0

@Hamedあなたが私の編集をテストして、それがうまくいくかどうかを確認したいかもしれません –

+0

私は、テストしましたが、うまくいきません。 – Ali

関連する問題