4
votes

I am trying to setup a custom post type plugin in wordpress that allows for selecting a page that will produce the posts list in the same fashion as setting the "Posts page" setting so that when the url of the page is accessed it produces the custom post types archive page instead of the page content.

I have option for selecting the page to use setup and it uses the pages slug as the rewrite slug for the custom post type, I just can't figure out how to get it to display the archive instead of the page content.

2

2 Answers

0
votes

Based on the WordPress Template Hierarchy, assuming you're using a custom post of type Foo, you want to put your archive code in archive-foo.php.

0
votes

I have a working solution, there is probably a better solution but this work for top level pages. Basically I check to see if the slug for the page has changed and flush the rewrite rules if it has.

add_action( 'init', 'faqmgr_create_post_type' );
function faqmgr_create_post_type() {
    $options=get_option('faqmgr_options', array('faq_page'=>0, 'faq_slug'=>'faq'));
    $updated=false;
    $tpost=get_post( $options['faq_page'], OBJECT );
    if(is_null($tpost)){
        $options=array('faq_page'=>0, 'faq_slug'=>'faq');
    $updated=true;
        update_option('faqmgr_options', $options);
    }else{
        if($options['faq_slug']!=$tpost->post_name){
            $options['faq_slug']=$tpost->post_name;
            $updated=true;
        }
    }
    register_post_type( 'faq',
        array(
            'labels' => array(
                'name' => __( 'FAQs' ),
                'singular_name' => __( 'FAQ' ),
                'add_new_item' => __( 'Add FAQ' ),
                'edit_item' => __( 'Edit FAQ' ),
                'new_item' => __( 'New FAQ' ),
                'view_item' => __( 'View FAQ' ),
                'search_items' => __( 'Search FAQs' ) 
            ),
        'public' => true,
        'exclude_from_search'=>true,
        'has_archive' => true,
        'rewrite' => array(
            'slug' => $options['faq_slug'],
            'with_front' => false
        ),
        'supports' => array(
            'title',
            'editor',
            'thumbnail'
        )
        )
    );

    if($updated=true;){
        flush_rewrite_rules( false );
    }

}