wp-graphql-yoast-seo
wp-graphql-yoast-seo copied to clipboard
Querying redirects using where params
There are cases that we need to query if there is a redirection set for a specific URI. For example, in case of "not found error" you may want to redirect the user to correct page instead of showing a 404 page.
Currently, we can get all redirects from the SEO (Yoast config) node but it is not feasible to get a full list of redirects and filter on client side. It would be perfect if we can query the redirect with a where param, use the query result to redirect to correct page or to throw a 404 error.
I would like to know your thoughts and possible development ideas on this.
Running into the same need
Here is my workaround for now.
Added a new field to the Root that takes a URI param and searches for a redirect. I use this alongside nodeByUri so if nodeByUri is null and the redirect exists I handle it. If both are null then that's a proper 404.
register_graphql_field( 'RootQuery', 'redirect', [
'type' => 'String',
'description' => __( 'Check if uri has redirect' ),
'args' => [
'uri' => [
'type' => [ 'non_null' => 'String' ],
'description' => __( 'The uri to check for redirect' ),
],
],
'resolve' => function($root, $args) {
$redirectsObj = class_exists('WPSEO_Redirect_Option') ? new \WPSEO_Redirect_Option() : false;
$lookup = $redirectsObj ? $redirectsObj->get($args['uri']) : false;
$redirect = $lookup ? $lookup->get_target() : null;
return $redirect;
}
] );