0

Learning as I go...

I have this functionality built, but I need it as a shortcode. How do I do that?

$args = array( 'taxonomy' => 'product_cat' );
$terms = get_terms('product_cat', $args);

$count = count($terms); $i=0;
if ($count > 0) {
    $cape_list = '<p class="my_term-archive">';
    foreach ($terms as $term) {
        $i++;
        $term_list .= '<a href="/term-base/' . $term->slug . '" title="' . sprintf(__('View all post filed under %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '</a>';
        if ($count != $i) $term_list .= ' &middot; '; else $term_list .= '</p>';
    }
    echo $term_list;
}
1

1 Answer 1

2

Like this:

add_shortcode('SHORTCODE_NAME', 'SHORTCODE_NAME_shortcode');  

function SHORTCODE_NAME_shortcode() {

// PUT YOUR CODE HERE


}

Then you can just do [SHORTCODE_NAME] and whatever is in the SHORTCODE_NAME_shortcode() function will do its thing.

4
  • in your CODE HERE section, make sure not to use any function that echos the output.
    – Michael
    Commented Nov 27, 2013 at 9:39
  • So, like this? And do I put this in the custom.css? add_shortcode('CATEGORY_LIST', 'CATEGORY_LIST_shortcode'); <to be ctd>
    – Katy W
    Commented Nov 27, 2013 at 19:41
  • function CATEGORY_LIST_shortcode() {$args = array( 'taxonomy' => 'product_cat' ); $terms = get_terms('product_cat', $args); $count = count($terms); $i=0; if ($count > 0) { $cape_list = '<p class="my_term-archive">'; foreach ($terms as $term) { $i++; $term_list .= '<a href="/term-base/' . $term->slug . '" title="' . sprintf(__('View all post filed under %s', 'my_localization_domain'), $term->name) . '">' . $term->name . '</a>'; if ($count != $i) $term_list .= ' &middot; '; else $term_list .= '</p>'; } echo $term_list; }
    – Katy W
    Commented Nov 27, 2013 at 19:42
  • You dont need to put it in caps, I just did that so you could see what to replace. Simply copy the code you've got and paste it where it says //your code here (which it looks like you've done). Then copy the whole function and put it in your themes functions.php file. Then you can use your shortcode in whatever template/page/post you want.
    – Jon Furry
    Commented Nov 27, 2013 at 20:17

Your Answer

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

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