【问题标题】:Make Custom Post Type Child of Page使自定义帖子类型成为页面的子级
【发布时间】:2019-05-03 00:04:13
【问题描述】:

我需要一个帖子类型作为页面的(实际上基本上是任何其他帖子类型及其本身),并且它也必须适用于 CPT 的分类法。

一般的想法是在cpt_parent_page 下保存我的选项中的动态父页面。目前,我的蛞蝓运行良好;在管理员中,在我的 CPT 分类下,我有正确的链接。但是,当我查看分类时,我得到了 404。我很确定我只是忘记了一件非常小的事情,但我需要记住所说的事情。

$cpt = 'book';
$cpt_singular = 'Book';
$cpt_plurial = 'Books';

/*
 * Register CPT
 */
$labels = array(
    'add_new_item' => 'Add New '.$cpt_singular,
    'all_items' => 'All '.$cpt_plurial,
    'edit_item' => 'Edit '.$cpt_singular,
    'name' => $cpt_singular,
    'name_admin_bar' => $cpt_singular,
    'new_item' => 'New '.$cpt_singular,
    'not_found' => 'No '.$cpt_singular.' found',
    'not_found_in_trash' => 'No '.$cpt_plurial.' found in Trash',
    'parent_item_colon' => 'Parent '.$cpt_singular,
    'search_items' => 'Search '.$cpt_plurial,
    'view_item' => 'View '.$cpt_singular,
    'view_items' => 'View '.$cpt_plurial,
);
$args = array(
    'labels' => $labels,
    'public' => true,
    'publicly_queryable' => true,
    'show_in_menu' => true,
    'show_in_admin_bar' => true,
    'can_export' => true,
    'has_archive' => false,
    'hierarchical' => true,
    'menu_position' => null,
    'supports' => array( 'editor', 'thumbnail', 'title' ),
    'rewrite' => array(
        'slug' => get_permalink( get_option('cpt_parent_page') ),
        'with_front' => false
    ),
);
register_post_type($cpt, $args);

/*
 * Register taxonomy
 */
register_taxonomy(
    $cpt_name, // Taxonomy name
    $cpt, // Associate taxonomy to this post type
    array(
        'hierarchical' => true,
        'label' => $tax_name,
        'query_var' => true,
        'rewrite' => array(
        'slug' => get_permalink( get_option('cpt_parent_page') ),
            'with_front' => false
        ),
        'show_in_quick_edit' => true,
        'show_admin_column' => true,
    )
);

【问题讨论】:

  • 我假设 $cpt_name 是在代码中的某处定义的,但你有一个错字(在问题中) - $cpy 我认为应该是 $cptcpt_parent_page 的示例值是什么?
  • @SallyCJ 感谢您抽出宝贵时间,并注意到我已更正的错字。 `` 的示例值为255。但是,如您所见,我使用 get_permalink() 来获取我的 URL 重写的格式。
  • 抱歉,我没有真正注意到代码中的get_permalink()。但是您不应该使用它..请检查我的答案并告诉我。 (如果您不想要/p/t ..,我们可以尝试一下。)

标签: php wordpress custom-post-type


【解决方案1】:

您收到错误404 很可能是因为您在更改选项后没有刷新重写规则。但即使不是这种情况,请确保在更改选项后始终刷新规则——只需访问永久链接设置页面。

除此之外,你不应该使用get_permalink(),或者你应该使用帖子slug而不是它的永久链接URL。所以进行以下更改:

// Change this:
get_permalink( get_option('cpt_parent_page') )

// to this FOR THE POST TYPE:
get_post_field( 'post_name', get_option('cpt_parent_page') ) . '/p'

// or this FOR THE TAXONOMY:
get_post_field( 'post_name', get_option('cpt_parent_page') ) . '/t'

应该可以;但是,/p/t 是必要的,以便 WordPress 知道请求是针对帖子还是术语(在分类中)——如果没有 /p/t,重写规则将发生冲突并可能失败(例如,术语请求被混淆为帖子或子页面请求)。

【讨论】:

  • PS:它确实不是必须是字母pt - 它可以是您喜欢的任何唯一文本
  • 感谢您的帮助,get_post_field 方法确实起到了作用,因为我现在可以使用我的 URL 结构和分类模板。
猜你喜欢
  • 2017-07-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-17
  • 1970-01-01
  • 2017-11-21
  • 2019-01-03
相关资源
最近更新 更多