WordPress开发函数attachment_url_to_postid()

WordPress开发函数attachment_url_to_postid()

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() (https://www.wpzt.net/) WordPress开发教程 第1张
用户贡献的笔记

(由Nilambar Sharma于5年前贡献)

从附件URL获取帖子ID

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

输出:

123

本站所有资源版权均属于原作者所有,这里所提供资源均只能用于参考学习用,请勿直接商用。若由于商用引起版权纠纷,一切责任均由使用者承担。如有需求,建议购买正版!如果源码侵犯了您的利益请留言告知!!
优质资源共享平台-811轩轩资源 » WordPress开发函数attachment_url_to_postid()

发表评论