How to use register_sidebar's 'before_widget' unique id generator into its other parameters like 'before_title'?

wordpress.stackexchange https://wordpress.stackexchange.com/questions/386759

Question

I'm trying to create a dynamic sidebar that uses bootstrap 4 accordion with the widget's title as the toggle link and the widget content as the accordion's content:

Planned Layout:

<div class="card">
    <div class="card-header">
        <a class="collapsed card-link" data-toggle="collapse" href="#faq-6">
            Widget Title
        </a>
    </div>
    <div id="faq-6" class="collapse" data-parent="#accordion">
        <div class="card-body">
            <p>Widget Content</p> 
        </div>
    </div>
</div>

Register Sidebar Code:

register_sidebar( array(
        'name' => __( 'FAQ', 'rocket' ),
        'id' => 'faq-tabs',
        'description' => __( 'Displays FAQ Tabs', 'rocket' ),
        'before_sidebar' => '<div id="accordion">',
        'after_sidebar' => '</div>',
        'before_widget' => '<div class="card"><div class="card-header"><a class="collapsed card-link" data-toggle="collapse" href="#%1$s">',
        'after_widget' => '</div></div></div>',
        'before_title' => '<h3 class="card-title">',
        'after_title' => '</h3></a><div id="%1$s" class="collapse" data-parent="#accordion">',
    ) );

But when it was rendered on the frontend, the 'after_title' parameter doesn't use/render the same ID that 'before_widget' uses:

<div id="accordion">
<div class="widget_text card">
    <div class="widget_text card-header">
        <a class="widget_text collapsed card-link" data-toggle="collapse" href="#custom_html-14"><h3 class="card-title">Widget Title</h3></a>
        <div id="%1$s" class="collapse" data-parent="#accordion">
            <div class="textwidget custom-html-widget"><p>Widget Content</p></div>
        </div>
    </div>
</div>

Is there some way I can achieve this? Thanks!

Was it helpful?

Solution

You could use the dynamic_sidebar_params filter to do your own substitution.

Something like this:

add_filter('dynamic_sidebar_params', function($params){
    $params[0]['after_title'] = str_replace( '%1$s', $params[0]['widget_id'], $params[0]['after_title'] );
    return $params;
});
Licensed under: CC-BY-SA with attribution
Not affiliated with wordpress.stackexchange
scroll top