web-dev-qa-db-ja.com

Bodyタグのclass属性に現れるクラスのリストにpostまたはpageタグを追加するにはどうすればいいですか?

良い一日、

おそらくあなたはphp初心者を手伝っても構わないと思っています。

Bodyタグのclass属性に現れるクラスのリストにpostまたはpageタグを追加しようとしています。これらのクラスはheader.phpによってHTMLに出力されます。

<body <?php body_class(''); ?>>

これまでは、次のコードを使用して自分のページタグをmeta要素に出力していました。

<meta name="print-post-tag" content="<?php
$posttags = get_the_tags();
if ($posttags) {
    foreach($posttags as $tag) {
        echo $tag->name;
    }
}
?>
" >

注:投稿にはデフォルトでタグが付いていますが、私はプラグインの "タグページ"を使ってページにタグを追加します。

だから今私はよく使われているボディ属性クラス空間で同様のことをやろうとしています。

http://codex.wordpress.org/Function_Reference/body_class および http://codex.wordpressでコーデックスを読んだ後。 org/Function_Reference/the_tags 、これを行う最善の方法は私のテーマのfunctions.phpにフィルターを追加することであることを発見しました。

私の最初の試みはエラー以外何もしませんでした:(ここで複数のコードエラー)

function the_tags( $classes ) {
global $tag;
foreach ( get_the_tags( $tag->name ) as $category ) {
    $classes[] = $category->category_nicename;
}
return $classes;
}
add_filter( 'body_class', 'the_tags' );

注:私はWordPressのテンプレート構造とその多くの変数や機能についての構造的な理解に欠けています。

2回目の試み:Ryan's( https://stackoverflow.com/questions/11232676/trying-to-add-the-slug-to-my-body-class-with-noを実行してみました-success-in-wordpress-can-anyone )が解決策を提案したが、私のhtmlはページタグを表示していない。これは私が私のテーマのfunctions.phpの一番下に落とした試みです:

function a_beautiful_new_body_class() {  // adding a class to <body> tag
global $wp_query;
$tag = '';
if (is_front_page() ) {
    $tag = 'home'; // 'home' as class for the home page
} elseif (is_page()) {
    $tag = $wp_query->query_vars["tag"]; // placing the tag
}
if ($tag)
    echo 'class= "'. $tag. '"';
}

どうやってこの問題に取り組みますか?

親切に、

1
hamburger

あなたは近いです。あなたの最初の試みはget_the_tagsを間違って使っています。この関数は、タグを取得したい投稿IDを受け取ります。あなたの例では、$tagグローバルがないので、$tag->nameは非オブジェクトのプロパティを取得しようとしています。

2回目の試みでは、1つの投稿にタグ関連のクエリ変数がありません。これはタグアーカイブページにのみ設定されます(タグ分類は実際には背後でpost_tagという名前になります)。

それで、これはあなたの例で問題を解決する実用的なバージョンです。現在の投稿/ページIDをget_queried_object_id()に渡すためにget_the_tags()を使うことに注意してください。 global $postを使用してから$post->IDを使用してIDを関数に渡す他の例を見ることもできますが、これも機能します。

function add_tags_to_body_class( $classes ) {

    // if this is a page or a single post
    // and this page or post has tags
    if( ( is_page() || is_single() )
        && $tags = get_the_tags( get_queried_object_id() ) ){

        // loop over the tags and put each in the $classes array
        // note that you may want to prefix them with tag- or something
        // to prevent collision with other class names
        foreach( $tags as $tag ) {
            $classes[] = $tag->name;
            // or alternately, with prefix
            // $classes[] = 'tag-' . $tag->name;
        }
    }

    // return the $classes array
    return $classes;

}
add_filter( 'body_class', 'add_tags_to_body_class' );
1
Milo