jeudi 29 janvier 2015

Get all custom taxonomies for a post, it's values, and use values for each in HTML


I am building out a database template which will show data stored in a mix of custom fields and custom taxonomies. When finished, there will be a potential for 50 different custom taxonomies with data for any given post.


I am trying to avoid writing out each individual custom-taxonomy in it's own if statement. And pinging the database that many times per page load (if possible).


I currently have this:



//For getting data belonging to custom taxonomy "Years", for this post

$termyears = get_the_terms( $post->ID, 'years' );

if ( $termyears && ! is_wp_error( $termyears ) ) {

foreach ( $termyears as $termyear ) {
$termyears_with_links[] = '<a href="'.$termyear->taxonomy.'/'.$termyear->slug.'/">'.$termyear->name.'</a>';
$termyears_without_links[] = $termyear->name;
}

$termyears_with_links_final = join( ", ", $termyears_with_links );
$termyears_without_links_final = join( ", ", $termyears_without_links );

}

//Then we use those variables below in HTML build out

if ($termyears != '') { echo '<li>Year: '. $termyears_with_links_final .'</li>'; }


And, I need to do this 50 times, for 50 custom taxonomies, all printed out at different places on the page, not just a list in one spot.


One other monkey wrench, it won't always be this simple list element with/without links. We need to check values, print differently depending on results, if they exist. Example:



$termstatuses = get_the_terms( $post->ID, 'status' );

if ( $termstatuses && ! is_wp_error( $termstatuses ) ) {

foreach ( $termstatuses as $termstatus ) {
$termstatuses_with_links[] = '<a href="'.$termstatus->taxonomy.'/'.$termstatus->slug.'/">'.$termstatus->name.'</a>';
$termstatuses_without_links[] = $termstatus->name;
}

$termstatuses_with_links_final = join( ", ", $termstatuses_with_links );
$termstatuses_without_links_final = join( ", ", $termstatuses_without_links );

}

if ($termstatus !='') {

echo '<li>Status: ';

if ($termstatus_nolinks_final == 'Released') {
echo 'Released';
} else {
echo $termstatus_links_final;
}

echo '</li>';
}


So, how can we call all taxonomies, turn each one and it's terms into a variable, once.


Then all able to be referenced like:



$years(term->name)
$years(term->slug)
$statuses(term->name)
$statuses(term->slug)

//aka

$taxslug(term->name)
$taxslug(term->slug)


...For use in HTML build out like shown above?





Aucun commentaire:

Enregistrer un commentaire