WordPress.org

Make WordPress Core

Ticket #16830: 16830.2.patch

File 16830.2.patch, 1.1 KB (added by c3mdigital, 5 years ago)

Get post_id if url is attachment image

  • wp-includes/rewrite.php

     
    297297                        return $id;
    298298        }
    299299
     300        // Check if we are working with an image file
     301        $test_url = parse_url( $url );
     302        if ( in_array( $test_url['scheme'], array( 'http', 'https' ) ) && preg_match( "/(?:png|jpg|gif)/ui", $test_url['path'], $matches ) ) {
     303                global $wpdb;
     304
     305                $upload_dir = wp_upload_dir();
     306
     307                // Get the path or the original size image by slicing the widthxheight off the end and adding the extension back
     308                $search_url = preg_replace( '/-\d+x\d+(\.(?:png|jpg|gif))$/i', '.' . $matches[0], $url );
     309
     310                // Get the path to search postmeta for
     311                $search_url = explode( $upload_dir['baseurl'] . '/', $search_url );
     312
     313                $post_id = (int)$wpdb->get_var( $wpdb->prepare( "SELECT post_id FROM $wpdb->postmeta WHERE meta_value LIKE %s", $search_url[1] ) );
     314
     315                if ( $post_id )
     316                        return $post_id;
     317        }
     318
    300319        // Check to see if we are using rewrite rules
    301320        $rewrite = $wp_rewrite->wp_rewrite_rules();
    302321