问题描述

这似乎是愚蠢的问题。但是,我不能弄清楚:()

我需要在家里显示按钮到自定义 post_type 的存档 URL(archive- {post_type} .php) 。我怎么做?

最佳解决方案

嗨 @Silent:

事实证明 WordPress 3.1 中有一个功能完全符合你的要求,它被命名为 get_post_type_archive_link(); 以下是您称之为 (假定自定义帖子类型名为'product'):

<a href="<?php%20echo%20get_post_type_archive_link('product');%20?>">Products</a>

以下是我之前的答案,之前我发现 WordPress 确实有一个功能 built-in 为这种用例。

以前的答案:

除非我忽略了 WordPress 3.1 的核心源代码中的某些东西,我想你正在寻找一个像 get_archive_link()这样的函数,你可能会这样称呼 (假定自定义后缀类型为'product'):

<a href="<?php%20echo%20get_archive_link('product');%20?>">Products</a>

这里是您可以将其放入主题的 function.php 文件或.php 文件中的源代码,用于您可能正在编写的插件:

if (!function_exists('get_archive_link')) {
  function get_archive_link( $post_type ) {
    global $wp_post_types;
    $archive_link = false;
    if (isset($wp_post_types[$post_type])) {
      $wp_post_type = $wp_post_types[$post_type];
      if ($wp_post_type->publicly_queryable)
        if ($wp_post_type->has_archive && $wp_post_type->has_archive!==true)
          $slug = $wp_post_type->has_archive;
        else if (isset($wp_post_type->rewrite['slug']))
          $slug = $wp_post_type->rewrite['slug'];
        else
          $slug = $post_type;
      $archive_link = get_option( 'siteurl' ) . "/{$slug}/";
    }
    return apply_filters( 'archive_link', $archive_link, $post_type );
  }
}

我实际上是在周末的这个确切的逻辑上,尽管我还没有百分之百地肯定,所有的 use-cases 逻辑的顺序是一般正确的,WordPress 可能会看到,虽然它可能适用于任何特定的网站。

这也是一个很好的事情,建议通过 trac 添加到 WordPress,我想我晚上会做。

次佳解决方案

当您注册帖子类型时,您可以使用”has_archive” 参数传递一个字符串作为 slug,并确保您还将重写设置为 true 或数组,但不是 false,那么您的 CPT 归档 URL 将是 http://www.YOURDOMAIN.com/has_archive_slug 例如

如果你设置在你的 register_post_type 例如:

$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_ui' => true,
    'show_in_menu' => true,
    'query_var' => true,
    'rewrite' => 'product',
    'capability_type' => 'post',
    'has_archive' => 'products',
    'hierarchical' => false,
    'menu_position' => null,
    'supports' => array('title','editor','author','thumbnail','excerpt','comments')
  );
 register_post_type('product',$args);

那么你的单个 URL 是:http://www.YOURDOMAIN.com/product/postName,你的归档 URL 是:http://www.YOURDOMAIN.com/products/

参考文献

注:本文内容整合自 Google/Baidu/Bing 辅助翻译的英文资料结果。如果您对结果不满意,可以加入我们改善翻译效果:薇晓朵技术论坛。