自定义发布类型重写-找不到页面

时间:2016-09-01 作者:j.grima

我正在测试重写自定义帖子类型的永久链接。自定义帖子类型用于事件,其中一个元字段是事件的年份。

我希望将活动的年份作为URL的一部分,因此如果我有一个标题为“会议1”的活动,年份为“2011”,URL如下:http://_____.com/events/2011/conference-1

我跟踪了这个tutorial 能够重写自定义帖子的永久链接。一切似乎都正常,但具有新URL的页面总是返回未找到的页面。我多次尝试保存Permanlinks设置并刷新重写规则,但似乎没有任何效果。

转到位于的页面http://_____.com/?event=conference-1 工作,但不是“新”URL。

这是我迄今为止重写permalink的代码:

function custom_post_event() {

    // ...

    $args = array(
        \'labels\' => $labels,
        \'description\' => \'Holds our Events and Event specific data\',
        \'public\' => true,
        \'menu_position\' => 5,
        \'supports\' => array(\'title\', \'editor\', \'page-attributes\', \'thumbnail\'),
        \'has_archive\' => false,
        \'publicly_queryable\' => true,
        \'query_var\' => true,
        \'rewrite\' => false
    );

    register_post_type(\'event\', $args);

    // add to our plugin init function
    global $wp_rewrite;

    $event_structure = \'/events/%event_year%/%event%\';
    $wp_rewrite->add_rewrite_tag("%event%", \'([^/]+)\', "event=");
    $wp_rewrite->add_permastruct(\'event\', $event_structure, false);
}
add_action(\'init\', \'custom_post_event\');

// Add filter to plugin init function
add_filter(\'post_type_link\', \'event_permalink\', 10, 3);   

function event_permalink($permalink, $post_id, $leavename) {
    $post = get_post($post_id);
    $rewritecode = array(
        \'%event_year%\',
        $leavename? \'\' : \'%postname%\'
    );

    if ( \'\' != $permalink && !in_array($post->post_status, array(\'draft\', \'pending\', \'auto-draft\')) ) {
        $event_year = get_post_meta( $post->ID, \'event_post_year\', true );

        $rewritereplace = array(
            $event_year,
            $post->post_name
        );

        $permalink = str_replace($rewritecode, $rewritereplace, $permalink);
    }

    return $permalink;
}

1 个回复
SO网友:The J

如果您在插件中使用此功能,请从codex:

要在激活插件时让permalinks工作,请使用以下示例,注意如何在register_activation_hook回调中调用my_cpt_init:

add_action( \'init\', \'my_cpt_init\' );
function my_cpt_init() {
    register_post_type( ... );
}

function my_rewrite_flush() {
    // First, we "add" the custom post type via the above written function.
    // Note: "add" is written with quotes, as CPTs don\'t get added to the DB,
    // They are only referenced in the post_type column with a post entry, 
    // when you add a post of this CPT.
    my_cpt_init();

    // ATTENTION: This is *only* done during plugin activation hook in this example!
    // You should *NEVER EVER* do this on every page load!!
    flush_rewrite_rules();
}
register_activation_hook( __FILE__, \'my_rewrite_flush\' );
我会把

// add to our plugin init function
global $wp_rewrite;

$event_structure = \'/events/%event_year%/%event%\';
$wp_rewrite->add_rewrite_tag("%event%", \'([^/]+)\', "event=");
$wp_rewrite->add_permastruct(\'event\', $event_structure, false);
在一个单独的行动比后注册,但之前冲洗。

return $permalink 输出是否正确?

相关推荐