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()
Related
I'm trying to get the featured image from the postid passed through the url.
http://www.example.com/schedule-appointment/?postid=589
I've managed to get the postid from the url, but everything goes down hill from there. I must be missing something simple. I'm not a programmer...would love some help.
add_shortcode('CF7_ADD_POST_ID', 'cf7_add_post_id');
function cf7_add_post_id(){
$Path=$_SERVER['REQUEST_URI'];
$control = array();
$control = explode('?', $Path);
$get = $control[1];
$get = explode('=', $get);
$get2 = $get[1];
$args = array(
'post_type' => 'page',
'post__in' => $get2,
);
// Fire up the Query
$the_query = new WP_Query( $args );
while ( $the_query->have_posts() ): $the_query->the_post();
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->$get2) );
echo '$feat_image';
};
Try this
<?php
add_shortcode('CF7_ADD_POST_ID', 'cf7_add_post_id');
function cf7_add_post_id(){
$ID = isset( $_GET["postid"] ) ? $_GET["postid"] : false;
if( $ID ){
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id( $ID ), 'full' );
$url = $thumb['0'];
echo "<img src ='".$url."' alt = 'Image'>";
}
}
?>
There is no need for the WP_Query , You have one id and you can easily get this done by using following code,
add_shortcode('CF7_ADD_POST_ID', 'cf7_add_post_id');
function cf7_add_post_id(){
$postid = $_GET['postid'];
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($postid) );
echo '$feat_image';
};
I added a custom php function to my wordpress template, where I want to echo the content of pages under a certain parent:
Departments
-department 1 (get the title and the content clean)
-department 2 (get the title and the content clean)
(...)
The code I have so far is not working as i want, the title is fine but I need to filter the content so I can grab only the text between the "<p>" tag. Is this possible? Thank you.
functions.php
function echo_childs_of( $postID ) {
$args = array(
'order' => 'ASC',
'post_parent' => $postID,
'post_status' => null,
'post_type' => 'any'
);
$page_childs = get_children( $args );
if ( $page_childs ) {
foreach ( $page_childs as $child ) {
$title = get_the_title( $child );
$content = get_the_content($child);
$content = strip_shortcodes( $content );
$content = apply_filters('the_content', $content);
$content = str_replace(']]>', ']]>', $content);
$content = strip_tags($content);
echo $title;
echo $content;
}
}
}
on my php page
echo_childs_of( 7 );
You could use DOM to find the p tag elements and itarate over them using a for cycle to do whatever it is that you want to do.
$content = get_the_content($child);
$doc = new DOMDocument();
#$doc->loadHTML($content);
$p_elements = $doc->getElementsByTagName('p');
foreach ($p_elements as $p) {
//Do something with the p element... Strip tags maybe?
}
Try this:
$content = get_the_content($child);
preg_match('/<p>(.*)<\/p>/', $content, $match);
$content = $match[1];
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.
I am working with this two Wordpress Function for my Pinterest Button. What i'm trying to achieve is the flow chart below.
Function Catch That Image
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 = "http://www.mywebsite.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
}
return $first_img;
}
Function Get Featured Image
function get_featured_image( $size = 'full' ) {
global $post;
if ( has_post_thumbnail($post->ID) ) {
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
return $featured_image[0];
}
return false;
}
Wordpress Featured Thumbnail
<?php the_post_thumbnail(); ?>
As you can see in my flow chart, I am trying to combine the two functions above. The problem is it's not working.
This is my code:
Function Consolidated Pinterest Image Function
function pinterest_image_snatcher($size = 'full' ) {
global $post;
if ( has_post_thumbnail($post->ID) ) {
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
return $featured_image[0];
}
else
$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 = "http://www.mywebsite.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
}
return $first_img;
}
The first two functions above is working really fine but the third one is not! Could anyone help to consolidate the two function above. Everyone is welcome to modify the codes.
Please help me out Dear PHP Experts. My Code is messed up and NOT working. Do you mind to modify this according to the flow chart? thank you!
How to add Pinterest button for WordPress Blogs
Try this:
function pinterest_image_snatcher( $size = 'full' ) {
global $post;
$first_img = '';
if ( has_post_thumbnail($post->ID) ) {
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), $size);
$first_img = $featured_image[0];
} else {
$output = preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches);
$first_img = $matches[1][0];
if( empty($first_img) ) {
$first_img = "http://www.mywebsite.com/wp-content/themes/Lord%20of%20Avernus%20-%20Abaddon/Images/Deafult_Img.png";
}
}
return $first_img;
}
I just fixed missing brackets as #royal-bg mentioned in the comments & changed logic a bit.
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. ;)