2

I am currently creating a shortcode in order to display custom taxonomy terms as a list in my template :

// First we create a function
function list_terms_forme_juridique_taxonomy( $atts ) {

// Inside the function we extract custom taxonomy parameter of our 
shortcode

extract( shortcode_atts( array(
'custom_taxonomy' => 'forme_juridique',
), 
                    $atts ) );

// arguments for function wp_list_categories
$args = array( 
taxonomy => $custom_taxonomy,
title_li => ''
);

// We wrap it in unordered list 
echo '<ul>'; 
echo wp_list_categories($args);
echo '</ul>';
}

// Add a shortcode that executes our function
add_shortcode( 'forme_juridique', 'list_terms_forme_juridique_taxonomy' 
);

I run in the 2 following issues :

  • The shortcode (render) is displayed at the top of my page, not where I've placed it in the page;
  • PHP Console flag the 2 followings errores :
    • Use of undefined constant taxonomy - assumed 'taxonomy'
    • Use of undefined constant title_li - assumed 'title_li'

Any help appreciated!

Thanks

1 Answer 1

2

Firstly the output of your shortcode is displaying at the top of your page because you're echoing the output. You should create a $output variable and build it up with what you want to display, and then return it. For example:

$output = '';
$output .= '<ul>'; 
$output .= wp_list_categories($args);
$output .= '</ul>';
return $output;

Secondly you're getting the errors because you've not quoted the keys in your array declaration. Therefore PHP assumes they should be constants that were previously defined.

$args = array( 
    taxonomy => $custom_taxonomy,
    title_li => ''
);

Should be:

$args = array( 
    'taxonomy' => $custom_taxonomy,
    'title_li' => ''
);
Sign up to request clarification or add additional context in comments.

5 Comments

Thanks, this is better ! No more error. However, the shortcode is still outputted at the top of the page...
It should just depend on where you put your shortcode now. Where in the template is it?
It is in the middle of the page, inside a div
Difficult to say without seeing the site. If you inspect the output using web tools is it in the div as expected? Do you have other content within the same div that is showing where you expect it to?
I just remembered that wp_list_categories echoes by default. You'll also need to add 'echo' => 0 to your $args array.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.