0

Migrating a site to wordpress wanted to redirect old urls

so I made a function that would catch 404, look for a meta value that would match the number in the url to then redirect.

It worked like a charm until a user posted a new article and made it sticky then that query would return the sticky post ignoring meta query

I tried lots of things to correct this that didn't work like 'suppress_filters' => true

in the emergency 'post__not_in' => get_option( 'sticky_posts' ) did the trick but that isn't the way. (if that post I wanted happened to be sticky then it wouldn't find it!)

so then how could I do a WP_Query that gets a post by meta query and that doesn't inject sticky posts ?

add_action( 'template_redirect', 'wpd_do_stuff_on_404' );
function wpd_do_stuff_on_404(){
    if( is_404() ){

        $url = $_SERVER['REQUEST_URI'];

        if (preg_match('/\/(\d+)-[^\/]*$/', $url, $matches) ) {
            // looks like a dc post, lets try to find a post using dc_post_id
            $dc_post_id = intval($matches[1]);
            $args = array(
               'meta_query' => array(
                   array(
                       'key' => 'dc_post_id',
                       'value' => '' . $dc_post_id,
                       'compare' => '=',
                   )
               ),
               'suppress_filters' => true,
               'posts_per_page' => 1,
            );

            $q = new WP_Query($args);

            if ( $q->post_count == 1 && $q->max_num_pages == 1 ) {
                wp_redirect( get_permalink( $q->posts['0']->ID ), 301 );
                exit;
            }
        }
    }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.