Grabbing A WordPress Post's Image and Displaying it? - php

Is there a way to grab a post's first image and have it displayed as a thumbnail link to the post itself on the homepage? I can't seem to figure it out. Prefer not to use the featured image function. Is there a workaround? Any help would be much appreciated.
Would I be able to use the following code to acheive what I want? It doesn't seem like I can specify a post ID, but maybe i'm wrong?
http://www.wordimpressed.com/wordpress/get-the-first-image-from-a-post-and-display-it/
My main concern is grabbing a few posts and being able to display them on the frontpage/homepage. Is that possible?

You could do it through two ways:
function post_photo_count_attachments( $post_id ) {
$attachments = get_children(
array( 'post_parent' => $post_id )
);
return( $attachments[0] );
}
Or by Query/XPath method:
function post_photo_count_xpath( $post_id ) {
global $wpdb;
$post_id_safe = intval( $post_id );
$html = $wpdb->get_row(
"select * from {$wpdb->posts} where ID={$post_id_safe} limit 1"
);
$doc = new DOMDocument();
#$doc->loadHTML( $html->post_content );
$path = new DOMXpath( $doc );
$images = $path->query( "//img" );
return( $images->item(0)->getAttribute('src') );
}
print_r() these returns for more detailed information.

I've a code similar working in my web in the loop. It should work fine for you!
$content = $post->post_content;
$content = preg_replace('/\[.*\]/', '', $content);
$image = '';
$x = stripos($content, '<img');
if ($x !== false) {
$x = stripos($content, 'src="', $x);
if ($x !== false) {
$x += 5;
$y = strpos($content, '"', $x);
$image = substr($content, $x, $y-$x);
}
}
It works fine for me, so if you've problems please tell me. ;)

Related

Why html_entity_decode won't bring formatted HTML in WordPress?

I have this shortcode:
I do this shortcode in template, I tried several WordPress themes, and it does not return HTML, but just text in continuous row.
I used this shortcode way abck and it worked, I do not know what happened meanwhile in a year so it does not work in WordPress anymore.
Anyone has a clue?
function paywall_level_b( $atts, $content = null ) {
$post = get_queried_object();
if ( function_exists( 'pmpro_has_membership_access' )) {
// Check if the user has access to the post.
$hasaccess = pmpro_has_membership_access( $post->ID );
// Display Content if the user has access to the post.
if( ! empty( $hasaccess ) ) {
$content = apply_filters('the_content', get_the_content());
echo $content;
// Display Text if the user has no access to the post, but is logged in.
} elseif ( is_user_logged_in() ) {
$content = apply_filters('the_content', get_the_content());
$sentences = explode(".", $content);
$first_slice = implode(".", array_splice($sentences, 0, 5));
$second_slice = implode(".", array_splice($sentences, 0));
echo '<div class="non-paywall">'. html_entity_decode ( $first_slice ) .'.</div><div class="pmpro_content_message">Text</div>';
// Display Text if the user has no access to the post, and is not logged in.
} else {
$content = apply_filters('the_content', get_the_content());
$sentences = explode(".", $content);
$first_slice = implode(".", array_splice($sentences, 0, 5));
$second_slice = implode(".", array_splice($sentences, 0));
echo '<div class="non-paywall">'. html_entity_decode ( $first_slice ) .'.</div><div class="pmpro_content_message">Text 2</div>';
}
}
}
add_shortcode( 'paywall_level_b', 'paywall_level_b' );

Get first image from last post in WordPress

