• Hello,

    I created a custom content type called “Event”, like this:

    $args = array(
    	'labels'              => $labels, 
    	'description'         => __( 'Event custom post type', 'bailongos' ), 
    	'public'              => true,
    	'publicly_queryable'  => true,
    	'exclude_from_search' => false,
    	'show_ui'             => true,
    	'query_var'           => true,
    	'menu_position'       => 10, 
    	'menu_icon'           => 'dashicons-calendar', 
    	'rewrite'             => array( 'slug' => 'events/%category%', 'with_front' => true ), 
    	'has_archive'         => 'events/%category%', 
    	'capability_type'     => 'post', 
    	'hierarchical'        => false,
    	'supports'            => array( 'title', 'editor', 'page-attributes', 'thumbnail', 'excerpt' ), 
    	'taxonomies'	      => array( 'category' )
    );
    register_post_type( 'event', $args );

    I’m using the blog categories to group events in cities.

    Note that I have set ‘slug’ => ‘events/%category%’. This allows me to get URLs like this:

    domain.com/events/new-york/event-name/
    domain.com/events/miami/event-name/

    Using a filter:

    add_filter( 'post_type_link', 'base_category_post_link', 1, 3 );
     function base_category_post_link( $post_link, $id = 0 ) {
       $post = get_post($id);  
       $categories = wp_get_object_terms( $post->ID, 'category' ); 
       return str_replace( '%category%', $categories[0]->slug, $post_link );
    }

    It works fine, but the question is, how to create a filter for get_post_type_archive_link(‘event’) so that these URLs lists Events in each city?:

    domain.com/events/new-york/
    domain.com/events/miami/

    Thank you.

Viewing 2 replies - 1 through 2 (of 2 total)
  • It looks to me that you are defining the single and the archive to be the same URL.

    Moderator keesiemeijer

    (@keesiemeijer)

    I’m guessing it’s because you’re on a category archive and the default queried post type for that is post.

    Set the post type to event with the pre_get_posts filter
    https://developer.www.ads-software.com/reference/hooks/pre_get_posts/

    Something like this.

    
    add_action( 'pre_get_posts', 'my_theme_set_post_type_for_category_archives' );
    
    function my_theme_set_post_type_for_category_archives( $query ) {
    	if ( ! is_admin() && $query->is_main_query() && is_category() ) {
    
    		// Change the query for event category archives.
    		$query->set( 'post_type', 'event' );
    	}
    }
    
Viewing 2 replies - 1 through 2 (of 2 total)
  • The topic ‘Custom Post Type Archive with Category’ is closed to new replies.