web-dev-qa-db-ja.com

カスタムショットコードがテキストウィジットで機能なし

Function.phpにショートコードを作成するための関数を作成しました。この機能は以下のようになります

function related_category_sidebar() {
    include_once(WP_PLUGIN_DIR.'/sabai-directory/assets/templates/template_related_category.php');
}
add_shortcode( 'related_category', 'related_category_sidebar' );

今、私は以下のようなカスタムウィジェットサイドバーを作成しました:

add_action( 'widgets_init', 'theme_slug_widgets_init' );
function theme_slug_widgets_init() {
    register_sidebar( array(
         'name' => __( 'Related Category', 'theme-slug' ),
         'id' => 'rel_cat',
         'description' => __( 'Widgets in this area will be shown on all posts and pages.', 'theme-slug' ),
         'before_widget' => '<li id="%1$s" class="widget %2$s">',
         'after_widget'  => '</li>',
         'before_title'  => '<h2 class="widgettitle">',
         'after_title'   => '</h2>',
     ) );
}

さて、このRelated categoryウィジェットエリアにテキストウィジェットを追加しました。それから私はカスタムファイルの中でウィジェットエリアを呼び出した後:

<?php dynamic_sidebar('rel_cat'); ?>

しかしshorcodeは機能していません。ここでは、<?php echo do_shortcode('[related_category]'); ?>ファイルを直接使用しているので、うまくいきました。

しかし、私は自分のコードで何を変更しなければならないのですか?

1
Nisarg Bhavsar

ショートコードはエコーしないで、returndataにする必要があります - 出力バッファリングを使用します インクルードの出力をキャプチャして返します

function related_category_sidebar() {
    ob_start();
    include WP_PLUGIN_DIR . '/sabai-directory/assets/templates/template_related_category.php';
    return ob_get_clean();
}

それから、Charlesが提案したようにしてテキストウィジェットのショートコードを有効にする必要があります。

add_filter( 'widget_text', 'do_shortcode', 11 );
1
TheDeadMedic