0

Hi guys im doing a custom shortcode where the client can set a custom taxonomy and display in my sidebar

I want to use a template using the get_template_part but i dont get the terms of the taxonomy

I'm using the following code to display the shortcode

function cat_widgets( $atts ) {
    ob_start();
    get_template_part('templates/show-taxonomy');
    return ob_get_clean();
} 
add_shortcode( 'cat_widgets', 'cat_widgets' );

add_filter( 'widget_text', 'do_shortcode' );

And in the show-taxonomy.php my code is

<?php
    $atts = shortcode_atts( array(
        'custom_taxonomy' => '',
    ), $atts, 'atributes' );
    $terms_categorias = get_terms([
        'taxonomy' => $atts['custom_taxonomy'],
        'hide_empty' => false,
        'orderby' => 'term_id',
        'order' => 'ASC' 
    ]);
    ?>
    
    <ul class="product-categories">
        <?php foreach($terms_categorias as $term): ?>
            <li class="cat-item">
                <a href="<?php echo esc_url( get_term_link($term) ); ?>">
                    <?php echo esc_html($term->name); ?>
                </a>
            </li>
        <?php endforeach; ?>
    </ul>
    

I also tried to put the atts and get the terms in the shortcode after de ob_start(); but the returns is the same

Is there something that im missing?

1 Answer 1

1

The $atts in your template part (templates/show-taxonomy.php) that you passed to shortcode_atts() is not defined, so you need to define it by passing it via the third parameter for get_template_part() like this:

get_template_part( 'templates/show-taxonomy', '', array( 'atts' => $atts ) );

Then in the template part, use $args['atts'] to access the shortcode parameters:

$atts = shortcode_atts( array(
    'custom_taxonomy' => '',
), $args['atts'], 'atributes' ); // here, use $args['atts'] and not $atts

And actually, in the above shortcode_atts() call, the third parameter should be cat_widgets (i.e. the 1st parameter for add_shortcode()) and not atributes. :)

2
  • 1
    It works wonderfull, thank you so much!
    – Maria
    Sep 2, 2021 at 2:56
  • Glad it helped! :-) (PS: I revised my answer a bit - mainly to reword the first paragraph).
    – Sally CJ
    Sep 2, 2021 at 3:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.