Advertisement
pusatdata

WP Trik: Code Display WP Category

May 9th, 2016
113
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.42 KB | None | 0 0
  1. Sumber: https://dbarnwal.wordpress.com/2014/07/23/display-category-name-in-post-page/
  2.  
  3. Many times we need to display category name in post page . I have mentioned little code to display category name in post page, blog page.
  4. Display the first category name only:
  5.  
  6. <?php
  7. $category = get_the_category();
  8. echo $category[0]->cat_name;
  9. ?>
  10.  
  11. For more then one category name:
  12.  
  13. <?php
  14. foreach((get_the_category()) as $category) {
  15. echo $category->cat_name . ' ';
  16. }
  17. ?>
  18. Make the first category link to the category page
  19. <?php
  20. $category = get_the_category();
  21. if($category[0]){
  22. echo '<a href="'.get_category_link($category[0]->term_id ).'">'.$category[0]->cat_name.'</a>';
  23. }
  24. ?>
  25. get the post categories from outside the loop:
  26.  
  27. <?php
  28. global $post;
  29. $categories = get_the_category($post->ID);
  30. var_dump($categories);
  31. ?>
  32.  
  33. Display all categories as Links:
  34.  
  35. <?php
  36. $categories = get_the_category();
  37. $separator = ' ';
  38. $output = '';
  39. if($categories){
  40. foreach($categories as $category) {
  41. $output .= '<a href="'.get_category_link( $category->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '">'.$category->cat_name.'</a>'.$separator;
  42. }
  43. echo trim($output, $separator);
  44. }
  45. ?>
  46.  
  47. Display category images:
  48.  
  49. <?php
  50. foreach((get_the_category()) as $category) {
  51. echo '<img src="http://example.com/images/' . $category->cat_ID . '.jpg" alt="' . $category->cat_name . '" />';
  52. }
  53. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement