1

We're in the process of migrating all of our content from one site to another site and I'm trying to figure out how to programmatically create a bunch of redirects from the old URL to the new URL on a different domain. What I'm trying to do is similar to what I can manually do via Safe Redirect Manager, but I'm having trouble finding how to do it programmatically from PHP.

I'm aware of the safe_redirect method, but I think that only applies to the current page being viewed - not something that is persisted for a bunch of URLs like Safe Redirect Manager.

To clarify - we're not trying to replicate the functionality of Safe Redirect Manager. We intend to keep that running on the old site - we're just looking for help on how to create an instance of the Safe Redirect Manager's post type for each URL we need to redirect.

1 Answer 1

0

By looking over the code of Safe Redirect Manager, we were able to find what we were looking for. We just needed to create an instance of the redirect post type using code similar to this:

$post_args = array(
    'post_type'   => 'redirect_rule',
    'post_status' => $sanitized_post_status,
    'post_author' => 1,
    'menu_order'  => $sanitized_menu_order,
);

$post_id = wp_insert_post( $post_args );

if ( 0 >= $post_id ) {
    return new WP_Error( 'error-creating', esc_html__( 'An error occurred creating the redirect.', 'safe-redirect-manager' ) );
}

// update the posts meta info
update_post_meta( $post_id, '_redirect_rule_from', wp_slash( $sanitized_redirect_from ) );
update_post_meta( $post_id, '_redirect_rule_to', $sanitized_redirect_to );
update_post_meta( $post_id, '_redirect_rule_status_code', $sanitized_status_code );
update_post_meta( $post_id, '_redirect_rule_from_regex', $sanitized_enable_regex );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.