問題描述

有什麼辦法可以拿到圖像的 URL,並在數據庫中找到該圖像的附件或帖子 ID?

這是情況:

我正在循環瀏覽我的帖子內容中包含 「a」 標籤的所有 「img」 標籤。如果’img’ 標籤的 src 屬性與外部’a’ 標籤的 href 屬性不匹配,那麼我想替換’img’ 標籤。在這樣做時,如果要刪除的 「img」 在畫廊中,我想刪除該帖子,然後將替換’img’ 放在其位置。我嘗試使用這樣的功能:

function find_image_post_id($url) {
  global $wpdb;
  $postid = $wpdb->get_var($wpdb->prepare("SELECT DISTINCT ID FROM $wpdb->posts WHERE guid='$url'"));
  if ($postid) {
    return $postid;
  }
  return false;
}

這顯然是不正確的,因為指南是諷刺的不是全球唯一的。我已經 (早在同一個腳本) 上傳了一個同名的文件 (為什麼?因為它是更高的分辨率,我正在嘗試替換相同圖像的低分辨率版本),雖然 wordpress 將保存圖像與不同的名稱該目錄中,guid 的設置是相同的。 (可能是一個錯誤) 。

是否有其他技術可以使用?

最佳解決方案

大量改進的功能開發為插件重的圖像:

if ( ! function_exists( 'get_attachment_id' ) ) {
    /**
     * Get the Attachment ID for a given image URL.
     *
     * @link   http://wordpress.stackexchange.com/a/7094
     *
     * @param  string $url
     *
     * @return boolean|integer
     */
    function get_attachment_id( $url ) {

        $dir = wp_upload_dir();

        // baseurl never has a trailing slash
        if ( false === strpos( $url, $dir['baseurl'] . '/' ) ) {
            // URL points to a place outside of upload directory
            return false;
        }

        $file  = basename( $url );
        $query = array(
            'post_type'  => 'attachment',
            'fields'     => 'ids',
            'meta_query' => array(
                array(
                    'key'     => '_wp_attached_file',
                    'value'   => $file,
                    'compare' => 'LIKE',
                ),
            )
        );

        // query attachments
        $ids = get_posts( $query );

        if ( ! empty( $ids ) ) {

            foreach ( $ids as $id ) {

                // first entry of returned array is the URL
                if ( $url === array_shift( wp_get_attachment_image_src( $id, 'full' ) ) )
                    return $id;
            }
        }

        $query['meta_query'][0]['key'] = '_wp_attachment_metadata';

        // query attachments again
        $ids = get_posts( $query );

        if ( empty( $ids) )
            return false;

        foreach ( $ids as $id ) {

            $meta = wp_get_attachment_metadata( $id );

            foreach ( $meta['sizes'] as $size => $values ) {

                if ( $values['file'] === $file && $url === array_shift( wp_get_attachment_image_src( $id, $size ) ) )
                    return $id;
            }
        }

        return false;
    }
}

次佳解決方案

所有這些複雜的功能可以簡化成一個簡單的功能:

 attachment_url_to_postid()

您只需解析圖像 URL 即可檢索附件 ID:

$attachment_id = attachment_url_to_postid( $image_url );
echo $attachment_id;

這就是你需要的。

第三種解決方案

我修改了 Rarst 的代碼,讓您只匹配文件名而不是完整的路徑。如果您要卸載圖像,如果它不存在,這是有幫助的。目前,這隻有在文件名是唯一的時候才有用,但是我稍後會添加哈希檢查來幫助具有相同文件名的圖像。

function get_attachment_id( $url, $ignore_path = false ) {

if ( ! $ignore_path ) {

    $dir = wp_upload_dir();
    $dir = trailingslashit($dir['baseurl']);

    if( false === strpos( $url, $dir ) )
        return false;
}

$file = basename($url);

$query = array(
    'post_type' => 'attachment',
    'fields' => 'ids',
    'meta_query' => array(
        array(
            'key'     => '_wp_attached_file',
            'value'   => $file,
            'compare' => 'LIKE',
        )
    )
);

$ids = get_posts( $query );

foreach( $ids as $id ) {
    $match = array_shift( wp_get_attachment_image_src($id, 'full') );
    if( $url == $match || ( $ignore_path && strstr( $match, $file ) ) )
        return $id;
}

$query['meta_query'][0]['key'] = '_wp_attachment_metadata';
$ids = get_posts( $query );

foreach( $ids as $id ) {

    $meta = wp_get_attachment_metadata($id);

    foreach( $meta['sizes'] as $size => $values ) {
        if( $values['file'] == $file && ( $ignore_path || $url == array_shift( wp_get_attachment_image_src($id, $size) ) ) )
            return $id;
    }
}

return false;
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。