danjjohnson
5/26/2016 - 8:42 AM

WPJM: Add job type to base URL

WPJM: Add job type to base URL

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
	$terms = wp_get_post_terms( $post->ID, 'job_listing_type', array( 'orderby' => 'parent', 'order' => 'ASC' ) );

	if ( empty( $terms ) ) {
		// If no terms are assigned to this post, use a string instead (can't leave the placeholder there)
		$job_listing_type = _x( 'uncat', 'slug' );
	} else {
		// Replace the placeholder rewrite tag with the first term's slug
		$first_term = array_shift( $terms );
		$job_listing_type = $first_term->slug;
	}
	
    $find = array(
    	'%jobtype%'
    );

    $replace = array(
    	$job_listing_type
    );

    $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/%jobtype%';
  return $args;
}
add_filter( 'register_post_type_job_listing', 'change_job_listing_slug' );