钩子文档

pre_post_link

💡 云策文档标注

概述

pre_post_link 是一个 WordPress 过滤器,用于在令牌替换之前修改文章的固定链接结构。它仅适用于 post_type 为 'post' 的文章,允许开发者自定义永久链接格式。

关键要点

  • 过滤器名称:pre_post_link,在令牌替换前应用,用于调整固定链接结构。
  • 适用对象:仅对 post_type 为 'post' 的文章生效,不影响其他自定义文章类型。
  • 参数说明:接受 $permalink(固定链接结构)、$post(文章对象)和 $leavename(是否保留文章名称)三个参数。
  • 核心用途:通过 add_filter 添加自定义函数来修改链接,例如添加后缀或调整令牌顺序。
  • 移除方法:使用 remove_filter 可以取消已添加的过滤器,恢复默认行为。

代码示例

function wpdocs_modify_pre_post_link_defaults( $permalink, $post ) {
    // 检查文章类型是否为 'post'
    if ( 'post' === $post->post_type ) {
        // 在 %postname% 后添加 '-custom' 后缀
        $permalink = str_replace( '%postname%', '%postname%-custom', $permalink );
    }

    return $permalink;
}

add_filter( 'pre_post_link', 'wpdocs_modify_pre_post_link_defaults', 10, 2 );

注意事项

  • 确保在函数中检查 $post->post_type 以仅针对 'post' 类型应用修改,避免影响其他内容。
  • 使用 remove_filter 时需匹配相同的优先级和参数数量,以确保正确移除过滤器。

📄 原文内容

Filters the permalink structure for a post before token replacement occurs.

Description

Only applies to posts with post_type of ‘post’.

Parameters

$permalinkstring
The site’s permalink structure.
$postWP_Post
The post in question.
$leavenamebool
Whether to keep the post name.

Source

$permalink = apply_filters( 'pre_post_link', $permalink, $post, $leavename );

Changelog

Version Description
3.0.0 Introduced.

User Contributed Notes

  1. Skip to note 2 content

    Modifying Pre-Post Links in WordPress
    we will learn how to modify the default permalink structure of your WordPress posts using the pre_post_link filter. We will write a function to customize the permalink and then add and remove this filter.

    Step 1: Add the Filter

    function wpdocs_modify_pre_post_link_defaults( $permalink, $post ) {
        // Check if the post type is 'post'
        if ( 'post' === $post->post_type ) {
            // Append '-custom' to the permalink
            $permalink = str_replace( '%postname%', '%postname%-custom', $permalink );
        }
    
        return $permalink;
    }
    
    add_filter( 'pre_post_link', 'wpdocs_modify_pre_post_link_defaults', 10, 2 );

    Step 2: Remove the Filter

    remove_filter( 'pre_post_link', 'wpdocs_modify_pre_post_link_defaults' );