Skip to content

Instantly share code, notes, and snippets.

@mikejolley
Created March 21, 2015 01:06
Show Gist options
  • Save mikejolley/118219fd5d887b522ea7 to your computer and use it in GitHub Desktop.
Save mikejolley/118219fd5d887b522ea7 to your computer and use it in GitHub Desktop.
Category and Job Region in job permalink - Must save permalinks after adding the code to functions.php
function job_listing_post_type_link( $permalink, $post ) {
// Abort if post is not a job
if ( $post->post_type !== 'job_listing' ) {
return $permalink;
}
// Abort early if the placeholder rewrite tag isn't in the generated URL
if ( false === strpos( $permalink, '%' ) ) {
return $permalink;
}
// Get the custom taxonomy terms in use by this post
$categories = wp_get_post_terms( $post->ID, 'job_listing_category', array( 'orderby' => 'parent', 'order' => 'ASC' ) );
$regions = wp_get_post_terms( $post->ID, 'job_listing_region', array( 'orderby' => 'parent', 'order' => 'ASC' ) );
if ( empty( $categories ) ) {
// If no terms are assigned to this post, use a string instead (can't leave the placeholder there)
$job_listing_category = _x( 'uncategorized', 'slug' );
} else {
// Replace the placeholder rewrite tag with the first term's slug
$first_term = array_shift( $categories );
$job_listing_category = $first_term->slug;
}
if ( empty( $regions ) ) {
// If no terms are assigned to this post, use a string instead (can't leave the placeholder there)
$job_listing_region = _x( 'anywhere', 'slug' );
} else {
// Replace the placeholder rewrite tag with the first term's slug
$first_term = array_shift( $regions );
$job_listing_region = $first_term->slug;
}
$find = array(
'%category%',
'%region%'
);
$replace = array(
$job_listing_category,
$job_listing_region
);
$replace = array_map( 'sanitize_title', $replace );
$permalink = str_replace( $find, $replace, $permalink );
return $permalink;
}
add_filter( 'post_type_link', 'job_listing_post_type_link', 10, 2 );
function change_job_listing_slug( $args ) {
$args['rewrite']['slug'] = 'job/%category%/%region%';
return $args;
}
add_filter( 'register_post_type_job_listing', 'change_job_listing_slug' );
function add_region_endpoint_tag() {
add_rewrite_tag( '%region%', '([^/]*)' );
}
add_action( 'init', 'add_region_endpoint_tag' );
@atcraigwatson
Copy link

atcraigwatson commented Apr 15, 2018

@mikejolley - Since the update to include text boxes in the admin that specify the 3 main slug options, should this code be updated to include the option from the settings rather than overwriting it in this function?

Just thinking of a site owner updating the settings for - /job/ and not seeing it reflected in the url.

@jordiroscamps
Copy link

Hi, Is there any way to add in permalink the types of jobs, in addition to the categories and regions? Sorry for my english.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment