WordPressとPHPを最近始めたばかりですが、質問させてください。
ショートコードの第1引数にカテゴリー名を、第2引数にタグ名を指定し
さらに'post_type'カラムが'post'であるレコードリストを取得したいのですが
PHP
1function shortcode_list( $atts ) { 2 $atts = shortcode_atts( array( 3 'cat_name' => null, 4 'tag' => null, 5 ), $atts, 'list' ); 6 $args = array( 7 'post_type' => 'post', 8 'post_status' => 'publish', 9 'nopaging' => true, 10 'posts_per_page' => '-1', 11 ); 12 13$output = array(); 14 15 if ( isset( $atts['cat_name'] ) && ! empty( $atts['cat_name'] ) ) { 16 $args['category_name'] = preg_replace( '/[^\x01-\x7E]/', '', $atts['cat_name'] ); 17 } 18 19 if ( isset( $atts['tag'] ) && ! empty( $atts['tag'] ) ) { 20 $args['tag'] = preg_replace( '/[^\w\-,]/', '', $atts['tag'] ); 21 } 22 23 if ( isset( $atts['cat_name'] ) && isset( $atts['tag'] ) ) { 24 unset( $args['cat_name'] ); 25 } 26 27・・・ 28・・・ 29・・・ 30
自分でも調べましたが
そもそも'cat_name'がカテゴリー名ではなくスタック名のことらしいのですが
カテゴリーの表示名(日本語)では検索できないのでしょうか?
//こんな感じにしたい [list cat_name="赤,青",tag="Green"]
どなたかアドバイスいただけたら嬉しいです。
ご回答を受けて
以下のように直しました。
PHP
1function shortcode_list( $atts ) { 2 $atts = shortcode_atts( array( 3 'cat_name' => null, 4 'tag' => null, 5 ), $atts, 'list' ); 6 $args = array( 7 'post_type' => 'post', 8 'post_status' => 'publish', 9 'nopaging' => true, 10 'posts_per_page' => '-1', 11 'tax_query' => array( 12 'relation' => 'OR', 13 array( 14 'taxonomy' => 'category', 15 'field' => 'name', 16 'terms' => array($atts['cat_name']), 17 ), 18 ), 19 ); 20 21$output = array(); 22 23 if ( isset( $atts['cat_name'] ) && ! empty( $atts['cat_name'] ) ) { 24 $args['category_name'] = preg_replace( '/[^\x01-\x7E]/', '', $atts['cat_name'] ); 25 } 26 27 if ( isset( $atts['tag'] ) && ! empty( $atts['tag'] ) ) { 28 $args['tag'] = preg_replace( '/[^\w\-,]/', '', $atts['tag'] ); 29 } 30 31 if ( isset( $atts['cat_name'] ) && isset( $atts['tag'] ) ) { 32 unset( $args['cat_name'] ); 33 } 34 35・・・・ 36・・・ 37・・
'terms'の指定を
'terms' => array("赤","青","緑"),
とすると
引数をつけようがつけまいが、カテゴリ名が赤,青,緑のものが常に表示されます。
なので、
'terms' => array($atts['cat_name']),
としました。
これだと[カテゴリ名1つ + タグ複数] 指定で、想定通りの動きになります
[list cat_name="赤",tag="blue,Green"]
が、カテゴリ名を複数指定できません。
できない理由はわかるのですが、どうしたら改善できるのかがわかりません。
[list cat_name="赤,黒",tag="blue,Green"]
↑のようにそれぞれを複数指定した時に
カテゴリ赤のもの、黒のもの、タグがblueのもの,Greenのものが表示されるようにしたいので
'terms'の指定をどのように記述すれば複数の引数を渡すことができるでしょうか?
アドバイスよろしくお願いします。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/18 10:39