Created
April 14, 2021 01:07
-
-
Save webdevsuperfast/4b76d28422f420bd731a952b1b4b113c to your computer and use it in GitHub Desktop.
Redirect posts within a date range to new URL
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 | |
/** | |
* Redirect posts within a date range to new URL with wp_redirect() | |
* @url https://paulund.co.uk/get-posts-between-certain-dates-wordpress-rest-api | |
*/ | |
add_action( 'template_redirect', function() { | |
$args = array( | |
'date_query' => array( | |
array( | |
'after' => 'November 1, 2020', | |
'before' => array( | |
'year' => 2021, | |
'month' => 3, | |
'day' => 19 | |
), | |
'inclusive' => true | |
) | |
), | |
'posts_per_page' => -1 | |
); | |
$query = new WP_Query( $args ); | |
if ( $query->have_posts() ) : | |
while ( $query->have_posts() ) : $query->the_post(); | |
$slug = get_post_field( 'post_name', get_the_ID() ); | |
$url = 'https://example.com'; // Replace this to new URL | |
if ( is_single( get_the_ID() ) ) : | |
wp_redirect( $url . '/' . $slug, 301 ); | |
endif; | |
endwhile; | |
endif; | |
} ); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment