php - 如何以编程方式更改 Wordpress 的默认帖子永久链接?

标签 php wordpress wordpress-theming permalinks custom-wordpress-pages

在 Wordpress 的后端,我使用默认的 http://localhost/sitename/example-post/创建永久链接的值(value)。

对于自定义帖子类型,我以这种方式定义了自定义 slug,这里是 services例如:

register_post_type( 'service',
    array(
        'labels'      => array(
            'name'          => __( 'Services' ),
            'singular_name' => __( 'Service' )
        ),
        'public'      => true,
        'has_archive' => true,
        'rewrite'     => array(
            'slug'       => 'services',
            'with_front' => true
        ),
        'supports'    => array(
            'title',
            'editor',
            'excerpt',
            'thumbnail'
        ),
        'taxonomies'  => array( 'category' ),
    )
);

它创建 服务/职位名称 .

我还使用这个钩子(Hook)来创建一个自定义页面来创建一个自定义页面永久链接:
function custom_base_rules() {
    global $wp_rewrite;

    $wp_rewrite->page_structure = $wp_rewrite->root . '/page/%pagename%/';
}

add_action( 'init', 'custom_base_rules' );

它创建 页面/帖子名称

现在我唯一需要做的就是为普通的 Wordpress 创建另一个自定义永久链接路径。帖子 .

所以结果世界是 post 的帖子类型:

职位/职位名称

我不能为此使用 backed,因为我已经定义了处理永久链接的默认方式。我已经设法重写了自定义帖子类型和页面的路径......

如何改写正常的post以编程方式在 Wordpress 中发布类型永久链接路径?

最佳答案

您需要分两步完成。

首先使用 'with_front' => true 启用重写用于构建后注册

add_filter(
    'register_post_type_args',
    function ($args, $post_type) {
        if ($post_type !== 'post') {
            return $args;
        }

        $args['rewrite'] = [
            'slug' => 'posts',
            'with_front' => true,
        ];

        return $args;
    },
    10,
    2
);

这样的网址如 http://foo.example/posts/a-title工作,但生成的链接现在是错误的。

可以通过强制构建帖子的自定义永久链接结构来修复链接

add_filter(
    'pre_post_link',
    function ($permalink, $post) {
        if ($post->post_type !== 'post') {
            return $permalink;
        }

        return '/posts/%postname%/';
    },
    10,
    2
);

https://github.com/WordPress/WordPress/blob/d46f9b4fb8fdf64e02a4a995c0c2ce9f014b9cb7/wp-includes/link-template.php#L166

关于php - 如何以编程方式更改 Wordpress 的默认帖子永久链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52427918/

相关文章:

css - 如何在 wordpress 中使用 add_editor_style() 包含绝对 css 路径

wordpress - 如何为小部件提供单独的 ID 或类?

php - 在 codeigniter 中连接 3 个表

php - 如何使用不同的 css 和 js 创建一个 php header ?

wordpress - Wordpress 中的 Google Analytics - 跨域跟踪

jquery - 如何在 WordPress 站点中制作自定义宽子菜单

php - 如何从 sfUser 获取 id?

php - 我该如何调试这个 php/MySQL 错误?

php - Wordpress 选项页面中动态生成的下拉列表

css - 尝试在 WP 中正确注册和排队样式表,但没有呈现任何内容