1
votes

On my WordPress website, I have an archive page e.g.: http://www.example.com/2017. My archive.php file has a query to show posts as well as two custom post types: case-studies and media:

global $wp_query;
        $args = array_merge( $wp_query->query, array( 'post_type' => array('post','case-studies','media'), 'posts_per_page' => 3 ) );
        query_posts( $args );

        while ( have_posts() ) : the_post();

The archive page will only show provided there are posts under post (the standard post type that is included within WordPress) otherwise it will 404, even though there are posts under case-studies and media.

Is there a workaround this?

Here is a link to my archive.php for those who are interested: archive.php

2

2 Answers

0
votes

I've had this problem before. You can include a function in your functions.php file which can redirect the page to archive.php instead of the usual 404. See if this works:

function wpd_date_404_template( $template = '' ){
   global $wp_query;
      if( isset($wp_query->query['year'])
          || isset($wp_query->query['monthnum'])
          || isset($wp_query->query['day']) ){
          $template = locate_template( 'archive.php', false );
      }
   return $template;
}
add_filter( '404_template', 'wpd_date_404_template' );

Credit to Milo at the WordPress StackExchange. See his answer here: Preventing 404 error on empty date archive

0
votes
function wpd_date_404_template( $template = '' ){
    global $wp_query;
    if(
        isset($wp_query->query['year']) ||
        isset($wp_query->query['monthnum']) ||
        isset($wp_query->query['day'])
    ) {
        $template = locate_template( 'archive.php', false );

        if ( isset( $wp_query->query['post_type'] ) ) {
            $located = locate_template( 'archive-' . $wp_query->query['post_type'] . '.php', false );
            $template = $located !== '' ? $located : locate_template( 'archive.php', false );
        }
    }
    return $template;
}
add_filter( '404_template', 'wpd_date_404_template' );

Just used @Dev1997 his answer to solve the issue. With a small improvement to use the specific template for the current (custom) post_type. Maybe it will help someone who is using custom post types.