0

I'm trying to create a menu which loops through the registered custom post types and links to their archive pages. I've been able to get the list of post type names but it is not generating the links. It only outputs a en empty anchor tag wrapped around the post types name.

$args = array( 'public' => true,'_builtin' => false );
$output = 'names';
$operator = 'and';
$post_types = get_post_types( $args, $output, $operator );
foreach ( $post_types  as $post_type ) {
    $link = get_post_type_archive_link($post_type);
    echo '<li><a href="' . $link . '">' . $post_type . '</a></li>';
}

This is my output.

<li><a href="">posttypeA</a></li>
<li><a href="">posttypeB</a></li>
<li><a href="">posttypeC</a></li>

I have archive-posttypeX.php files for each post type.

enter image description here

All of my custom post types are registered similarly to this one:

function post_type_snippets() {
    register_post_type('snippets', array(
        'label'=>'Snippets',
        'menu_icon' => '',
        'labels'=>array(
            'name'=>_x('Snippets', 'post type general name'),
            'singular_name'=>_x('Snippet', 'post type singular name'),
            'add_new'=>_x('Add New', 'snippets'),
            'add_new_item'=>__('Add New Snippet'),
            'edit_item'=>__('Edit Snippet'),
            'new_item'=>__('New Snippet'),
            'view_item'=>__('View Snippet'),
            'search_items'=>__('Search Snippets'),
            'not_found'=>__('No snippets found'),
            'not_found_in_trash'=>__('No snippets found in Trash'),
            'parent_item_colon'=>''),
            'public'=>true,
            'publicly_queryable'=>true,
            'show_ui'=>true,
            'query_var'=>true,
            'rewrite'=>false,
            'capability_type'=>'post',
            'supports'=>array('title','thumbnail','comments','revisions','post-formats'),
            'taxonomies'=>array('category', 'post_tag'),
            'slug'=>'snippets',
            'hierarchical'=>false,
            'menu_position'=>4
        ));
    }
    add_action('init', 'post_type_snippets');
1
  • 1
    You're sure those post types actually have archives? And that $link is not false?
    – Tom J Nowell
    Jun 21, 2014 at 22:54

1 Answer 1

1

As Tom mentioned, $link is false because your post types don't have archives. You need to add the has_archive argument when you register your post types, and set rewrite to true so the rewrite rule for your archive is generated.

1

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.