您可以使用添加自定义url结构add_rewrite_rule
例如,您问题中建议的结构可以通过以下方式实现。。。
add_action( \'init\', function() {
add_rewrite_rule( \'^jobs/([^/]+)/edit/?$\', \'index.php?post_type=jobs&name=$matches[1]\', \'top\' );
} );
所以现在如果你来
https://example.com/jobs/job-title-example/edit/
你应该看到完全一样的东西
https://example.com/jobs/job-title-example/
这是因为我们告诉WordPress通过传递
post_type
和
name
作为查询参数。基本上与访问相同
https://example.com/?post_type=jobs&name=job-title-example
.
然而,基于post类型属性动态构建重写规则可能是一个好主意,例如。。。
add_action( \'init\', function() {
if ( $post_type = get_post_type_object( \'job\' ) ) {
$rewrite = !empty( $post_type->rewrite ) && is_array( $post_type->rewrite ) ? $post_type->rewrite : [];
$with_front = !empty( $rewrite[ \'with_front\' ] ) ? $rewrite[ \'with_front\' ] : false;
$slug = !empty( $rewrite[ \'slug\' ] ) ? $rewrite[ \'slug\' ] : null;
$slug = $slug ?: $post_type->name;
$front = \'\';
if ( $with_front ) {
$permalink_structure = get_option( \'permalink_structure\' );
$front = substr( $permalink_structure, 0, strpos( $permalink_structure, \'%\' ) );
}
$slug = $front ? \'/\' . $slug : $slug;
add_rewrite_rule( \'^\' . $front . $slug . \'/([^/]+)/edit/?$\', \'index.php?post_type=\' . $post_type->name . \'&name=$matches[1]\', \'top\' );
}
}, PHP_INT_MAX );
所以现在如果你改变你的
jobs
post type rewrite属性上述重写规则将自动调整。
始终记住flush your rewrite rules 如果进行任何更改。
我还想添加一个自定义查询变量,以便在模板中使用,例如。。。
add_filter( \'query_vars\', function( $vars ) {
$vars[] = \'frontend_editor\';
return $vars;
} );
并添加到您的重写规则中
&frontend_editor=1
就像这样。。。
add_action( \'init\', function() {
if ( $post_type = get_post_type_object( \'job\' ) ) {
$rewrite = !empty( $post_type->rewrite ) && is_array( $post_type->rewrite ) ? $post_type->rewrite : [];
$with_front = !empty( $rewrite[ \'with_front\' ] ) ? $rewrite[ \'with_front\' ] : false;
$slug = !empty( $rewrite[ \'slug\' ] ) ? $rewrite[ \'slug\' ] : null;
$slug = $slug ?: $post_type->name;
$front = \'\';
if ( $with_front ) {
$permalink_structure = get_option( \'permalink_structure\' );
$front = substr( $permalink_structure, 0, strpos( $permalink_structure, \'%\' ) );
}
$slug = $front ? \'/\' . $slug : $slug;
// We added `frontend_editor` parameter here.
add_rewrite_rule( \'^\' . $front . $slug . \'/([^/]+)/edit/?$\', \'index.php?post_type=\' . $post_type->name . \'&name=$matches[1]&frontend_editor=1\', \'top\' );
}
}, PHP_INT_MAX );
这与访问基本相同:
https://example.com/jobs/job-title-example/?frontend_editor=1
或
https://example.com/?post_type=jobs&name=job-title-example&frontend_editor=1
理论上,您现在应该能够更新模板以显示编辑器,例如。。。
single-jobs.php
<?php get_header(); ?>
<!-- Check if user is authorised to edit current job -->
<?php if ( is_user_logged_in() && (int)get_post_field( \'post_author\', get_the_ID() ) === get_current_user_id() ): ?>
<!-- Check for our edit parameter -->
<?php if ( get_query_var( \'frontend_editor\', false ) ): ?>
<form action="">
...
</form>
<?php endif ?>
<?php endif ?>
<?php get_footer(); ?>
我认为这应该足以为你指明正确的方向。
Please note that none of the above code has been tested!