プラグインBreadcrumb NavXTのbcn_li_attributesフィルタの使用方法・解説

概要

bcn_li_attributes フィルタは、WordPress の Breadcrumb NavXT プラグインにおいて、パンくずリストアイテムの <li> タグに追加の属性を加えるために使用されます。このフィルタを利用することで、特定の条件に基づいてカスタム属性(例:クラス、ID、データ属性など)を設定することができます。これにより、CSS や JavaScript を使用してパンくずリストをより柔軟にスタイリングしたり、機能を追加したりすることが可能になります。

以下に、bcn_li_attributes フィルタがよく使用される機能の例を挙げます:
1. カスタム CSS クラスを追加する
2. JavaScript 用のデータ属性を追加する
3. 特定の条件に基づくクラスの条件付き追加
4. リンクのアクティブ状態を示す属性を追加する
5. SEO 効果のある属性(例:rel=”nofollow”)を追加する
6. XPath 構造と合わせたカスタマイズを行う

構文

フィルタは以下のように使用します。

add_filter('bcn_li_attributes', 'your_custom_function', 10, 2);

パラメータ

  • $attributes: array – 追加するカスタム属性。
  • $crumb: object – 現在のパンくずアイテム。

戻り値

  • array – 追加されたカスタム属性を含む配列。

互換性

  • Breadcrumb NavXT バージョン: 6.0.0 以降。
  • WordPress バージョン: 4.0 以降。

この関数のアクションでの使用可能性

アクション 使用例
mu_plugin_loaded
registered_post_type
plugins_loaded
wp_roles_init
setup_theme
after_setup_theme
set_current_user
init
register_sidebar
wp_loaded
send_headers
parse_query
pre_get_posts
wp
template_redirect
get_header
wp_head

サンプルコード

サンプルコード 1

add_filter('bcn_li_attributes', 'add_custom_class_to_breadcrumb', 10, 2);

function add_custom_class_to_breadcrumb($attributes, $crumb) {
    $attributes['class'] = 'my-custom-class';
    return $attributes;
}

このコードは、すべてのパンくずアイテムに my-custom-class というカスタム CSS クラスを追加します。

サンプルコード 2

add_filter('bcn_li_attributes', 'add_data_attribute_to_breadcrumb', 10, 2);

function add_data_attribute_to_breadcrumb($attributes, $crumb) {
    $attributes['data-crumblink'] = 'true';
    return $attributes;
}

このコードは、すべてのパンくずアイテムに data-crumblink="true" 属性を追加します。

サンプルコード 3

add_filter('bcn_li_attributes', 'conditional_class_for_breadcrumb', 10, 2);

function conditional_class_for_breadcrumb($attributes, $crumb) {
    if ($crumb->id == 'home') {
        $attributes['class'] = 'home-item';
    }
    return $attributes;
}

このコードでは、ID が home のパンくずアイテムに home-item というクラスを追加します。

サンプルコード 4

add_filter('bcn_li_attributes', 'add_nofollow_to_external_links', 10, 2);

function add_nofollow_to_external_links($attributes, $crumb) {
    if ($crumb->url != get_home_url()) {
        $attributes['rel'] = 'nofollow';
    }
    return $attributes;
}

このコードは、外部リンクに rel="nofollow" 属性を追加します。

サンプルコード 5

add_filter('bcn_li_attributes', 'add_id_to_breadcrumb', 10, 2);

function add_id_to_breadcrumb($attributes, $crumb) {
    $attributes['id'] = 'breadcrumb-' . $crumb->id;
    return $attributes;
}

このコードは、それぞれのパンくずアイテムにユニークな ID を追加します。

これらのサンプルコードは、bcn_li_attributes フィルタの様々な使い方を示しています。様々な条件に基づいて、パンくずリストの表示をカスタマイズする際に役立ちます。

この関数について質問する


上の計算式の答えを入力してください