Wordpress CPT附加参数在URL的末尾->404.


Wordpress CPT extra parameter at the end of the URL -> 404

我已经创建了一个自定义帖子类型。集合见下面的代码

`$labels = array(
        'name' => __( 'Collections', 'pcs' ),
        'singular_name' => __( 'Collection', 'pcs' ),
        'add_new' => __( 'New Collection', 'pcs' ),
        'add_new_item' => __( 'New Collection', 'pcs' ),
        'edit_item' => __( 'Edit Collection', 'pcs' ),
        'new_item' => __( 'New Collection', 'pcs' ),
        'view_item' => __( 'View Collection', 'pcs' ),
        'search_items' => __( 'Search Collections', 'pcs' ),
        'not_found' => __( 'No Collection Found', 'pcs' ),
        'not_found_in_trash' => __( 'No Collection Found in Trash', 'pcs' ),
        'parent_item_colon' => __( 'Parent Collection', 'pcs' ),
        'menu_name' => __( 'All Collections', 'pcs' ),
        'filter_items_list' => __( 'Filter collections list', 'pcs' ),
        'items_list_navigation' => __( 'Collections list navigation', 'pcs' ),
        'items_list' => __( 'Collections list', 'pcs' )
    );`
    $args = array(
        'labels' => $labels,
        'hierarchical' => false,
        'supports' => array( 'title' ),
        'public' => true,
        'show_ui' => true,
        'show_in_nav_menus' => false,
        'show_in_menu'  => 'pcs',
        'menu_position' => 1,
        'publicly_queryable' => true,
        'exclude_from_search' => true,
        'has_archive' => false,
        'query_var' => true,
        'can_export' => true,
        'rewrite' => array(
            'slug' => 'collections'),
            'with_front' => false
        ),
        'capability_type' => 'post'
    );

很有魅力。当我进入这个页面:http://www.example.com/collections/slug

它显示了模板多亏了一个钩子:

function xload_template( $single_template ) {
    global $post;
    if ( $post->post_type == 'my_collection' ) {
        if ( file_exists( PATH . 'frontend/template.php' ) ) {
            $single_template = PATH . 'frontend/template.php';
        }
    }
    return $single_template;
}
add_filter( 'single_template', 'xload_template' );
问题是,我想通过url传递一个额外的变量,像这样:http://www.example.com/collection/slug/email_md5

所以我可以使用email_hash作为查看集合的验证。我知道我必须做一个url重写规则,但我不能让它工作。

function add_rewrite_rules($aRules) {
    $aNewRules = array('collections/([^/]+)/([^/]+)/?$' => 'index.php?collections=$matches[1]&email=$matches[2]','top');
    $aRules = $aNewRules + $aRules;
    return $aRules;
}
add_filter('rewrite_rules_array', 'add_rewrite_rules');

FIX:由于我对Wordpress插件中的自定义帖子类型很陌生,我发现如果你知道Wordpress正在做什么,创建重写要容易得多。改变你的wordpress设置->永久链接->普通。通过这种方式,您可以看到如何调用url以及如何在自己的重写中使用它。下面的答案为我解决了这个问题。由于

我认为你正在寻找的是add_rewrite_rule。您可以尝试如下操作:

  function custom_rewrite_rule() {
    add_rewrite_rule('collections/([^/]+)/([^/]+)/?$','index.php?collections=$matches[1]&email=$matches[2]','top');
  }
  add_action('init', 'custom_rewrite_rule', 10, 0);