Skip to content

Instantly share code, notes, and snippets.

@webdevsuperfast
Created April 14, 2021 01:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save webdevsuperfast/4b76d28422f420bd731a952b1b4b113c to your computer and use it in GitHub Desktop.
Save webdevsuperfast/4b76d28422f420bd731a952b1b4b113c to your computer and use it in GitHub Desktop.
Redirect posts within a date range to new URL
<?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