Question

Est-il possible que je peux prendre une URL d'une image et trouver la pièce jointe ou l'identifiant poste de cette image dans la base de données?

Voici la situation:

Je suis dans une boucle passe sur tous les « img » balises qui sont entourées par « un » tags dans mon contenu poste. si l'attribut src de la balise « img » ne correspond pas à l'attribut href de l'extérieur « une » étiquette, alors je veux remplacer la balise « img ». En faisant cela, si le « img » qui doit être retiré est dans la galerie, je veux supprimer ce poste, puis mettre mon remplacement « img » à sa place. J'ai essayé d'utiliser une fonction comme ceci:

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;
}

Ceci est apparemment pas juste parce que le guid est ironiquement pas globalement unique. J'ai eu (plus tôt dans le même script) uploadé un fichier avec le même nom (pourquoi? Parce qu'il était de plus haute résolution et je suis en train de remplacer les versions basse résolution de la même image) et bien que wordpress enregistre l'image avec un nom différent dans le répertoire, les années guid ont été fixés à la même chose. (Peut-être un bug).

Y at-il une autre technique que je peux utiliser?

Était-ce utile?

La solution

Massively improved function developed for plugin heavy on images:

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;
    }
}

Autres conseils

All those complex functions can be reduced to one simple function:

attachment_url_to_postid()

You only need to parse the image URL to retrieve the attachment ID:

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

That's all you need.

I modified Rarst's code to allow you to match just the filename instead of the full path. This is helpful if you are about to sideload the image if it does not exist. Currently this only works if file names are unique but I will be adding a hash check later to help with images that have the same filename.

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;
}

Ok I found the answer that no one has on the net I been looking for days now. Keep in mine this only works if your theme or plugin is using the WP_Customize_Image_Control() if you are using WP_Customize_Media_Control() the get_theme_mod() will return the ID and not the url.

For my solution I was using the newer version WP_Customize_Image_Control()

A lot of posts on the forums have the get_attachment_id() which does not work anymore. I used attachment_url_to_postid()

Here is how I was able to do it. Hope this helps someone out there

// This is getting the image / url
$feature1 = get_theme_mod('feature_image_1');

// This is getting the post id
$feature1_id = attachment_url_to_postid($feature1);

// This is getting the alt text from the image that is set in the media area
$image1_alt = get_post_meta( $feature1_id, '_wp_attachment_image_alt', true );

Markup

<a href="<?php echo $feature1_url; ?>"><img class="img-responsive center-block" src="<?php echo $feature1; ?>" alt="<?php echo $image1_alt; ?>"></a>

Here is an alternative solution:

$image_url = get_field('main_image'); // in case of custom field usage
$image_id = attachment_url_to_postid($image_url);

// retrieve the thumbnail size of our image
$image_thumb = wp_get_attachment_image_src($image_id, 'thumbnail');

Since WP 4.0 they introduced a function attachment_url_to_postid() that behaves similarly to your's find_image_post_id()

Please check the this url for your reference.

Licencié sous: CC-BY-SA avec attribution
Non affilié à wordpress.stackexchange
scroll top