Christi Richards

Christi Richards


Full-stack web developer and CTO @ NutritionFacts.org

Twitter


"Love this! https://t.co/oxddzkWMD5"

"RT @aloria: Once again a dude is named for a chick's accomplishment.😜good job @TechCrunch https://t.co/6DALd3noDb"

"We still have calendars! https://t.co/NbNxuyPkI2"

Share


Christi Richards

WordPress Related Topics Plugin

Quick tutorial on creating a code snippet to allow for displaying related terms of a custom post type

Christi RichardsChristi Richards

For a recent WordPress project I was working on I needed a way to display related taxonomies (topics) from a custom post type within a single taxonomy template. For this specific project, my custom post type was ‘video’ and its taxonomy was ‘topics’. For each taxonomy page I wanted to show a list of topics related to the video posts they had been tagged in.

Getting Started

First I needed to begin a new $wp_query with the settings below:

$term_slug = get_queried_object()->slug;
$wp_query = new WP_Query;
$args = array(

   // Related Topics based on the current topic

   'post_type'      => 'video',  // Video post type
   'post_status'    => 'publish', // Only check published posts
   'posts_per_page' => 10,       

   // Query the taxonomy

    'tax_query'      => array(
        array(
            'taxonomy' => 'topics', // Checks all the topics associated to the term
            'field'    => 'slug',
            'terms'    => $term_slug, // The term slug
        )
    )
);

Next I want to pass these $args and find the relational terms for each post containing my term slug.

To view our progress at this point, a print_r($related) will show an array of topics and the number of times it has appeared. Success! But not quite there yet.

$results = $wp_query->query( $args );

$related = array();

if( count( $results ) > 0 ) {
    foreach( $results as $result ) {
        $new_related = get_the_terms( $result->ID, 'topics' ); 
        if( is_array( $new_related ) ) {
            foreach( $new_related as $v ) {
                $name = $v->name;
                if( array_key_exists( $name, $related ) )
                    $related[$name]++; // Add to total if existing
                else
                    $related[$name] = 1; // Initialize if it does not exist
            }
        }
    }  
    arsort( $related, SORT_NUMERIC ); // Sort the array numerically
}

So next I need to do few things.

  1. I want to sort the output into a list and make it pretty.
  2. I only want to display 10 results.
  3. Out of these 10 results, I do not want to show the topic of the page I am currently on.
  4. If you did a print_r of the array, you’ll see that the output is not formatted for direct insertion into a URL, so I will need to remove the whitespace of this result and enter a hyphen for use again as a term slug. This is easily achieved with a str_replace and trim. (Pretty basic stuff.)
echo "";

Finishing Up

Since this was something I wanted to show in a custom sidebar of my taxonomy template, I opted for creating a custom plugin. I didn’t need any options with the plugin, just a quick solution, so I just wrapped it up in a function to do what I needed.

Here is the final result:

//Related Topics Function
function related_topics() {

$term_slug = get_queried_object()->slug;
$wp_query = new WP_Query;
$args = array(
    // Related Topics based on the current topic
    'post_type'      => 'video',  // Video post type
    'post_status'    => 'publish', // Only check published posts
    'posts_per_page' => 10,       
    // Query the taxonomy
    'tax_query'      => array(
        array(
            'taxonomy' => 'topics', // Checks all the topics associated to the term
            'field'    => 'slug',
            'terms'    => $term_slug, // The term slug
        )
    )
);

$results = $wp_query->query( $args );

$related = array();

if( count( $results ) > 0 ) {
    foreach( $results as $result ) {
        $new_related = get_the_terms( $result->ID, 'topics' ); 
        if( is_array( $new_related ) ) {
            foreach( $new_related as $v ) {
                $name = $v->name;
                if( array_key_exists( $name, $related ) )
                    $related[$name]++; // Add to total if existing
                else
                    $related[$name] = 1; // Initialize if it does not exist
            }
        }
    }  

    arsort( $related, SORT_NUMERIC ); // Sort the array numerically
}

echo "";
}

Here is the final plugin version tested on WordPress 4.4. Since I didn’t need an options page, you’ll need to edit the file with your own custom post type and taxonomy to make it work for you.

Please feel free to change it to suit your needs or expand upon it.

[prettyfilelink src=”http://www.christirichards.com/wp-content/uploads/2012/03/Related-Topics-1.0.zip” type=”zip”]Download WordPress Related Topics Plugin – 1.0[/prettyfilelink]

If you have any questions, comments, concerns (or criticisms) – leave a comment below.

Post updated on 12/08/2015

Christi Richards is a passionate full-stack web developer currently serving NutritionFacts.org as Chief Technology Officer. She has over 15 years of working industry experience in both front and back-end web technologies.

Comments 0
There are currently no comments.