As for what you asked:
If I have domain.com/something/{$variable} how do I retrieve that
$variable
In your case, you would want to do these:
-
Add that variable to the public query variables which are automatically parsed by WordPress, e.g. from the URL of the current page.
-
Add a custom rewrite rule which will let WordPress know what should be displayed for that URL.
-
Use
get_query_var()
to get the value of that variable.
Here’s a working example for the domain.com/<post type>/for/<hobby>
structure:
-
Add the variable, which I named it
for_hobby
, using thequery_vars
hook:add_filter( 'query_vars', 'my_custom_query_vars' ); function my_custom_query_vars( $vars ) { // Add the variable. $vars[] = 'for_hobby'; return $vars; }
-
Add the custom rewrite rule, using
add_rewrite_rule()
:add_action( 'init', 'my_custom_rewrite_rules' ); function my_custom_rewrite_rules() { // Your post types, which are used in the permalink URL. $post_types = array( 'articles', 'photos' ); add_rewrite_rule( // Regular expression (RegEx) pattern for matching variables in the URL. '(' . implode( '|', $post_types ) . ')/for/([^/]+)(?:/page/(\d+)|)/?$', // The query variables which are passed to WP_Query. 'index.php?post_type=$matches[1]&for_hobby=$matches[2]&paged=$matches[3]', 'top' ); }
That
(?:/page/(\d+)|)
and&paged=$matches[3]
is for paginated requests, e.g. page 2 atdomain.com/articles/for/baseball/page/2
.PS: Don’t forget to flush the rewrite rules! (Or re-save your permalinks) Just visit the Permalink Settings admin page without having to do anything else on that page.
-
To get the variable’s value, use
get_query_var( 'for_hobby' )
.
But, are you absolutely sure you do not want to use categories?
Because a taxonomy can be attached to one or more post types, so you can use just one Hobby taxonomy containing various topics which can be shared among the different post types. E.g.
-
Create Hobby as a taxonomy and attach the Hobby taxonomy to your post types (Articles and Photos).
-
Create Baseball as a term/category in the Hobby taxonomy, and just assign your posts to that category.
That way,
domain.com/hobby/baseball
will display Articles/Photos assigned to the Baseball category.What’s more, you can pretty easily filter the posts by post type via the
post_type
parameter:-
domain.com/hobby/baseball?post_type=articles
— displays only the Articles in the Baseball Hobby -
domain.com/hobby/baseball?post_type=photos
— displays only the Photos in the Baseball Hobby
-