In your case, I think the best solution would be to use an HTML Parser , which allows you to find tags as well as with jQuery. However, I do not know how your WP code is structured, nor whether you can include the library (business reasons or whatever), so I'll propose a solution using regular expressions.
Full Disclaimer : Regular expressions are costly and can cause slowness, and the one I wrote can probably be written in a smarter way. I'm also assuming WordPress will always return the links using double quotation marks (i.e., "
and not '
). If tomorrow they decide to change, this solution will fall. Finally, the extraction of the attributes is not elegant, which can cause adverse reactions in more experienced programmers.
The secret of the thing, as far as the world of WP is concerned, is to use the right filters. More specifically, two. Filters serve to invoke methods at certain times, and you can read more about filters here . In this case
add_filter( 'post_thumbnail_html', 'build_custom_url', 10 );
add_filter( 'image_send_to_editor', 'build_custom_url', 10 );
are the necessary filters. All you have to do is to create the build_custom_url()
method to intercept the HTML generated by WP and modify it according to your needs.
Using preg_match_all()
, you can compare the content of a string ($ html) with the RegEx parameters and store them in an array ( $result)
.
preg_match_all('/(width|height|src)=("[^"]*")/i', $html, $result);
print_r($result);
you get (for example):
Array
(
[0] => Array
(
[0] => width="247"
[1] => height="359"
[2] => src="http://localhost:8880/wp/wp-content/uploads/2016/07/pg.png")[1]=>Array([0]=>width[1]=>height[2]=>src)[2]=>Array([0]=>"247"
[1] => "359"
[2] => "http://localhost:8880/wp/wp-content/uploads/2016/07/pg.png"
)
)
I did this test by getting the HTML that WP itself provided through one of these filters. See what you can do now
$width = $result[2][0];
$height = $result[2][1];
$src = substr($result, strrpos($result, '/') + 1); //necessário para extraír o nome do arquivo.
See that it's now simple for you to build (and return) your HTML as you like, based on those parameters. With this, the final code is
add_filter( 'post_thumbnail_html', 'build_custom_url', 10 );
add_filter( 'image_send_to_editor', 'build_custom_url', 10 );
function build_custom_url( $html ) {
preg_match_all('/(width|height|src)=("[^"]*")/i', $html, $result);
$width = $result[2][0];
$height = $result[2][1];
$src = substr($result, strrpos($result, '/') + 1); //necessário para extraír o nome do arquivo.
// Reconstruindo a URL. Aqui você adequa a sua necessidade real
$html = '<img src=http://meusite/'.$width.'x'.$height.'/'.$src;
return $html;
}
Match this code to your need, and add it to your functions.php
file, and everything should work.