Advertisement
sscovil

WordPress Custom Taxonomy Terms as Post Title Prefix

Aug 3rd, 2012
133
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.88 KB | None | 0 0
  1. <?php
  2. /*  WORDPRESS: Add prefix to post title in a page template, using one or more custom taxonomy terms.
  3.  
  4.     CASE: Website has a custom post type called 'Events' and a custom taxonomy called 'Nights'
  5.     that behaves like post categories (hierarchical). New 'Nights' were added in order, starting
  6.     with 'Monday' and ending with 'Sunday', so that term_id could be used for sorting. When 'Events'
  7.     are created, one or more 'Nights' can be selected. This code adds a prefix to the event title.
  8.    
  9.     EXAMPLE: If event title is 'College Night' and 'Thursday' is selected, event title becomes
  10.     'Thursday: College Night'
  11.  
  12.     PUNCTUATION: If multiple nights are selected, they get separated by commas and/or an ampersand.
  13.    
  14.     EXAMPLE: 'Thursday & Friday: College Night' -OR- 'Thursday, Friday & Saturday: College Night'
  15. */
  16.     // Get the 'nights' custom taxonomy terms object for the current post
  17.     $terms = get_the_terms( $post->ID, 'nights' );
  18.     // Only create a prefix if the current post has 'nights' associated with it
  19.     if ( $terms && ! is_wp_error( $terms ) ){
  20.         $nightname = array();
  21.         $nightorder = array();
  22.         foreach ( $terms as $term ) {
  23.             // Store night names (e.g. 'Monday', 'Tuesday') in an array
  24.             $nightname[] = $term->name;
  25.             // Store night term IDs in array; assumes they were added in order
  26.             $nightorder [] = $term->term_id;
  27.         }
  28.         // Combine night names and ids as key=>value pairs in an associative array
  29.         $nights = array_combine( $nightname, $nightorder );
  30.         // Sort the nights by numeric value (term ID)
  31.         asort( $nights, SORT_NUMERIC );
  32.         // Combine night names, adding punctuation
  33.         $prefix = join( ' & ', array_keys( $nights ) ) . ': ';
  34.         // Convert all but the last ampersand into a comma
  35.         $prefix = preg_replace( '/ \&(?=.*\&)/', ', ', $prefix );
  36.     }
  37.     <a href="<?php the_permalink();?>" alt="link to <?php the_title(); ?>"><h2><?php echo $prefix; the_title();?></h2></a>
  38. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement