Usually I try my best to find answers by searching online or endless experimenting. This time I’m really desperate. I have read many related questions but none has the solution to my problem.
I use ‘get_template_part’ in many other themes and it worked well. This time I don’t know what made the difference.
In my theme there is a registered custom post type event. The url of a post in event would look like example.com/event/wine-tasting.
The problem is: example.com/event/ returns a 404 page instead of lining up all event posts (loop-event.php)
Here is my archive.php:
<?php get_header(); ?>
<?php if ( have_posts() ) the_post();?>
<?php rewind_posts();?>
<?php $post_type = get_post_type();
get_template_part( 'loop', $post_type );?>
<?php get_footer(); ?>
Here is my loop-event.php:
<?php get_header(); ?>
<?php if ( have_posts() ) while ( have_posts() ) : the_post(); ?>
<div class="container">
<?php the_title();?>
<?php the_content();?>
</div>
<?php endwhile; ?>
This is how I register the custom post type ‘event’:
function yd_create_post_type_event()
{
$labels = array(
'name' => __( 'Events','yd'),
'singular_name' => __( 'Event','yd' ),
'add_new' => __('Add New','yd'),
'add_new_item' => __('Add New Event','yd'),
'edit_item' => __('Edit Event','yd'),
'new_item' => __('New Event','yd'),
'view_item' => __('View Event','yd'),
'search_items' => __('Search Event','yd'),
'not_found' => __('No event found','yd'),
'not_found_in_trash' => __('No event found in Trash','yd'),
'parent_item_colon' => ''
);
$args = array(
'labels' => $labels,
'public' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'show_ui' => true,
'show_in_menu' => true,
'show_in_admin_bar' => true,
'query_var' => true,
'capability_type' => 'post',
'hierarchical' => false,
'menu_position' => 5,
'menu_icon' => 0,
'supports' => array('title','editor','excerpt')
);
register_post_type('event',$args);
}
register_taxonomy(
"event-category",
array("event"),
array(
"hierarchical" => true,
"label" => __( "Event Categories",'yd' ),
"singular_label" => __( "Event Category",'yd' ),
"rewrite" => array('slug' => 'event')
)
);
I would really appreciate your help. I have tried everything and I wish it was me who made some dumb mistakes. But I couldn’t work it out so far. Thank you in advance!
When you add a new custom post type in WordPress you need to flush/refresh the permalinks. Please go to:
Settings > Permalinks
and click the Save Changes button (do this twice). This should fix your problem.You need to flush the rewrite rules generated by WordPress.
Create a function as below:
If the custom post type is in your template use:
If the custom post type is in your plugin use:
The other way round is what @Sunny Johal’s answer.