Instantly share code, notes, and snippets.

Embed
What would you like to do?
function dm_display_wpjm_categories () {
$terms = get_terms( array(
'taxonomy' => 'job_listing_category',
'hide_empty' => false,
) );
if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
echo '<ul>';
foreach ( $terms as $term ) {
echo '<li>' . '<a href="' . esc_url( get_term_link( $term ) ) . '">' . $term->name . '</a></li>';
}
echo '</ul>';
}
}
add_shortcode('list_categories', 'dm_display_wpjm_categories');
@DonKoko

This comment has been minimized.

DonKoko commented Feb 13, 2018

Great snippet. My only suggestion/improvement is to use Output Buffering so this shortcode can be used anywhere on the page. Here is my version:

// Shortcode for showing job categories
function dm_display_wpjm_categories () {
  $terms = get_terms( array('taxonomy' => 'job_listing_category',
                            'hide_empty' => false,));

  // begin output buffering
  ob_start();

  if ( ! empty( $terms ) && ! is_wp_error( $terms ) ){
    echo '<ul class="job-categories-wrapper">';
    foreach ( $terms as $term ) {
      echo '<li>' . '<a href="' . esc_url( get_term_link( $term ) ) . '">' . $term->name . '</a></li>';
    }
    echo '</ul>';
  }

  // end output buffering, grab the buffer contents, and empty the buffer
  return ob_get_clean();
}

add_shortcode('list_categories', 'dm_display_wpjm_categories');

Hope this helps someone who had the same issue as me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment