Attachment.php
989 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?php
namespace WPML\LIB\WP;
use WPML\FP\Logic;
use WPML\FP\Str;
use function WPML\FP\pipe;
class Attachment {
private static $withOutSizeRegEx = '/-\d+[Xx]\d+\./';
/**
* @param string $url
*
* @return int|null The found post ID, or null on failure.
*/
public static function idFromUrl( $url ) {
$removeSize = Str::pregReplace( self::$withOutSizeRegEx, '.' );
return Logic::firstSatisfying(
function ( $id ) { return $id !== 0; },
[
'attachment_url_to_postid',
pipe( $removeSize, 'attachment_url_to_postid' ),
[ self::class, 'idByGuid' ],
pipe( $removeSize, [ self::class, 'idByGuid' ] ),
],
$url
);
}
/**
* @param string $url
*
* @return int The found post ID, or 0 on failure.
*/
public static function idByGuid( $url ) {
global $wpdb;
$attachment = $wpdb->get_col( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE guid='%s'", $url ) );
return $attachment && count( $attachment )
? $attachment[0]
: 0;
}
}