こんにちは
以前のこちらのトピックのコードが参考になりませんか?
例:
function my_the_title_menu_category( $title, $post_ID ) {
if ( 'nav_menu_item' == get_post_type( $post_ID ) ) {
if ( 'post_type' == get_post_meta( $post_ID, '_menu_item_type', true ) && 'page' == get_post_meta( $post_ID, '_menu_item_object', true ) ) {
if ( 'メニューのタイトル' === $title ) {
$category = get_category( 123 );
if ( $category->count > 0 ) {
$title .= sprintf( ' (%d)', $category->count );
}
}
}
}
return $title;
}
add_filter( 'the_title', 'my_the_title_menu_category', 10, 2 );
※ コードの、’メニューのタイトル’ は対象のメニューのタイトル、123 はカテゴリー ID。
うまくいきました!ありがとうございます。
あと、メニューなので、複数あるのですが、
その場合単純に上記コードを複数置くと、Wordpressのエラーになってしまいました。
複数メニューでそれぞれに対応するカテゴリーの件数を表示させるには、どのように書けばよろしかったでしょうか?
よろしくお願いいたします。
複数のメニューであれば、下記のようにテーブル ($table) を持たせるのはどうでしょうか?
function my_the_title_menu_category( $title, $post_ID ) {
if ( 'nav_menu_item' == get_post_type( $post_ID ) ) {
if ( 'post_type' == get_post_meta( $post_ID, '_menu_item_type', true ) && 'page' == get_post_meta( $post_ID, '_menu_item_object', true ) ) {
$table = [
'メニュー1' => 123,
'メニュー2' => 456,
'メニュー3' => 789,
];
if ( isset( $table[$title] ) ) {
$category = get_category( $table[$title] );
if ( $category->count > 0 ) {
$title .= sprintf( ' (%d)', $category->count );
}
}
}
}
return $title;
}
add_filter( 'the_title', 'my_the_title_menu_category', 10, 2 );
※ $table は、メニューの名前とカテゴリー ID のテーブルです。
ありがとうございます。テーブルでうまくいきました。
最後に、もし投稿者ない場合にゼロ表記させるには、どのように追記すれば、よろしいでしょうか?
if ( $category->count > 0 ) {
ここで0以上か判定していますよ。
if ( $category->count > 0 ) {
$title .= sprintf( ' (%d)', $category->count );
}
↓
$title .= sprintf( ' (%d)', $category->count );
おっと、すみませんでした。
これではどうでしょうか?
if ( $category->count > 0 ) {
$title .= sprintf( ' (%d)', $category->count );
}
↓
if ( $category->count > 0 ) {
$title .= sprintf( ' (%d)', $category->count );
} else {
$title .= ' (0)';
}
はい、いけました!
ホントにいつもありがとうございます。
余談ではありますが、投稿の画像をアイキャッチに設定出来るプラグインの方、使用させていただいております。
こちらの方もありがとうございます。重宝しております。