Last active
November 26, 2024 06:51
-
-
Save joshuadavidnelson/3b320988859efc054d0f7ec5aba61519 to your computer and use it in GitHub Desktop.
Programmatically add a redirect to the Yoast SEO Premium redirects.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Create a new redirect within the Yoast redirect system. | |
* | |
* @param string $origin_url redirecting from. | |
* @param string $destination_url redirecting to. | |
* @param int $type redirect code, defaults to 301. | |
* @param string $format the format, either 'plain' or 'regex', defaults to 'plain'. | |
* @return void | |
*/ | |
function add_yoast_redirect( $origin_url, $destination_url, $type = 301, $format = 'plain' ) { | |
$redirect_option = new WPSEO_Redirect_Option(); | |
$redirect_array = array( | |
'origin' => $origin_url, | |
'url' => $destination_url, | |
'type' => $type, | |
'format' => $format, | |
); | |
// Add the redirect to Yoast SEO table. | |
$redirect_object = new WPSEO_Redirect( $redirect_array['origin'], $redirect_array['url'], $redirect_array['type'], $redirect_array['format'] ); | |
$redirect_option->add( $redirect_object ); | |
$redirect_option->save(); | |
// Apply the redirect. | |
$manager = new WPSEO_Redirect_Manager(); | |
$manager->export_redirects(); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A few changes to make in order to make things work:
'origin' => $redirect_url,
to'origin' => $orgin_url,
line 16 (or $origin_url with an 'i', but then also change it in the function declaration)$manager = new WPSEO_Redirect_Manager();
$manager->export_redirects();