当前位置:首页>网络教程>WordPress开发函数attachment_url_to_postid()

WordPress开发函数attachment_url_to_postid()

WordPress开发函数attachment_url_to_postid(),尝试将附件URL转换为帖子ID。

WordPress开发函数attachment_url_to_postid(),尝试将附件URL转换为帖子ID。

用法:

attachment_url_to_postid( string $url )

参数:

$url

(string) (必需) 要解析的URL。

返回

(int)找到的post ID,失败时为0。

来源:

文件: wp-includes/media.php

function attachment_url_to_postid( $url ) {

global $wpdb;

$dir = wp_get_upload_dir();

$path = $url;

$site_url = parse_url( $dir[‘url’] );

$image_path = parse_url( $path );

// Force the protocols to match if needed.

if ( isset( $image_path[‘scheme’] ) && ( $image_path[‘scheme’] !== $site_url[‘scheme’] ) ) {

$path = str_replace( $image_path[‘scheme’], $site_url[‘scheme’], $path );

}

if ( 0 === strpos( $path, $dir[‘baseurl’] . ‘/’ ) ) {

$path = substr( $path, strlen( $dir[‘baseurl’] . ‘/’ ) );

}

$sql = $wpdb->prepare(

“SELECT post_id, meta_value FROM $wpdb->postmeta WHERE meta_key = ‘_wp_attached_file’ AND meta_value = %s”,

$path

);

$results = $wpdb->get_results( $sql );

$post_id = null;

if ( $results ) {

// Use the first available result, but prefer a case-sensitive match, if exists.

$post_id = reset( $results )->post_id;

if ( count( $results ) > 1 ) {

foreach ( $results as $result ) {

if ( $path === $result->meta_value ) {

$post_id = $result->post_id;

break;

}

}

}

}

/**

* Filters an attachment ID found by URL.

*

* @since 4.2.0

*

* @param int|null $post_id The post_id (if any) found by the function.

* @param string $url The URL being looked up.

*/

return (int) apply_filters( ‘attachment_url_to_postid’, $post_id, $url );

}

更新日志:
WordPress开发函数attachment_url_to_postid()

用户贡献的笔记

(由Nilambar Sharma于5年前贡献)

从附件URL获取帖子ID

echo attachment_url_to_postid( ‘http://example.com/wp-content/uploads/2016/05/castle-old.jpg’ );

输出:

123

给TA打赏
共{{data.count}}人
人已打赏
网络教程

WordPress功能函数attachment_submit_meta_box()

2022-7-15 17:29:20

网络教程

WordPress功能函数background_image()

2022-7-15 17:29:38

0 条回复 A文章作者 M管理员
    暂无讨论,说说你的看法吧
个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索