PHP code example of automattic / wpcom-legacy-redirector
1. Go to this page and download the library: Download automattic/wpcom-legacy-redirector library. Choose the download type require. 2. Extract the ZIP file and open the index.php. 3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
automattic / wpcom-legacy-redirector example snippets
use Automattic\LegacyRedirector\Domain\Destination;
use Automattic\LegacyRedirector\Domain\SourceUrl;
use function Automattic\LegacyRedirector\container;
// Get the redirect manager via the helper function (recommended for third-party code)
$manager = container()->manager();
// Add a redirect to an external URL. The destination host must be allowed via
// the allowed_redirect_hosts filter, or this fails with external-url-not-allowed.
$source = SourceUrl::from_string( '/old-page' );
$destination = Destination::from_mixed( 'https://example.com/new-page' );
$result = $manager->create_redirect( $source, $destination );
if ( $result->is_error() ) {
// Handle error: $result->error_code(), $result->error_message()
}
$redirect_id = $result->redirect_id();
// Add a redirect to an internal post by ID
$source = SourceUrl::from_string( '/another-old-page' );
$destination = Destination::from_mixed( $post_id );
$result = $manager->create_redirect( $source, $destination );
// Check if a redirect exists and get its data
$redirect_data = container()->resolver()->get_redirect_data( '/old-page' );
if ( $redirect_data ) {
$redirect_url = $redirect_data['url'];
$redirect_status = $redirect_data['status_code'];
}