Retrieving post thumbnail url from a post array with foreach loop - php

I'm having troubles retrieving the thumbnail of each post contained in an array.
I have this array that contains every post of a custom post type:
<?php
$clients_array = array(
'post_type' => 'clients',
'sort_order' => 'ASC',
'sort_column' => 'post_title',
'post_status' => 'publish'
);
?>
While I have no problem retrieving the thumbnail using the standard wordpress loop, like this:
<?php
$query = new WP_Query( $clients_array );
while ( $query->have_posts() ) : $query->the_post();
?>
<?php if ( has_post_thumbnail()) : ?>
<?php the_post_thumbnail() ?>
<?php
endif;
endwhile;
?>
I'd like to load the posts with a foreach look, such as:
<?php
$clients = get_pages($clients_array);
foreach ($clients as $page_data) {
$client_id = $page_data->ID;
$thumb = wp_get_attachment_image_src( get_post_thumbnail_id($client_id), 'thumbnail' );
echo $thumb;
}
?>
Unfortunately, I can't get it work in any way I tried.
What am I doing wrong?

Most of WordPress's functions prefixed with get_ are to retrieve the specified data and not echo it. Therefore putting the data into a variable or echoing it manually would work for your situation like #jothikannan said:
echo get_the_post_thumbnail($id);
or
$foo = get_the_post_thumbnail($client_id);
//do sowething with $foo

you must use follow to get the thumbnail of the features image
<?php echo get_the_post_thumbnail($client_id); ?>
it is already answered here look at here

Related

List each custom post type separately in a wp_query without repeating the loop

