I don’t know what your definition of “simple” is, so not sure this qualifies. It’s not really a simple task to do this dynamically.
First, we register a new query var to pass the alternate identifier:
function wpd_portfolios_query_var($query_vars){
$query_vars[] = 'portfolio_key';
return $query_vars;
}
add_filter('query_vars', 'wpd_portfolios_query_var');
Next, we add a rewrite rule to handle incoming requests, and set the query var accordingly:
function wpd_portfolios_rewrite(){
add_rewrite_rule(
'portfolios/([^/]+)/?$',
'index.php?post_type=portfolio&portfolio_key=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_portfolios_rewrite' );
Then we hook parse_query
, check if our query var is set, and convert these requests to singular post requests. Otherwise WordPress will default to setting these requests to is_home
.
function wpd_portfolios_parse( $query ){
if( isset( $query->query_vars['portfolio_key'] ) ){
$query->is_home = 0;
$query->is_single = 1;
$query->is_singular = 1;
}
}
add_action( 'parse_query', 'wpd_portfolios_parse' );
Next we hook pre_get_posts
to set a meta query for the portfolio post with the desired meta value.
function wpd_portfolios_query( $query ){
if( isset( $query->query_vars['portfolio_key'] ) ){
$query->set( 'posts_per_page', 1 );
$meta_query = array(
array(
'key' => 'portfolio_key',
'value' => $query->query_vars['portfolio_key']
)
);
$query->set( 'meta_query', $meta_query );
}
}
add_action( 'pre_get_posts', 'wpd_portfolios_query' );
And lastly, we filter single_template
to load the special template for these requests:
function wpd_portfolios_template( $template="" ){
global $wp_query;
if( isset( $wp_query->query_vars['portfolio_key'] ) ){
$template = locate_template( 'portfolio-special.php', false );
}
return $template;
}
add_filter( 'single_template', 'wpd_portfolios_template' );