Home / APIs / attachment_url_to_postid() – Tries to convert an attachment URL into a post ID.

You appear to be a bot. Output may be restricted

Description

Tries to convert an attachment URL into a post ID.

Usage

$int = attachment_url_to_postid( $url );

Parameters

$url
( string ) required – The URL to resolve.

Returns

int The found post ID, or 0 on failure.

Source

File name: wordpress/wp-includes/media.php
Lines: 1 to 34 of 34

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 FROM $wpdb->postmeta WHERE meta_key = '_wp_attached_file' AND meta_value = %s",
    $path
  );
  $post_id = $wpdb->get_var( $sql );

  
/**
 * 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 );
}
 

 View on GitHub View on Trac

Published: 10th March 2017 | Last updated: 10th March 2017

Information

Function name: attachment_url_to_postid
Plugin ref: WordPress
Version: 5.0.3
Sourcefile: wp-includes/media.php
File ref: wp-includes/media.php
Deprecated?: No
API Letters: A,P,T,U

  • Plugins
  • Themes
  • Shortcodes
  • APIs
  • Files
  • Hooks
  • Classes
  • Home
  • Sites
  • Sitemap
  • Blog
oik-plugins WordPress a2z
WordPress Dynamic API Reference

Site:  wp-a2z.org
© Copyright oik-plugins 2014-2019. All rights reserved.


Website designed and developed by Herb Miller
Proudly powered by WordPress and oik plugins