Skip to content

Instantly share code, notes, and snippets.

@joshuadavidnelson
Last active June 10, 2023 04:47
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joshuadavidnelson/3b320988859efc054d0f7ec5aba61519 to your computer and use it in GitHub Desktop.
Save joshuadavidnelson/3b320988859efc054d0f7ec5aba61519 to your computer and use it in GitHub Desktop.
Programmatically add a redirect to the Yoast SEO Premium redirects.
<?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();
}
@fluktegrute
Copy link

A few changes to make in order to make things work:

  1. change 'origin' => $redirect_url, to 'origin' => $orgin_url, line 16 (or $origin_url with an 'i', but then also change it in the function declaration)
  2. With this code, redirects are well placed in the table in the Yoast plugin, but are not applied. You need to add the following after the save() method :
    $manager = new WPSEO_Redirect_Manager();
    $manager->export_redirects();

@joshuadavidnelson
Copy link
Author

Hey @fluktegrute thanks so much for the feedback! I've updated the function above accordingly.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment