I didn't expect this to be difficult but so far have failed at implementing it.
Simply I want to add a class name to the link tag that wraps the img tag when you insert an image into a post using the media library.
I want to turn this
<img src="http://..." alt="..." width="780" height="490" class="alignnone size-full wp-image-12" />
Into this
<img src="http://..." alt="..." width="780" height="490" class="alignnone size-full wp-image-12" />
I can do it simply enough using jQuery, but I'd much prefer to use a wordpress filter or custom function. SO the output in the post includes the class name.
Thanks msbodetti, the solution is as follows.
function add_colorbox_class_to_image_links($html, $attachment_id, $attachment) {
$linkptrn = "/<a[^>]*>/";
$found = preg_match($linkptrn, $html, $a_elem);
// If no link, do nothing
if($found <= 0) return $html;
$a_elem = $a_elem[0];
// Check to see if the link is to an uploaded image
$is_attachment_link = strstr($a_elem, "wp-content/uploads/");
// If link is to external resource, do nothing
if($is_attachment_link === FALSE) return $html;
if(strstr($a_elem, "class=\"") !== FALSE){
// If link already has class defined inject it to attribute
$a_elem_new = str_replace("class=\"", "class=\"fancylink ", $a_elem);
$html = str_replace($a_elem, $a_elem_new, $html);
}else{ // If no class defined, just add class attribute
$html = str_replace("<a ", "<a class=\"fancylink \" data-fancybox-group=\"gallery\" ", $html);
}
return $html;
}
add_filter('image_send_to_editor', 'add_colorbox_class_to_image_links', 10, 3);
Related
I'm using the following code to remove the sizes added by Wordpress to medias' filenames.
function replace_content($content) {
$content = preg_replace('/-([^-]*(\d+)x(\d+)\. ((?:png|jpeg|jpg|gif|bmp)))"/', '.${4}"', $content);
return $content;
}
add_filter('the_content','replace_content');
How to change the regex to apply it only to the href attribute value?
Folowing regex with preg_replace() function
$replaced_content = preg_replace( '#<img[^>]*?src[\s]?=[\s]?[\'"]?([^\'">]*?(https|http|\/\/)[^\'">]*?(png|jpeg|jpg|gif|bmp))[^\'" >]*?)[\'" ][^>]*?>#',
'<img src="$1">', $content );
cleans this awful img tag
<img ttl='Ren src = https://cdn.wpbeginner.com/wp-content/uploads/2015/01/rename-on-save.png' alt="Rena width=520" height="344" wp-image-25391">
to this clean and nice code
<img src="https://cdn.wpbeginner.com/wp-content/uploads/2015/01/rename-on-save.png">
Short story:
I'm trying to get the ID of the Header Image in Wordpress.
All I found was this guide, which dosn't seem to work anymore:http://nickohrn.com/2013/09/get-attachment-id-wordpress-header-image/
Long Story
I'm trying to make the WP Header responsive with an srcset. so I don't want to use this code
<img id="masthead-bg" src="<?php header_image() ?>" alt="">
...but instead want to use the wp_get_attachment_image_srcset function to get the srcset of my header image. Only problem: I need an Image ID for this function -> The ID of my Header image.
<img id="masthead-bg"
src="<?php header_image() ?>"
srcset="<?php echo wp_get_attachment_image_srcset( image_id(), 'thumbnail' ); ?>"
sizes="100vw" alt="">
Any suggestions?
Try this...
// Get the header image data
$data = get_object_vars(get_theme_mod('header_image_data'));
// Now check to see if there is an id
$attachment_id = is_array($data) && isset($data['attachment_id']) ? $data['attachment_id'] : false;
if($attachment_id) {
// Put your image code here, user whatever function to get image by id you need
}
Note: if you use a proper WordPress function to get the image it should add in all the srcset etc stuff for you, to allow for responsive images.
To answer the original question, I've found the simplest way to get the ID while I was filtering the markup that gets outputted by <?php the_header_image_tag(); ?> (introduced in v4.4).
function header_img_markup( $html, $header, $attr) {
// we can get the image ID by passing its src url to this method
$header_img_id = attachment_url_to_postid($attr['src']);
// now we can get its metadata from the db
$header_img_data = wp_get_attachment_metadata($header_img_id);
// now we can use the data
$customSizeWidth = $header_img_data['sizes']['my-custom-size']['width'];
// ...your custom output here...
return $html;
}
add_filter('get_header_image_tag', 'header_img_markup', 20, 3);
Responsive Wordpress Header Image with fallback:
if (get_header_image() !== '') {
$attachment_id = attachment_url_to_postid(get_header_image());
echo wp_get_attachment_image($attachment_id, 'large');
}
if (get_header_image() == '') {
echo '<h1>'.get_bloginfo( "name" ).'</h1>';
echo '<h2>'.get_bloginfo( "description" ).'</h2>';
}
We load html by url. After that creating DOMDocument
libxml_use_internal_errors(true); // disable errors
$oHtml = new DOMDocument();
if (!$oHtml->loadHTML($this->getHtml($aData['href']))) {
return false;
}
Next step is to delete fancybox or other popUp links... In our case image code is
<a onclick="return hs.expand(this)" href="http://domain.com/uploads/09072014106.jpg">
<img title="Some title" alt="Some title" src="http://domain.com/uploads/thumbs/09072014106.jpg">
</a>
And we execute our method for it ...
$this->clearPopUpLink($oHtml); // delete parent <a tag....
Method...
private function clearPopUpLink($oHtml)
{
$aLink = $oHtml->getElementsByTagName('a');
if (!$aLink->length) {
return false;
}
for ($k = 0; $k < $aLink->length; $k++) {
$oLink = $aLink->item($k);
if (strpos($oLink->getAttribute('onclick'), 'return hs.expand(this)') !== false) {
// <a onclick="return hs.expand(this)" href="http://domain.com/uploads/posts/2014-07/1405107411_09072014106.jpg">
// <img title="Some title" alt="Some title" src="http://domain.com/uploads/posts/2014-07/thumbs/1405107411_09072014106.jpg">
// </a>
$oImg = $oLink->firstChild;
$oImg->setAttribute('src', $oLink->getAttribute('href')); // set img proper src
// $oLink->parentNode->removeChild($oLink);
// $oLink->parentNode->replaceChild($oImg, $oLink);
$oLink->parentNode->insertBefore($oImg); // replacing!?!?!?!
// echo $oHtml->ownerDocument->saveHtml($oImg);
}
}
}
Now questions... This code is working BUT I don't get WHY! Why when clearPopUpLink() done with all "images" it has not OLD code with tags? I tried to use (in first time when start investigation) ->insertBefore(), after that ->removeChild(). First is add simple (edited) image BEFOR current image (with <a>), after that delete old node image (with <a>). BUT! It doesn't work, it was doing only on each second (each first was done correctly).
So, let me ask simple question, how to do it in right way? Because I don't think that code below (clearPopUpLink) is correct enough... Please suggest your solutions.
Hmm, I would use the trustee XPath for this and make sure the anchor gets removed; the code you've shown doesn't exactly make that obvious (I haven't tested it).
$xpath = new DOMXPath($doc);
foreach ($xpath->query('//a[contains(#onclick, "return hs.expand(this)")]/img') as $img) {
$anchor = $img->parentNode;
$anchor->parentNode->insertBefore($img, $anchor); // take image out
$anchor->parentNode->removeChild($anchor); // remove empty anchor
}
echo $doc->saveHTML();
$img = '<img src="http://some-img-link" alt="some-img-alt"/>';
$src = preg_match('/<img src=\"(.*?)\">/', $img);
echo $src;
I want to get the src value from the img tag and maybe the alt value
Assuming you are always getting the img html as you shown in the question.
Now in the regular expression you provided its saying that, after the src attribute its given the closing tag for img. But in the string there is an alt attribute also. So you need to care about it also.
/<img src=\"(.*?)\".*\/>/
And if you are going to check alt also then the regular expression.
/<img src=\"(.*?)\"\s*alt=\"(.*?)\"\/>/
Also you are just checking whether its matched or not. If you need to get the matches, you need to provide a third parameter to preg_match which will fill with the matches.
$img = '<img src="http://some-img-link" alt="some-img-alt"/>';
$src = preg_match('/<img src=\"(.*?)\"\s*alt=\"(.*?)\"\/>/', $img, $results);
var_dump($results);
Note : The regex given above is not so generic one, if you could provide the img strings which will occur, will provide more strong regex.
function scrapeImage($text) {
$pattern = '/src=[\'"]?([^\'" >]+)[\'" >]/';
preg_match($pattern, $text, $link);
$link = $link[1];
$link = urldecode($link);
return $link;
}
Tested Code :
$ input=’<img src= ”http://www.site.com/file.png” > ‘;
preg_match(“<img.*?src=[\"\"'](?<url>.*?)[\"\"'].*?>”,$input,$output);
echo $output; // output = http://www.site.com/file/png
How to extract img src, title and alt from html using php?
See the first answer on this post.
You are going to use preg_match, just in a slightly different way.
Try this code:
<?php
$doc = new DOMDocument();
$doc->loadHTML('<img src="" />');
$imageTags = $doc->getElementsByTagName('img');
foreach($imageTags as $tag) {
echo $tag->getAttribute('src');
}
?>
Also you could use this library: SimpleHtmlDom
<?php
$html = new simple_html_dom();
$html->load('<html><body><img src="image/profile.jpg" alt="profile image" /></body></html>');
$imgs = $html->find('img');
foreach($imgs as $img)
print($img->src);
?>
preg_match('/<img src=\("|')([^\"]+)\("|')[^\>]?>/', $img);
You already have good enough responses above, but here is another one code (more universal):
function retrieve_img_src($img) {
if (preg_match('/<img(\s+?)([^>]*?)src=(\"|\')([^>\\3]*?)\\3([^>]*?)>/is', $img, $m) && isset($m[4]))
return $m[4];
return false;
}
You can use JQuery to get src and alt attributes
include jquery in header
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
//HTML
//to get src and alt attributes
<script type='text/javascript'>
// src attribute of first image with id =imgId
var src1= $('#imgId1').attr('src');
var alt1= $('#imgId1').attr('alt');
var src2= $('#imgId2').attr('src');
var alt2= $('#imgId2').attr('alt');
</script>
Here's an example:
I have a DOM object, $content created from this div :
<div class="content">"test" <!-- m -->
<a class="postlink" href="http://imaginethisisareallylongurl.com">http://imagin...longurl.com</a><!-- m -->
<img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" /> "test"
<img src="./images/smilies/icon_e_sad.gif" alt=":(" title="Sad" /> sl
<img src="./images/smilies/icon_e_biggrin.gif" alt=":D" title="Very Happy" />
<img src="./images/smilies/icon_e_sad.gif" alt=":(" title="Sad" /> ok
</div>
And I want to get this output:
"test" http://imaginethisisareallylongurl.com :D :( sl :D :( ok
Image tags within the div are replaced by their alt attributes and URLs are replaced by their full href attributes.
How can I do this?
Edit :
Something like this:
foreach($content->find('a[class=postlink]') as $postlink)
{
$postlink->outertext = $postlink->href;
}
does not work. How can I reference this specific link in the $contents->innertext so that I can modify it?
I should have read the documentation more carefully. You can customize the parsing behaviour like so :
$html->set_callback('custom_parse');
where $html is your original DOMDocument.
function custom_parse($element)
{
if (isset($element->class)){
if($element->class=='postlink'){
$element->outertext = $element->href;
}
}
if (isset($element->innertext)){
$element->innertext = str_replace('<!-- m -->', '', $element->innertext);
}
if (isset($element->outertext)){
if ($element->tag=='img' and isset($element->alt)){
$element->outertext = $element->alt;
}
}
}
then on my content object I can call this:
function parse_content($content)
{
$content = $content->innertext;
$content = strip_tags($content);
$content = html_entity_decode($content);
return $content;
}
No idea if this is the "right" way to do it, but it returns the desired output.