add_ping()
云策文档标注
概述
add_ping() 函数用于向指定文章的已 ping URL 列表中添加一个或多个 URL。它接受文章 ID 或对象以及 URI 参数,更新数据库并返回受影响的行数。
关键要点
- 函数参数:$post(必需,文章 ID 或 WP_Post 对象),$uri(必需,字符串或数组形式的 ping URI)。
- 返回值:成功时返回更新的行数(整数),失败时返回 false。
- 内部处理:通过 get_post() 获取文章对象,合并现有 pinged 字段与新的 URI,使用 apply_filters('add_ping', $new) 过滤新 URL,最后通过 $wpdb->update() 更新数据库并清理缓存。
- 版本变化:自 4.7.0 起,$uri 参数支持数组形式。
代码示例
function add_ping( $post, $uri ) {
global $wpdb;
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$pung = trim( $post->pinged );
$pung = preg_split( '/s/', $pung );
if ( is_array( $uri ) ) {
$pung = array_merge( $pung, $uri );
} else {
$pung[] = $uri;
}
$new = implode( "n", $pung );
/**
* Filters the new ping URL to add for the given post.
*
* @since 2.0.0
*
* @param string $new New ping URL to add.
*/
$new = apply_filters( 'add_ping', $new );
$return = $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post->ID ) );
clean_post_cache( $post->ID );
return $return;
}注意事项
- 确保 $post 参数有效,否则函数返回 false。
- 使用 apply_filters('add_ping', $new) 钩子可以自定义新 URL 的过滤逻辑。
- 函数更新后会自动调用 clean_post_cache() 清理文章缓存。
原文内容
Adds a URL to those already pinged.
Parameters
$postint|WP_Postrequired-
Post ID or post object.
$uristring|arrayrequired-
Ping URI or array of URIs.
Source
function add_ping( $post, $uri ) {
global $wpdb;
$post = get_post( $post );
if ( ! $post ) {
return false;
}
$pung = trim( $post->pinged );
$pung = preg_split( '/s/', $pung );
if ( is_array( $uri ) ) {
$pung = array_merge( $pung, $uri );
} else {
$pung[] = $uri;
}
$new = implode( "n", $pung );
/**
* Filters the new ping URL to add for the given post.
*
* @since 2.0.0
*
* @param string $new New ping URL to add.
*/
$new = apply_filters( 'add_ping', $new );
$return = $wpdb->update( $wpdb->posts, array( 'pinged' => $new ), array( 'ID' => $post->ID ) );
clean_post_cache( $post->ID );
return $return;
}
Hooks
- apply_filters( ‘add_ping’, string $new )
-
Filters the new ping URL to add for the given post.