在WordPress中按文件路径获取附件ID

Xav*_*ver 13 wordpress

我知道文件的路径,我喜欢获取附件ID.

有一个函数wp_get_attachment_url()需要ID来获取URL,但我需要它反向(虽然路径不是URL)

Luc*_*lin 29

更新:因为wp 4.0.0有一个新功能可以完成这项工作.我还没有测试过,但就是这样:

https://developer.wordpress.org/reference/functions/attachment_url_to_postid/


迟回答:到目前为止,我发现的最佳解决方案如下:

http://frankiejarrett.com/get-an-attachment-id-by-url-in-wordpress/

我认为这是最好的有两个原因:

  • 它做了一些完整性检查
  • [重要!]这是与域无关的.这使得安全的网站移动.对我来说,这是一个关键特征.

  • 这应该是公认的答案。WordPress功能中使用的方法比依赖GUID的方法要健壮得多。阅读Pippins页面上的注释以了解限制。 (2认同)

Fra*_*cci 15

我用pippinsplugins.com这个很酷的剪辑

在functions.php文件中添加此函数

// retrieves the attachment ID from the file URL
function pippin_get_image_id($image_url) {
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 
        return $attachment[0]; 
}
Run Code Online (Sandbox Code Playgroud)

然后在您的页面或模板中使用此代码来存储/打印/使用ID:

// set the image url
$image_url = 'http://yoursite.com/wp-content/uploads/2011/02/14/image_name.jpg';

// store the image ID in a var
$image_id = pippin_get_image_id($image_url);

// print the id
echo $image_id;
Run Code Online (Sandbox Code Playgroud)

原帖在这里:https://pippinsplugins.com/retrieve-attachment-id-from-image-url/

希望提供帮助;)弗朗切斯科

  • 往下看这篇文章......不要使用这个功能,使用attachment_url_to_postid()中现在官方的WP功能 (3认同)

小智 6

试试attachment_url_to_postid功能。

$rm_image_id = attachment_url_to_postid( 'http://example.com/wp-content/uploads/2016/05/castle-old.jpg' );
echo $rm_image_id;
Run Code Online (Sandbox Code Playgroud)

更多细节


ran*_*ame 5

对于文件路径,这里的其他任何答案似乎都不能正常或可靠地工作。使用 Pippin 函数的答案也有缺陷,并没有真正按照“WordPress 方式”做事。

此函数将支持路径或 url,并依靠内置的 WordPress 函数attachment_url_to_postid 正确进行最终处理:

/**
 * Find the post ID for a file PATH or URL
 *
 * @param string $path
 *
 * @return int
 */
function find_post_id_from_path( $path ) {
    // detect if is a media resize, and strip resize portion of file name
    if ( preg_match( '/(-\d{1,4}x\d{1,4})\.(jpg|jpeg|png|gif)$/i', $path, $matches ) ) {
        $path = str_ireplace( $matches[1], '', $path );
    }

    // process and include the year / month folders so WP function below finds properly
    if ( preg_match( '/uploads\/(\d{1,4}\/)?(\d{1,2}\/)?(.+)$/i', $path, $matches ) ) {
        unset( $matches[0] );
        $path = implode( '', $matches );
    }

    // at this point, $path contains the year/month/file name (without resize info)

    // call WP native function to find post ID properly
    return attachment_url_to_postid( $path );
}
Run Code Online (Sandbox Code Playgroud)