I'm having troubles understanding how add_rewrite_rule works in my case.
I have a page which lists news from an external source.
All items are linked with a "read more". Those links look like: domain.com/news/single/?id=12345&title=title-of-this-news
Everything works fine. If I click the link the "single" page reads the "id" param and displays the output I want it to.
Well to make this pretty I want the links to look like this: domain.com/news/12345/title-of-this-news
which means /single/ not part of the url - the first part is the ID I need to fetch it's data and the title the last part.
Can someone help me with this? Thanks!
EDIT: due to one of the answers I came up with this to match my URL, params, and so on - but it is not working (permalinks are resaved):
// Register the custom rewrite rule.
function wpse_373628_init() {
add_rewrite_rule(
// Matches /news/<id>/<title-slug> in the URL.
'^news-events/single/(\d+)/([^/]+)/?$',
// You could also add &news_title=$matches[2], but I think the ID is
// enough for you to identify the single news being requested.
'index.php?pagename=news-events/single&newsID=$matches[1]&newsTitle=$matches[2]', // query by slug
// 'index.php?page_id=123&news_id=$matches[1]', // or query by ID
'top'
);
}
add_action( 'init', 'wpse_373628_init' );
// And register the custom query arg.
function wpse_373628_query_vars( $vars ) {
$vars[] = 'newsID';
$vars[] = 'newsTitle'; // if you're using news_title in the rewrite rule
return $vars;
}
add_filter( 'query_vars', 'wpse_373628_query_vars' );
single
andnews
? Are they Pages, i.e. posts of thepage
type? Also, if the pretty URL doesn't include theid
, then would you still be able to identify what the single news feed is based solely on the title (e.g. thetitle-of-this-news
)?