自定义帖子类型的wordpress存档模板

时间:2013-11-12 14:00:46

标签: wordpress

我在WordPress 3.6.1上有一个网站,我使用代码为食谱创建了一个自定义帖子类型:

add_action('init', 'register_cpt_my_recipes');

function register_cpt_my_recipes() {
    $args = array(
        'hierarchical' => false,
        'supports' => array('title', 'editor', 'custom-fields' ,'tag' , 'excerpt', 'thumbnail'),
        'public' => true,
        'show_ui' => true,
        'show_in_menu' => true,
        'menu_position' => 5,
        'show_in_nav_menus' => false,
        'publicly_queryable' => true,
        'exclude_from_search' => false,
        'has_archive' => true,
        'query_var' => true,
        'can_export' => true,
        /* Not necessary but added as a solution */
        'rewrite'=> array('slug' => 'my_recipes', 'with_front' => true),
        'capability_type' => 'post'
    );
    register_post_type('my_recipes', $args);
    /* Not necessary but added as a solution */
    flush_rewrite_rules(false);
}

我创建了archive-my_recipes.php自定义模板文件,但每当我导航到mysite / my_recipes /我最终得到来自archive.php的代码,我的所有帖子不仅仅是我的自定义帖子类型的帖子。我尝试过taxonomy-my_recipes.php但也没用。

此外,单一my_recipes.php工作正常。 我的自定义帖子类型的帖子显示在主循环上。

我在wordpress文档网站herehere上阅读了该主题 我也在这里阅读类似问题的答案,但还没有有效的解决方案。

还尝试了解决方案here

function namespace_add_custom_types( $query ) {
  if( is_category() || is_tag() && empty( $query->query_vars['suppress_filters'] ) ) {
    $query->set( 'post_type', array(
     'post', 'your-custom-post-type-here'
        ));
      return $query;
    }
}
add_filter( 'pre_get_posts', 'namespace_add_custom_types' );

2 个答案:

答案 0 :(得分:0)

我觉得您的问题与此custom post types and template names

类似

您可能需要更新永久链接设置

答案 1 :(得分:0)

好的,我发现这部分会导致问题

add_action( 'pre_get_posts', 'add_my_post_types_to_query' );

function add_my_post_types_to_query( $query ) {
    if ( !is_admin() && $query->is_main_query() )
        $query->set( 'post_type', array( 'post', 'page', 'recipes' ) );
    return $query;
}

当我删除它时,存档页面正常工作但是现在我必须编辑其他模板以通过提供查询参数来获取自定义帖子。

如果有人问您如何在模板中使用它而不是默认循环

<?php $loop = new WP_Query( array( 'post_type' => 'recipes', 'posts_per_page' => 100 ) ); ?>

       <?php while ( $loop->have_posts() ) : $loop->the_post(); ?>



        <ul>
            <li>

                <a href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>

                <h4><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h4>

            </li>
        </ul>



            <?php endwhile; // end of the loop. ?>
相关问题