Can't get the first picture in the last post (function - get_first_post_image). Where is the mistake? Please help me. Thank you in advance for your help.
function get_first_post_image() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
if(preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches)){
$first_img = $matches [1] [0];
return $first_img;
}
else {
$first_img = "http://yyyyyy/post-default.png";
return $first_img;
}
};
function custom_function(){
$args = array(
'numberposts' => '1',
);
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ):
$post_id = $recent['ID'];
$post_url = get_permalink($recent['ID']);
$post_title = $recent['post_title'];
$post_content = $recent['post_content'];
$post_thumbnail = get_the_post_thumbnail($recent['ID']);
$imglink = get_first_post_image($recent['ID']);
endforeach;
$data = '... ' . $imglink . ' ...';
....
}
Sorry for my bad English.
I've rewritten the function to return the default image if no first image is found. Best way of parsing HTML is DOM parsing, not regex.
function get_first_post_image(string $post_content): string
{
$defaultImage = 'http://yyyyyy/post-default.png';
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTML($post_content);
$img = $doc->getElementsByTagName('img');
if (!$img->length) return $defaultImage;
return $img->item(0)->getAttribute('src') ?: $defaultImage;
}
You are calling get_first_post_image() with the ID instead of the post content.
change
$imglink = get_first_post_image($recent['ID']);
to
$imglink = get_first_post_image($recent['post_content']);
I've updated the function above
Changed Signature
Removed global $post
Changed loadHtml()

How can I restrict Worpress' Automatically Paginate Post to only one post type?

I am using the Wordpress Automatically Paginating Post. My requirement is to paginate multiple post types. It works fine with post-type "post" but I have custom post types like "department", "information" and more. I want it to work for every post type. Can you help me to make it generic?
Here is my Code.
foreach ($content as $index => $paragraph ) {
$paragraph_words = count( preg_split( '/\s+/', strip_tags( $paragraph ) ) );
$word_counter += $paragraph_words;
if ( $word_counter >= $num_words ) {
$content[ $index ] .= '<!--nextpage-->';
$word_counter = 0;
} else {
continue;
}
}
unset( $word_counter );
unset( $index );
unset( $paragraph );
unset( $paragraph_words );
break;
//Reunite content
$content = implode( "\r\n\r\n", $content );
//And, overwrite the original content
$the_post->post_content = $content;
I was facing the same issue after hours of googling i have found the solution. Use a jquery plugin imtech_pager
Replace '<!--nextpage-->'
with This
'</span><span class="do-paginate">'
After replacing
paste this code and include imtech_pager JS and its css
echo '<div id="content"><span class="do-paginate">' . $content . '</span></div><div
id="pagingControls" class="pagination_single"></div>';
?>
<script type="text/javascript">
var pager = new Imtech.Pager();
jQuery(document).ready(function() {
pager.paragraphsPerPage = 1; // set amount elements per page
pager.pagingContainer = jQuery('#content'); // set of main container
pager.paragraphs = jQuery('.do-paginate',
pager.pagingContainer);
// set of required containers
pager.showPage(1);
});
</script>

Trouble returning usable string or array with foreach loop

I am trying to return an string that I can use in a function (programatically adding terms in WordPress).
My function that generates my string is basically looping through html meta tags that match a certain criteria and is as follows:
function getYouTubeTags( $post_id ) {
$video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
$tag_url = "http://www.youtube.com/watch?v=" . $video_id;
$sites_html = file_get_contents($tag_url);
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_tag = null;
foreach( $html->getElementsByTagName('meta') as $meta ) {
if( $meta->getAttribute('property')==='og:video:tag' ){
$meta_og_tag = $meta->getAttribute('content');
print_r ($meta_og_tag . ",");
}
}
}
When I simply execute this (getYouTubeTags();), it returns the string:
supra vs lambo,tt lambo,twin turbo,street race,texas streets,underground racing,supra,turbo supra,1200hp,nitrous,superleggera,gallardo,
In my function to add terms to a post, the following DOES NOT work:
function rct_save_post_terms( $post_id ) {
$terms = getYouTubeTags();
wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}
If I manually add the string as outputted from the first function, it DOES work:
function rct_save_post_terms( $post_id ) {
$terms = 'supra vs lambo,tt lambo,twin turbo,street race,texas streets,underground racing,supra,turbo supra,1200hp,nitrous,superleggera,gallardo,';
wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}
Also, according to WordPress, $terms in wp_set_post_terms: Can be an array or a comma separated string.
I know I must be missing something simple here but cannot seem to figure it out. Thank in advance for some help!
Since you want to get those string to be reused, why not return those:
function getYouTubeTags( $post_id ) {
$out = null;
$video_id = get_post_meta( get_the_ID(), 'rfvi_video_id', true );
$tag_url = "http://www.youtube.com/watch?v=" . $video_id;
$sites_html = file_get_contents($tag_url);
$html = new DOMDocument();
#$html->loadHTML($sites_html);
$meta_og_tag = null;
foreach( $html->getElementsByTagName('meta') as $meta ) {
if( $meta->getAttribute('property')==='og:video:tag' ){
// i seriously doubt this checking i think this should be
// if($meta->getAttribute('property') == 'og:video') {
$meta_og_tag = $meta->getAttribute('content');
// print_r ($meta_og_tag . ",");
$out[] = $meta_og_tag; // gather them inside first
}
}
return implode(',', $out); // return implode comma delimited strings
}
And then utimately, then you could use them:
function rct_save_post_terms( $post_id ) {
$terms = getYouTubeTags(); // strings are in here
wp_set_post_terms( $post_id, $terms, 'post_tag', true );
}
You don't seem to be returning a value in your original function. You need to use;
return $meta_og_tag;
at the end of your function to return a value back to an assigned variable.
Also, you need to append strings to the end of your returned variable using .=;
$meta_og_tag .= $meta->getAttribute('content');
OR you can save each attribute in an array and implode for the return;
// inside loop
$meta_og_tag[] = $meta->getAttribute('content');
// outside loop
return implode(', ',$meta_og_tag);
print_r will simply echo the contents of the variable, not return a value.
Hope this helps.

PHP preg_match_all with Wordpress to echo a image if more than 1 image in post

Basically what I am looking to accomplish is if there is more than 1 img it will echo the below statement so I can basically have a rollover saying click to see more. Another question would be how would I have it link to the post itself if I were to change it to 'a href' and echo out the permalink to post_id.
Any help would be very much appreciated.
function catch_images() {
global $post, $posts;
$first_image = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/ii', $post->post_content, $matches);
$first_image = $matches [2] [0];
if ($output == '2') {
echo '<div class="seemore"><img src="images/magglass.png"></div><div class="seemoretext">See More</div>';
}
}
Well I feel stupid, I should of just put the following:
if ($output > '2') {
Why don't you do something like this to check the number of attached images in your post? This assumes that your images are attached to your post, though.
Well, As said in comment , I did not really understood what you want to link if it has more than 2 images , to the image itself ?? to attachment page ? to another post ?
anyhow, something like this should work - read and execute the comments to suit your needs ..
(the second question I did not understood ...)
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => 'published', // or NULL
//'post_mime_type' => 'image', // only if you want images alone
'post_parent' => $post->ID
);
$attachments = get_posts($args);
$counter = 0;
$attachments = get_posts( $args );
if ( $attachments ) {
foreach ( $attachments as $attachment ) {
if (!$counter == 1) {
echo wp_get_attachment_image($attachment->ID);
}
else {
// uncomment the following line if you want a LIST of all following attachments and then delete the marked line
//echo '<a href = ' . wp_get_attachment_url($attachment->ID) . '> see more (image'. $counter .') </a>' ;
}
++$counter;
}
// Delete this line if you have more than 2 images, otherwise it will show the last one only
echo '<a href = ' . wp_get_attachment_url($attachment->ID) . '> see more (image'. $counter .') </a>' ;
}
The following is the answer to my own question, it will echo if there is more than 1 img src tag in a given post.
function catch_images() {
global $post, $posts;
$first_image = '';
ob_start();
ob_end_clean();
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/ii', $post->post_content, $matches);
$first_image = $matches [0] [1];
if ($output > '2') {
echo '<div class="seemore"><div class="seemoreimg"><img src="images/magglass.png"></div><div class="seemoretext">See More</div></div>';
}
}
Thanks everyone for your help!

Categories