wordpressについて質問させて頂きます。
カテゴリーid65の親カテゴリー、子カテゴリー、孫カテゴリーとありまして、カテゴリー一覧を下記のように作ったのですが、孫カテゴリーのためのページは作っていないので、孫カテゴリーのリンク先は子カテゴリのページの孫カテゴリのid(h2のid)に設定したいのですが、どなたかやり方をご教授頂けないでしょうか。
よろしくお願い申し上げます。
気になる質問をクリップする
クリップした質問は、後からいつでもMYページで確認できます。
またクリップした質問に回答があった際、通知やメールを受け取ることができます。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
回答2件
0
ベストアンサー
コードはテストできていませんので、なにかあったら適当に修正してください。
functions.php に関数を準備。
PHP
1function my_list_categories( $args = '' ) { 2 $defaults = array( 3 'orderby' => 'name' 4 , 'order' => 'DESC' 5 , 'hide_empty' => false 6 , 'exclude' => array() 7 , 'parent' => '' 8 , 'echo' => true 9 , 'target_depth' => 1 10 , 'now_depth' => 1 11 , 'url' => '' 12 ); 13 $r = wp_parse_args( $args, $defaults ); 14 $r[ 'hierarchical' ] = false; 15 $output = ''; 16 $now_depth = $r[ 'now_depth' ]; 17 $next_depth = $now_depth + 1; 18 $target_depth = $r[ 'target_depth' ]; 19 20 // 同じ親を持つカテゴリーを呼び出す 21 $categories = get_categories( $r ); 22 foreach( $categories as $category ) { 23 $child = ''; 24 // $target_depth 以下の階層では $target_depth の親のURLを引き継ぐ 25 $url = ( $target_depth <= $now_depth ) ? $r[ 'url' ] : get_category_link( $category->term_id ); 26 27 // 下層を呼び出す 28 if ( $target_depth > $now_depth ) { // $target_depth まで表示して、それ以降の階層を表示しない 29 $child = my_list_categories( wp_parse_args( array( 30 'parent' => $category->term_id 31 , 'echo' => false 32 , 'now_depth' => $next_depth 33 , 'url' => $url 34 ), $r ) ); 35 } 36 // liのHTMLを組む 37 $output .= sprintf( '%7$s%6$s<li class="%3$s"><a href="%2$s" title="%1$s">%1$s</a>%4$s%7$s%6$s</li>' 38 , /* %1$s */ esc_html( $category->name ) 39 , /* %2$s */ esc_url( $url ) 40 , /* %3$s */ esc_attr( $category->slug ) 41 , /* %4$s */ esc_attr( $category->name ) 42 , /* %5$s */ $child 43 , /* %6$s */ ( $next_depth > 0 ) ? str_repeat( "\t", $next_depth ) : '' 44 , /* %7$s */ "\n" 45 ); 46 } 47 // ulのHTMLを組む 48 $html .= sprintf( '%3$s%2$s<ul class="catList">%1$s%3$s%2$s</ul>' 49 , /* %1$s */ $output 50 , /* %2$s */ ( $now_depth > 0 ) ? str_repeat( "\t", $now_depth ) : '' 51 , /* %3$s */ "\n" 52 ); 53 54 // 出力する 55 if ( $r['echo'] ) { 56 echo $html; 57 } else { 58 return $html; 59 } 60} // my_list_categories()
テンプレートのタグクラウドが必要な箇所に下記を記述。
PHP
1// 使うとき 2$categories = my_list_categories( array( 3 'orderby' => 'term_group' 4 , 'child_of' => get_category_by_slug( 'ABC' )->term_id // 子カテゴリー(親カテゴリーから始めるときは省略) 5 , 'hide_empty' => '0' 6 , 'echo' => true 7 , 'target_depth' => 2 // 孫カテゴリー(親カテゴリーから始めるときは「3」) 8) );
投稿2016/04/08 17:37
総合スコア69446
0
categoryは追加で増えますか?
category.phpの中で現在のカテゴリーidなどを取得して表示を切り替えたほうがリンク先を弄るよりも楽だと思います
参考ソース
http://kawatama.net/web/1068
投稿2016/03/20 16:14
総合スコア59
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/03/20 17:33
あなたの回答
tips
太字
斜体
打ち消し線
見出し
引用テキストの挿入
コードの挿入
リンクの挿入
リストの挿入
番号リストの挿入
表の挿入
水平線の挿入
プレビュー
質問の解決につながる回答をしましょう。 サンプルコードなど、より具体的な説明があると質問者の理解の助けになります。 また、読む側のことを考えた、分かりやすい文章を心がけましょう。
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2016/06/12 08:26