I'm using an AJAX search to pull 3 custom post types from wordpress (post, guides, advice). As you can see in my if while loop, the results show which results are which but I'm trying to section them out individually so it will show something like this:
section 1
blog posts
section 2
guides
The problem seems to be that I need to edit the if while loop because adding anything inside that loop will just cause it to be in that loop. Does anyone know the best way to modify the if while loop to achieve this?
function data_fetch(){
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr( $_POST['keyword'] ),
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
)
);
global $post;
if( $the_query->have_posts()) :
while( $the_query->have_posts() ): $the_query->the_post(); ?>
<?php $type = get_post_type();
$term = $_POST['keyword'];
$i++;
$total = $the_query->found_posts;
?>
<span class="search-title">
<?php if ($type == 'post'):?>
<?php echo 'Article: ';?>
<?php elseif($type == 'guide' ):?>
<?php echo 'Guide: ';?>
<?php elseif($type == 'advice' ):?>
<?php echo 'advice: ';?>
<?php endif;?>
<?php the_title();?><br>
</span>
<?php endwhile; ?>
<?php
wp_reset_postdata();
else:
echo '<h3>No Results Found</h3>';
endif;
die();
}
If I were you, I'd probably just do three separate queries. They seem simple enough that it shouldn't cause any issues at all. Otherwise you have to either sort through or reorder the WP_Query results somehow.
If you're set on the single query, however - since these are such short HTML strings, I'd probably just control the output with the Output Buffer.
Basically you can create an associative array, and add the HTML strings to the appropriate keys. You could get a bit more elaborate and have them be nested arrays, but since your output is so light, you can probably get by just by having HTML strings as the values for the keys.
I took the liberty of cleaning up your code a little bit and removing some unused variables, etc.
function data_fetch(){
// Build the Query Arguments
$the_query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
// Do we have posts?
if( $the_query->have_posts()){
// We do. Start an array that will fill with HTML from the output buffer
$output = array(
'post' => '',
'guides' => '',
'advice' => '',
);
// Loop through the posts
while( $the_query->have_posts() ){
$the_query->the_post();
ob_start(); // Turn on the output buffer
$type = get_post_type(); ?>
<span class="search-title">
<?php echo ($type == 'post') ? 'Article: ' : ucwords($type).': '; // Output "Articles: " for posts, or just capitalize the other post type names ?>
<?php the_title();?><br>
</span>
<?php $output[$type] .= ob_get_clean(); // Add the HTML output from the buffer to our array
}
wp_reset_postdata();
// Here we have an array with 3 HTML strings that we can output wherever
echo $output['post'];
echo $output['guides'];
echo $output['advice'];
} else {
echo '<h3>No Results Found</h3>';
}
}
if I understood your concern, I propose to divide your code by creating a generic class.
and you make calls to the different Post Type :
class Custom_Query {
public $post_type;
public $key_word;
public function __construct($post_type, $keyword) {
$this->post_type = $post_type;
$this->key_word = $keyword;
}
public function getResult() {
echo '<h1>Article : ' . $this->post_type . '</h1>';
$the_query = new WP_Query(
array(
'posts_per_page' => 6,
's' => esc_attr($this->key_word),
'post_type' => array($this->post_type),
'post_status' => 'publish'
)
);
if ($the_query->have_posts()):
while ($the_query->have_posts()): $the_query->the_post();
echo '<span class="search-title">';
echo '' . the_title() . '<br>';
echo '</span>';
endwhile;
else:
echo '<h3>No Results Found</h3>';
endif;
wp_reset_postdata();
}
}
global $post;
$type = get_post_type();
$term = $_POST['keyword'];
$article = new Custom_Query($type, $term);
$article->getResult();
You were on the right track initially. You can just use the standard post objects to check for post type. You can adjust to fit your needs, but try something like this:
<?php
query = new WP_Query( array(
's' => esc_attr($_POST['keyword']),
'posts_per_page' => 6,
'post_type' => array('post' , 'guides', 'advice'),
'post_status' => 'publish'
) );
if ($query->have_posts()) {
while ($query->have_posts()):
$query->the_post();
?>
<div class="posts">
<?php
if ($query->post->post_type === 'post') {
// add your content
} else if ($query->post->post_type === 'guides' {
// add your content
} else {
// add your content
}
?>
</div>
<?php endwhile;
} else {
// no posts found
}

How to call a wp_list_categories to page template

I used this code to my category.php and I want it to convert for my page template, this code is fully functional and working on category.php.
<?php
if (in_category('interior')) {
$cat = get_query_var('cat');
$this_category = get_category($cat);
$this_category = wp_list_categories('hide_empty=0&hierarchical=false&order=ASC&orderby=title&show_count=0&title_li=&use_desc_for_title=1&child_of='.$this_category->cat_ID."&echo=0");
if($this_category !='<li>No categories</li>') {
echo '<ul class="ul-menu">'.$this_category.'</ul>';
}
}
?>
Image Attached Sample
Use this code into your page template.
$args = array (
'cat' => array(2,6,9,13),//use category id
'posts_per_page' => -1, //showposts is deprecated
'orderby' => 'date' //You can specify more filters to get the data
);
$cat_posts = new WP_query($args);
if ($cat_posts->have_posts()) : while ($cat_posts->have_posts()) : $cat_posts->the_post();
get_template_part( 'content', 'page' );
endwhile; endif;
I think its work for you. check and let me know

Post image only with a e keyword

I want to post a gallery formed by a number of images from my site that have a certain keyword. Like from a certain location, or time. I thought to use the caption option or the description option from wordpress. Images will have more keywords, something like: "Location" "Sunset". I tryed to use this What is the function got get all the media files wordpress? combined with https://wordpress.org/ideas/topic/functions-to-get-an-attachments-caption-title-alt-description but I cant get them working. Can you help me please. But I am a newbie so can you explain exactly what to write in function.php and what to write in page-name.php
LE: <?php $attachment_meta = wp_get_attachment(wp_get_attachement_id()); ?>
<?php if ($attachement_meta[caption] == 'Ceahlau' ) ?>
echo do_shortcode('[gallery columns="4" link="file" ids=" <?php wp_get_attachement_id() ?>"]')
<?php else: ?>
<?php endif; ?>
This is what I have now in my page-name.php
<?php $attachment_meta = wp_get_attachment(wp_get_attachement_id()); ?>
<?php if ($attachement_meta[caption] == 'Ceahlau' ) ?>
echo do_shortcode('[gallery columns="4" link="file" ids=" <?php
wp_get_attachement_id() ?>"]')
<?php else: ?>
<?php endif; ?>'
This is what i have now in my page-name.php
This is what i have now in my page-name.php
<?php
$args = array(
'post_type' => 'attachment',
'numberposts' => -1,
'post_status' => null,
'post_parent' => null, // any parent
'post_mime_type' => 'image'
);
$attachments = get_posts($args);
if ($attachments) {
$attachment_meta = wp_get_attachment($attachment->ID);
foreach ($attachments as $post) {
if ($attachment_meta['caption'] == 'Ceahlau' ){
setup_postdata($post);
echo wp_get_attachment_image( $attachment->ID, 'full' );
the_attachment_link($post->ID, false);
}
}
}
?>

Simple query for Wordpress posts & excerpts

I'm trying to make a little "latest news" section on my custom homepage in Wordpress, that outputs:
2 most recent news stories
Their titles
The excerpt
The link
I've tried taking the standard loop from the codex to see what I get first, but I get nothing. I am a bit confused, as I can't work out why it's not even outputting ANY posts, no content at all using just the basic loop:
<?php
// The Query
$the_query = new WP_Query( 'post_count=2' );
// The Loop
if ( $the_query->have_posts() ) {
echo '<ul>';
while ( $the_query->have_posts() ) {
$the_query->the_post();
echo '<li>' . get_the_title() . '</li>';
}
echo '</ul>';
} else {
// no posts found
echo 'No news is good news!';
}
/* Restore original Post Data */
wp_reset_postdata();
?>
This code presently shows the "no news is good news" message. There are two published posts.
Your code does render output on my side, so it is working. You have one problem though, post_count is a property and not a parameter of WP_Query. You should be using posts_per_page
What I do believe is happening why you don't get any output, is that you are using custom post types, and not normal posts, which in this case will render no output as you don't have any normal posts.
Just change this line
$the_query = new WP_Query( 'post_count=2' );
to
$the_query = new WP_Query( 'posts_per_page=2&post_type=NAME_OF_POST_TYPE' );
You're passing the variable $args into WP_Query but not actually defining it.
Try this:
$args = array(
'post_type' => 'post',
'posts_per_page' => 2,
'no_found_rows' => false,
);
$the_query = new WP_Query( $args );
Then to output the content you need:
if ( $the_query->have_posts() ) :
echo '<ul>';
while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<li>
<h3><?php the_title(); ?></h3>
<?php the_excerpt(); ?>
</li>
<?php endwhile;
echo '</ul>';
else :
// no posts found
echo 'No news is good news!';
endif;
wp_reset_postdata();
You don't need to use this alternative syntax for the if statement but it's common to see it written this way.
I noticed since writing this answer you updated your question passing in 'post_count=2' to WP_Query. You need to use 'posts_per_page' instead. post_count is a property of the query object and not a parameter.
This should only return the last two posts published.
<?php
$args=array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 2,
);
$my_query = null;
$my_query = new WP_Query($args);
if( $my_query->have_posts() )
{
echo '<ul>';
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>
<h1><?php the_title(); ?></h1>
<?php the_excerpt(); ?>
</li>
<?php endwhile;
echo '</ul>';
<?php
}
else
{
echo 'No news is good news!';
}
wp_reset_query(); // Restore global post data stomped by the_post().
?>
(The above is slightly changed from the post here)

How to get post content from its ID in WordPress multi site?

I'm running a multi site and I want to pull post with certain categories from two blogs. Therefore I am running a loop for each of the blog to pull the posts as one of the category is in blog 1 while the other category is in blog 2.
<?php $value = array(); ?>
<?php
// Get the values from $_POST
$original_blog_id = get_current_blog_id(); // get current blog
$bids = array(1,2); // all the blog_id's to loop through EDIT
foreach($bids as $bid):
switch_to_blog($bid);
$args = array(
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => 'Music',
'field' => 'slug',
'terms' => array('artist', 'club')
),
)
);
$the_query = new WP_Query( $args );
?>
<?php $postids = array(); ?>
<?php if ( $the_query->have_posts() ) { ?>
<?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
<?php $postids[]=get_the_ID(); ?>
<?php endwhile; ?>
<?php $value[] = $postids; ?>
<?php
} else {
// no posts found
echo 'Nothing found.';
}
?>
<?php endforeach; ?>
<?php
$it = new RecursiveIteratorIterator(new RecursiveArrayIterator($value));
$list = iterator_to_array($it,false);
$posts = new WP_Query(array(
'post__in' => $list,
'post_type' => 'post',
));
?>
<?php
foreach ($posts as $post) {
setup_postdata($post);
?>
<?php echo the_title(); ?>
<?php
}
wp_reset_postdata(); ?>
<?php switch_to_blog($original_blog_id); ?>
The reason why I'm getting the IDs inside an array:
<?php $postids[]=get_the_ID(); ?>
because I want to fetch random post's. If at this point instead of the above statement I get the title and content of the posts then it will show in sequential order. Something like this:
BLOG1: POST1,POST2, POST : BLOG2: POST1, POST2, POST3
But I want Posts in random order like this:
BLOG1: POST1, BLOG2: POST3, BLOG1: POST2, BLOG2: POST1: BLOG2: POST2
So everything is working fine, I am able to get the posts IDs even outside the foreach loop but the problem is:
I am not able to get post content from those IDs. It only gives me posts from blog 2 because the current blog is 2. But it doesn't show anything from blog1 even though the postID is in the list array.
Can anyone please help?
The solution can be the following, just add the code into your themes footer.php files, although this can be put anywhere within your WordPress theme, example:
<?php
if (!function_exists('display_posts_from_blogs')) {
function display_posts_from_blogs($blog_id) {
global $switched;
switch_to_blog($blog_id); //switched to blog id 2, for example
// Get latest Post
$latest_posts = get_posts('category=-3&numberposts=6&orderby=post_name&order=DSC');
$cnt =0;
?>
<ul>
<?php foreach($latest_posts as $post) : setup_postdata($post);?>
<li>
<?php echo $post->post_title; ?>
</li>
<?php endforeach ; ?>
<?php restore_current_blog(); //switched back to main site
} //end function
}
?>

Categories