I've got the following code, it spits out the first image of each post, on WordPress:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
}
echo "<img src=" . $first_img . ">";
}
However, I also need to catch the first iframe, and echo whichever is first. I'm not experienced with regular expressions, so any help or resources would be great :)
Use the |(or) operator. Replace the img with (img|iframe).
Related
I would like to use alt attribute tags with image on the main site.
I use code that calls for pictures on my index page from latest wordpress posts. I use this code for index.php:
<img src="<?php echo catch_that_image() ?>" width="250" alt="">
The code in the functions.php file for catch that image is:
function catch_that_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
What I want to achieve is to get the alt tag from that post, not only the image. Actually some kind of "catch that alt". The new code in index.php would be
<img src="<?php echo catch_that_image() ?>" width="250" alt="text from wordpress post">
How can can I add anything to functions.php to get that alt text together?
The purpose is that google often search for images and doesn't find alt tags on the main site but only on individual wordpress posts.
you can add the following code in your functions.php to enable that.
function add_img_title($attr, $attachment = null) {
$img_title = trim(strip_tags($attachment->post_title));
$attr['alt'] = $img_title;
$attr['title'] = $img_title;
return $attr;
}
add_filter('wp_get_attachment_image_attributes', 'add_img_title', 10, 2);
I have a "get first image script" I am using that is all over the internet but am getting the error:
PHP Notice: Undefined offset: 0
the script is:
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i',$post->post_content, $matches);
$first_img = $matches [1] [0];
return $first_img;
}
can this be fixed?
Based on your regex this could happen if the <img> tag has no src attribute or if there are no <img> tags at all.
As others have suggested you could fix this by checking $matches first, but I'd like to suggest an alternate approach that may be more robust for parsing html in php, since using regex to do this is discouraged.
function get_first_image() {
global $post;
$first_img = '';
$dom = new DOMDocument();
$dom->loadHtml($post->post_content);
foreach ($dom->getElementsByTagName('img') as $img) {
if ($img->hasAttribute('src')) {
$first_image = $img->getAttribute('src');
break;
}
}
return $first_img;
}
The above function uses php's DOMDocument Class to iterate over <img> tags and get the src attribute if it exists. (Note: I removed the ob_start() and ob_end_clean() functions from your code because I don't understand what purpose they were serving)
You can do this:
$first_img = isset($matches[1][0]) ? $matches[1][0] : false;
Which will, then, return false if the first position in this two dimension array would not exist.
Before operator:
$first_img = $matches [1] [0];
insert the line:
var_dump($matches);
Make sure, that $matches is an array, and has two dimensions.
I am working on some code and I've done enough work to get something going. I want to replace a image url(s) and web links within that body of text.
E.G "This is my text with http://www.google.com and some image http://www.somewebimage.png"
Replace to "This is my text with http://www.google.com and some image <img src="http://www.somewebimage.png">"
My hack gets me to replace the url(s) or the img links but not both..one is over written because of the order
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";
$reg_exImg = '/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?(jpg|png|gif|jpeg)/';
$post = "This is my text with http://www.google.com and some image http://www.somewebimage.png";
if(preg_match($reg_exImg, $post, $img)) {
$img_post = preg_replace($reg_exImg, "<img src=".$img[0]." width='300' style='float: right;'> ", $post);
} else {
$img_post = $post;
}
if(preg_match($reg_exUrl, $post, $url)) {
$img_post = preg_replace($reg_exUrl, "<a href=".$url[0]." target='_blank'>{$url[0]}</a> ", $post);
} else {
$img_post = $post;
}
If I block the $reg_exUrl code block I get the image link if it runs the I get the url link.
You can do it in a single pass, your two patterns are very similar and it's easy to build a pattern that handles the two cases. Using preg_replace_callback, you can choose the replacement string in the callback function:
$post = "This is my text with http://www.google.com and some image http://www.domain.com/somewebimage.png";
# the pattern is very basic and can be improved to handle more complicated URLs
$pattern = '~\b(?:ht|f)tps?://[a-z0-9.-]+\.[a-z]{2,3}(?:/\S*)?~i';
$imgExt = ['.png', '.gif', '.jpg', '.jpeg'];
$callback = function ($m) use ($imgExt) {
if ( false === $extension = parse_url($m[0], PHP_URL_PATH) )
return $m[0];
$extension = strtolower(strrchr($extension, '.'));
if ( in_array($extension, $imgExt) )
return '<img src="' . $m[0] . '" width="300" style="float: right;">';
# better to do that via a css rule --^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
return '' . $m[0] . '';
};
$result = preg_replace_callback($pattern, $callback, $post);
I am trying to create a dynamic website, I have a database with some news, and I wanted to get the first image from the post content
The news are added to this database with wordpress, as you know wordpress images are inside the post_content.
Please can you help me to get the first image of the post and dispay the link.
Thank you
Put this in your functions.php file:
function get_first_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$first_img = "/images/default.jpg";
}
return $first_img;
}
and then simply call the function on the page you need to get the first image of the post like this:
<?php echo get_first_image() ?>
I want ask what could be the mistake i am doing in this code.
I am currently trying to find the first occurrence of an image tag or an object tag then return a piece of html if it matches one.
Currently, I can get the image tag, but unfortunately I can't seem to have any results on object tag.
I am thought, I am doing some mistake in my regex pattern or something. Hope requirement is clear enough for you to understand thanks.
My code here:
function get_first_image(){
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) || preg_match_all('/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>/smi', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$mediaSearch = preg_match_all('/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>/smi', $post->post_content, $matches2);
$first_media = $matches2 [1] [0];
$first_img = "/images/default.jpg";
}
if(!empty($first_img)){
$result = "<div class=\"alignleft\"><img src=\"$first_img\" style=\"max-width: 200px;\" /></div>";
}
if(!empty($first_media)){
$result = "<p>" . $first_media . "</p>";
}
return $result;
}
While regular expressions can be good for a large variety of tasks, I find it usually falls short when parsing HTML DOM. The problem with HTML is that the structure of your document is so variable that it is hard to accurately (and by accurately I mean 100% success rate with no false positive) extract a tag.
What I recommend you do is use a DOM parser such as SimpleHTML and use it as such:
function get_first_image(){
global $post, $posts;
require_once('SimpleHTML.class.php')
$post_dom = str_get_dom($post->post_content);
$first_img = $post_dom->find('img', 0);
if($first_img !== null) {
$first_img->style = $first_img->style . ';max-width: 200px';
return '<div class="alignleft">' . $first_img->outertext . '</div>';
} else {
$first_obj = $post_dom->find('object', 0);
if($first_obj !== null) {
return '<p>' . $first_obj->outertext . '</p>';
}
}
return '<div class="alignleft"><img src="/images/default.jpg" style="max-width: 200px;" /></div>';
}
Some may think this is overkill, but in the end, it will be easier to maintain and also allows for more extensibility. For example, using the DOM parser, I can add to the styles of your current image.
A regular expression could be devised to achieve the same goal but would be limited in such way that it would force the style attribute to be after the src or the opposite, and to overcome this limitation would add more complexity to the regular expression.
Also, consider the following. To properly match an <img> tag using regular expressions and to get only the src attribute (captured in group 2), you need the following regular expression:
<\s*?img\s+?[^>]*?\s*?src\s*?=\s*?(["'])((\\?+.)*?)\1[^>]*?>
And then again, the above can fail if:
The attribute or tag name is in capital and the i modifier is not used.
Quotes are not used around the src attribute.
Another attribute then src uses the > character somewhere in their value.
Some other reason I have not foreseen.
So again, simply don't use regular expressions to parse a dom document.
Try this: (You need to define what you want to get in the matches array)
function get_first_image(){
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches) || preg_match_all('(/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>)/smi', $post->post_content, $matches);
$first_img = $matches [1] [0];
if(empty($first_img)){ //Defines a default image
$mediaSearch = preg_match_all('/<object[0-9 a-z_?*=\":\-\/\.#\,<>\\n\\r\\t]+<\/object>/smi', $post->post_content, $matches2);
$first_media = $matches2 [1] [0];
$first_img = "/images/default.jpg";
}
if(!empty($first_img)){
$result = "<div class=\"alignleft\"><img src=\"$first_img\" style=\"max-width: 200px;\" /></div>";
}
if(!empty($first_media)){
$result = "<p>" . $first_media . "</p>";
}
return $result;
}