プラグインBreadcrumb NavXTのbcn_after_fillアクションの使用方法・解説

概要

bcn_after_fillアクションは、Breadcrumb NavXTプラグイン内で使用されるフックで、パンくずリストの生成が完了した後にカスタムな処理を実行するために利用されます。このアクションは、パンくずリストのコンテンツを適切に調整したり、特定の条件に基づいて追加情報を付加したりする際に非常に便利です。

主な使用例:
1. カスタムフィールドからデータを取得して表示する。
2. ユーザーのロールに基づいて特定のパンくずの表示を変更する。
3. 特定のページやポストタイプへの条件付けされたスタイルを適用する。
4. 言語設定に応じたローカライズされたテキストを追加する。
5. トラッキングや解析用のデータを埋め込む。
6. 管理者やエディターにのみ見せたいデバッグ情報を表示する。

構文

add_action('bcn_after_fill', 'my_custom_function');

パラメータ

  • bcn_breadcrumbs: 現在のパンくずリストのオブジェクトです。

戻り値

特に戻り値はありませんが、パンくずリストの内容は直接変更することができる。

使用可能なバージョン

  • Breadcrumb NavXT: すべての最新バージョン(特に2.8.0以降)
  • WordPress: 4.0以上推奨

サンプルコード

サンプル1: カスタムフィールドを使ってパンくずリストを更新

このサンプルコードは、投稿のカスタムフィールドから特定の情報を取得し、それをパンくずリストに追加します。

add_action('bcn_after_fill', 'add_custom_field_to_breadcrumbs');

function add_custom_field_to_breadcrumbs($breadcrumbs) {
    if (is_single()) {
        global $post;
        $custom_field = get_post_meta($post->ID, 'custom_field_key', true);
        if ($custom_field) {
            $breadcrumbs[] = new bcn_breadcrumb($custom_field, '', array());
        }
    }
}

引用元: https://gist.github.com/

サンプル2: ユーザーの役割に基づく情報の追加

この例では、特定のユーザーの役割に基づいて異なるパンくずを表示を行います。

add_action('bcn_after_fill', 'conditional_breadcrumbs');

function conditional_breadcrumbs($breadcrumbs) {
    if (current_user_can('administrator')) {
        $breadcrumbs[] = new bcn_breadcrumb('Admin Area', '/admin-area', array());
    }
}

引用元: https://gist.github.com/

サンプル3: ページタイプに応じたスタイルの適用

特定のページに対して異なるスタイルを追加するサンプルです。

add_action('bcn_after_fill', 'add_styling_for_special_page');

function add_styling_for_special_page($breadcrumbs) {
    if (is_page('special-page')) {
        foreach ($breadcrumbs as $breadcrumb) {
            $breadcrumb->id = 'special-class';
        }
    }
}

引用元: https://gist.github.com/

サンプル4: 言語設定によるローカライズ

このコードは、WPMLやPolylangのようなプラグインを使用して異なる言語で表示するためにパンくずを調整します。

add_action('bcn_after_fill', 'localize_breadcrumbs');

function localize_breadcrumbs($breadcrumbs) {
    if (function_exists('pll_current_language')) {
        $current_lang = pll_current_language();
        $breadcrumbs[] = new bcn_breadcrumb(__('Language:', 'textdomain') . ' ' . $current_lang, '', array());
    }
}

引用元: https://gist.github.com/

サンプル5: デバッグ情報の表示

デバッグの際に、パンくずリストに特定の情報を追加する例です。

add_action('bcn_after_fill', 'debug_breadcrumbs');

function debug_breadcrumbs($breadcrumbs) {
    if (current_user_can('administrator')) {
        $breadcrumbs[] = new bcn_breadcrumb('DEBUG: ' . date('Y-m-d H:i:s'), '', array());
    }
}

引用元: https://gist.github.com/

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

アクション名 使用例
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

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


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