Skip to content

Instantly share code, notes, and snippets.

@benhuson
Created September 3, 2015 17:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save benhuson/08b688a437703392bb85 to your computer and use it in GitHub Desktop.
Save benhuson/08b688a437703392bb85 to your computer and use it in GitHub Desktop.
Intelligent Post Terms - use most appropriate category for WordPress post links.
<?php
/**
* Intelligent Post Terms
*
* If the post category is included in the permalink for posts
* we can be clever and detect when a post is displayed or linked to
* which is the most suitable category to use in the URL.
*
* @version 1.0
*/
add_filter( 'post_link_category', array( 'Intelligent_Post_Terms', 'post_link_category' ), 10, 3 );
add_filter( 'get_the_categories', array( 'Intelligent_Post_Terms', 'get_the_categories' ) );
class Intelligent_Post_Terms {
/**
* Post Link Category
*
* Gets categories associated with a post an returns
* the most appropriate category for the context.
*
* @param WP_Term $cat Category object.
* @param array $cats Post category objects.
* @param WP_Post $post Post.
* @return WP_Term Category object.
*/
public static function post_link_category( $cat, $cats, $post ) {
$category_name = self::get_query_category_name();
if ( ! empty( $category_name ) ) {
$category = wp_list_filter( $cats, array( 'slug' => $category_name ) );
if ( ! empty( $category ) ) {
return current( $category );
}
}
return $cat;
}
/**
* Get the Categories
*
* @param array $categories Category objects.
* @return array Category objects.
*/
public static function get_the_categories( $categories ) {
$category_name = self::get_query_category_name();
if ( ! empty( $category_name ) ) {
$category = wp_list_filter( $categories, array( 'slug' => $category_name ) );
if ( ! empty( $category ) ) {
$categories = wp_list_filter( $categories, array( 'slug' => $category_name ), 'NOT' );
$categories = array_merge( $category, $categories );
}
}
return $categories;
}
/**
* Get Query Category Name
*
* Gets the 'category_name' query var and if it's a child category
* remove the category ancestors to get the category slug.
*
* @return string The category slug.
*/
public static function get_query_category_name() {
$category_name = get_query_var( 'category_name' );
// If category name is a path, strip category ancestors
if ( ! empty( $category_name ) && false !== strpos( $category_name, '/' ) ) {
$category_name_parts = explode( '/', $category_name );
$category_name = end( $category_name_parts );
}
return $category_name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment