Skip to content

Instantly share code, notes, and snippets.

@jonnyvaughan
Created July 19, 2019 13:11
Show Gist options
  • Save jonnyvaughan/47c01f63cd905838ee685a6fea260d36 to your computer and use it in GitHub Desktop.
Save jonnyvaughan/47c01f63cd905838ee685a6fea260d36 to your computer and use it in GitHub Desktop.
rewrite structure
<?php
class TD_Custom_Rewrites {
public function __construct() {
// set up rewrite tags
add_rewrite_tag('%query1%', '([^&]+)');
add_rewrite_tag('%query2%', '([^&]+)');
add_rewrite_tag('%query3%', '([^&]+)');
add_rewrite_tag('%query4%', '([^&]+)');
// this rewrite rule uses /browse-by/ as a hardcoded URL structure and a page ID of 7 to show the results.
// /browse-by/sector/type/location/hours
// e.g. /browse-by/accounting/permanent/wokingham/full-time/
add_rewrite_rule( '^browse-by/([^/]*)?(/[^/]*)?(/[^/]*)?(/[^/]*)?/?', 'index.php?page_id=7&query1=$matches[1]&query2=$matches[2]&query3=$matches[3]&query4=$matches[4]', 'top' );
$this->register_taxonomies();
}
// this function should be called from within a page template.
public function generate_query() {
$maybes = [];
$maybes[] = $wp_query->query_vars['query1'];
$maybes[] = $wp_query->query_vars['query2'];
$maybes[] = $wp_query->query_vars['query3'];
$maybes[] = $wp_query->query_vars['query4'];
foreach ( $maybes as &$maybe ) {
if ( $check = get_term_by( "slug", $maybe, "sector") ) {
$params['sector'] = str_replace("-", " ", $check->slug);
}elseif ( $check = get_term_by( "slug", $maybe, "type") ) {
$params['job_type'] = str_replace("-", " ", $check->slug);
}elseif ( $check = get_term_by( "slug", $maybe, "location") ) {
$params['search_keywords'] = $check->slug;
}elseif ( $check = get_term_by( "slug", $maybe, "hours") ) {
switch ( $check->slug ) {
case "full-time":
$params['search_preferred_hours'] = 2;
break;
case "part-time":
$params["search_preferred_hours"] = 1;
break;
}
}
}
print_r( $params );
// you'll then need to get these params into a WP_Query object to return the right results.
}
public function register_taxonomies() {
// this is only needed if you haven't registered your taxonomies yet.
register_taxonomy(
'type',
'job',
array(
'label' => __( 'Type' ),
'rewrite' => array( 'slug' => 'type' ),
'hierarchical' => true,
)
);
register_taxonomy(
'sector',
'job',
array(
'label' => __( 'Sector' ),
'rewrite' => array( 'slug' => 'sector' ),
'hierarchical' => true,
)
);
register_taxonomy(
'location',
'job',
array(
'label' => __( 'Location' ),
'rewrite' => array( 'slug' => 'location' ),
'hierarchical' => true,
)
);
register_taxonomy(
'hours',
'job',
array(
'label' => __( 'Preferred Hours' ),
'rewrite' => array( 'slug' => 'hours' ),
'hierarchical' => true,
)
);
}
}
new TD_Custom_Rewrites();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment