当前浏览:首页 / WordPress函数 / sanitize_post_field()

sanitize_post_field( string $field, mixed $value, int $post_id, string $context = 'display' ): mixed

基于上下文对post字段进行清理

field 字段more...

kses 清理

postmore...

sanitize 清理more...


描述

可能的上下文值有:“raw”、“edit”、”db“、”display“、”attribute“和”js“。默认情况下使用“display”上下文,attribute和js上下文在调用过滤器时被视为display。


参数

$fieldstring必填
Post对象字段名。
$valuemixed必填
Post对象值。
$post_idint必填
Post ID
$contextstring可选
如何清理字段。可能的值为'raw''edit''db''display''attribute''js'。默认'display'

默认:'display'


返回

mixed 清理后的值。


更多信息

使用apply_filters()

  • 如果$context'edit',字段名前缀为'post_',则调用'edit_{$field}''{$field_no_prefix}_edit_pre',传递$value$post_id
  • 如果$context'db',则传递$value$post_id调用'edit_post_{$field}'
  • 如果$context'db'且字段名前缀为'post_',则调用'pre_{$field}'传递$value
  • 如果$context'db'并且字段名前缀不是'post_',则调用'{$field}_pre'传递$value
  • 如果$context不是'raw''edit''db',并且字段名前缀是'post_',则调用'{$field}'传递$value$post_id$context
  • 如果$context不是'raw''edit''db',并且字段名前缀不是'post_',则调用'post_$field'传递$value

钩子

apply_filters( "edit_{$field}", mixed $value, int $post_id )

过滤要编辑的特定文章字段的值。

apply_filters( "pre_{$field}", mixed $value )

保存前过滤特定文章字段的值。

apply_filters( "{$field_no_prefix}_edit_pre", mixed $value, int $post_id )

过滤要编辑的特定文章字段的值。

apply_filters( "{$field_no_prefix}_save_pre", mixed $value )

保存前过滤特定字段的值。

apply_filters( "{$field}", mixed $value, int $post_id, string $context )

过滤要显示的特定文章字段的值。

apply_filters( "{$field}_pre", mixed $value )

保存前过滤特定文章字段的值。



源码

查看源码 官方文档


更新日志

版本描述
4.4.0sanitize_post()一样,$context默认为'display'
2.3.0开始引入

使用示例

  • 示例1

    为显示进行清理
    为显示清理文章标题:

    $post = get_post( 35 );
    $post_title = sanitize_post_field( 'post_title', $post->post_title, $post->ID, 'display' );
    echo $post_title;
  • 示例2

    为属性清理
    为用作隐藏表单字段值的文章标题进行清理:

    $post = get_post( 543 );
    $post_title = sanitize_post_field( 'post_title', $post->post_title, $post->ID, 'attribute' );
    echo '<input type="hidden" name="post-title" value="' . esc_attr( $post_title ) . '" />';
  • 示例3

    以下是您可以获得的默认文章字段(区分大小写):

      ID
      post_author
      post_date
      post_date_gmt
      post_content
      post_title
      post_excerpt
      post_status
      comment_status
      ping_status
      post_password
      post_name
      to_ping
      pinged
      post_modified
      post_modified_gmt
      post_content_filtered
      post_parent
      guid
      menu_order
      post_type
      post_mime_type
      comment_count
      filter