Skip to content

Instantly share code, notes, and snippets.

@elvismdev
Last active January 26, 2022 21:15
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save elvismdev/914a67f26b91b3e1c6e097ab62f8aba5 to your computer and use it in GitHub Desktop.
Save elvismdev/914a67f26b91b3e1c6e097ab62f8aba5 to your computer and use it in GitHub Desktop.
<?php
/*
Plugin Name: WP All Import - Redirection AddOn
Description: Add a redirect for each post imported.
*/
// If this file is called directly, abort.
if ( ! defined( 'WPINC' ) ) {
die;
}
/**
* Create a redirect.
*
* @param string $source
* @param string $target
* @param string $group_name
*/
function create_redirect( $source, $target, $group_name = 'migration' ) {
// Get the correct group ID, group will need to exist.
global $wpdb;
$group_id = $wpdb->get_var( "SELECT id FROM {$wpdb->prefix}redirection_groups WHERE name='{$group_name}'" );
// Check if a redirect for this URL already exists.
$exists = Red_Item::get_for_url( $source );
if ( empty( $exists ) && !empty( $group_id ) ) {
// Create the redirection.
$ret = Red_Item::create( [
'url' => $source,
'action_data' => [
'url' => $target,
],
'regex' => 0,
'group_id' => $group_id,
'match_type' => 'url',
'action_type' => 'url',
'action_code' => 301,
] );
}
}
/**
* Set a redirection if any.
* @param object $post
*/
function set_redirection( $post ) {
// Prepare the source.
$source = get_post_meta( $post->ID, '_legacy_path', true );
$source = wp_parse_url( $source, PHP_URL_PATH );
// Prepare the target.
$permalink = get_permalink( $post->ID );
$target = wp_parse_url( $permalink, PHP_URL_PATH );
// Create a redirect.
if ( $source && $target ) {
create_redirect( $source, $target );
}
}
/**
* Register actions to run after each saved post.
* @param integer $id
*/
function redirect_after_saved_post( $id ) {
$post = get_post( $id );
// Handle redirection.
set_redirection( $post );
}
add_action( 'pmxi_saved_post', 'redirect_after_saved_post', 10, 1 );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment