Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- /* WORDPRESS: Add prefix to post title in a page template, using one or more custom taxonomy terms.
- CASE: Website has a custom post type called 'Events' and a custom taxonomy called 'Nights'
- that behaves like post categories (hierarchical). New 'Nights' were added in order, starting
- with 'Monday' and ending with 'Sunday', so that term_id could be used for sorting. When 'Events'
- are created, one or more 'Nights' can be selected. This code adds a prefix to the event title.
- EXAMPLE: If event title is 'College Night' and 'Thursday' is selected, event title becomes
- 'Thursday: College Night'
- PUNCTUATION: If multiple nights are selected, they get separated by commas and/or an ampersand.
- EXAMPLE: 'Thursday & Friday: College Night' -OR- 'Thursday, Friday & Saturday: College Night'
- */
- // Get the 'nights' custom taxonomy terms object for the current post
- $terms = get_the_terms( $post->ID, 'nights' );
- // Only create a prefix if the current post has 'nights' associated with it
- if ( $terms && ! is_wp_error( $terms ) ){
- $nightname = array();
- $nightorder = array();
- foreach ( $terms as $term ) {
- // Store night names (e.g. 'Monday', 'Tuesday') in an array
- $nightname[] = $term->name;
- // Store night term IDs in array; assumes they were added in order
- $nightorder [] = $term->term_id;
- }
- // Combine night names and ids as key=>value pairs in an associative array
- $nights = array_combine( $nightname, $nightorder );
- // Sort the nights by numeric value (term ID)
- asort( $nights, SORT_NUMERIC );
- // Combine night names, adding punctuation
- $prefix = join( ' & ', array_keys( $nights ) ) . ': ';
- // Convert all but the last ampersand into a comma
- $prefix = preg_replace( '/ \&(?=.*\&)/', ', ', $prefix );
- }
- <a href="<?php the_permalink();?>" alt="link to <?php the_title(); ?>"><h2><?php echo $prefix; the_title();?></h2></a>
- ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement