How to show text if no posts from query? - php

I have a custom WordPress post type, and want to make so if there are no posts in the query to display, it shows a message of saying no posts were found, I've tried a few suggestions but nothing seems to be working so far.
Full Code of the relevant section:
<?php
$k=0;
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query($args);
while($the_query->have_posts()):$the_query->the_post();
$k++;
if($k==1){
$color= 'gray';
}else if($k==2){
$color= 'blue';
}else if($k==3){
$color= 'green';
}else if($k==4){
$color= 'light-blue';
}else if($k==5){
$color= 'yellow';
}
?>
<div itemprop="exampleOfWork" class="col-xs-12 col-sm-4 portfolio-item">
<div class="portfolio-holder">
<?php
if(has_post_thumbnail()){
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'singleport',true);
?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo $image_url[0];?>" alt="Portfolio image" /></a></figure>
<?php }else{ ?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/noimage.jpg" alt="No image" /></a></figure>
<?php } ?>
<h6 itemprop="name"><?php the_title(); ?></h6>
<span itemprop="genre"><?php the_field('name');?></span>
<div class="transparentbg <?php echo $color; ?>">
<?php
$image = get_field('logo');
if( !empty($image) ): ?>
<a itemprop="url" href="<?php the_permalink();?>">
<img src="<?php echo $image['url']; ?>" alt="logo" />
</a>
<?php endif; ?>
<a href="<?php the_permalink();?>" class="info">
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/port-hover-bg.png" alt="Port hover bg" /><br />
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/search-icon.png" height="20" width="20" alt="Search icon">
</a>
</div>
</div>
</div>
<?php endwhile;wp_reset_query();?>
</div>
</div>
</section>
How can we make it so, if there's no posts, it echo's a message?

Add a check -
if (!empty($the_query->have_posts())) {
while(...) {...}
} else {
echo "No Posts!";
}

Issue
You want to use WP Query class for fetching a particular type of posts ( based on custom fields ), and if it returns no posts at all, it should display a message.
Solution
$the_query = new WP_Query( $args );
Where "$args" is your list of parameters for WP_Query constructor.
Now $the_query is an object of class type WP-Query. Hence it contains a function that will return whether there is any post matching your particular query. If there is at least one post, it will return True, else it will return False.
That function to check if there are any posts matching your queries is have_posts() .
Usage is ObjectName->have_posts();
in your specific case it is
$the_query->have_posts();
This will return true or false based on the query ( ie, arguments you supply using $arg variable ).
hence:
if($the_query->have_posts()) {
//There are posts matching the query
}
else
{
//There are no posts matching the query
}
You can use the below code ( You will have to modify this, but still a good start ).
<?php
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query( $args ); ?>
<?php if ( $the_query->have_posts() ) : ?>
<!-- pagination here -->
<!-- the loop -->
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else : ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>
Reference : https://codex.wordpress.org/Class_Reference/WP_Query

You need to add if condition before while loop like that way:
<?php
$k=0;
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query($args);
if( $the_query->have_posts() ) {
while($the_query->have_posts()):
// your code
<?php endwhile;
} else {
echo "No data found.";
}
wp_reset_query();
?>

<?php
$k=0;
$args = array(
'post_type'=>'portfolios',
'posts_per_page'=>5,
'order'=>'DESC'
);
$the_query = new WP_Query($args);
if($the_query->have_posts()):
while($the_query->have_posts()):$the_query->the_post();
$k++;
if($k==1){
$color= 'gray';
}else if($k==2){
$color= 'blue';
}else if($k==3){
$color= 'green';
}else if($k==4){
$color= 'light-blue';
}else if($k==5){
$color= 'yellow';
}
?>
<div itemprop="exampleOfWork" class="col-xs-12 col-sm-4 portfolio-item">
<div class="portfolio-holder">
<?php
if(has_post_thumbnail()){
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'singleport',true);
?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo $image_url[0];?>" alt="Portfolio image" /></a></figure>
<?php }else{ ?>
<figure><a itemprop="url" href="<?php the_permalink();?>"><img src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/noimage.jpg" alt="No image" /></a></figure>
<?php } ?>
<h6 itemprop="name"><?php the_title(); ?></h6>
<span itemprop="genre"><?php the_field('name');?></span>
<div class="transparentbg <?php echo $color; ?>">
<?php
$image = get_field('logo');
if( !empty($image) ): ?>
<a itemprop="url" href="<?php the_permalink();?>">
<img src="<?php echo $image['url']; ?>" alt="logo" />
</a>
<?php endif; ?>
<a href="<?php the_permalink();?>" class="info">
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/port-hover-bg.png" alt="Port hover bg" /><br />
<img itemprop="image" src="<?php echo esc_url( get_template_directory_uri() );?>/assets/images/search-icon.png" height="20" width="20" alt="Search icon">
</a>
</div>
</div>
</div>
<?php
endwhile;
else:
echo "Your message goes here";
endif;
wp_reset_query();
?>
</div>
</div>
</section>
Adding if condition will do it.

Related

Error accessing my widgets.php in wordpress [duplicate]

I have been trying to show the posts of my website in a grid view in one of the category page. For doing so, i implemented the following code:
<div class="row-fluid">
<div class="span6 featured-block">
<?php while($block1Featured->have_posts()): $block1Featured->the_post(); ?>
<a class="featured_image" href="<?php the_permalink();?> "target="_blank">
<?php if ((function_exists('has_post_thumbnail')) && (has_post_thumbnail()) ) {
$image_id = get_post_thumbnail_id();
$image_url = wp_get_attachment_image_src($image_id,'large');
$image_url = $image_url[0];
if(!#getimagesize($image_url)){
$image_url = "/wp-content/uploads/2014/02/logo2.jpg";
}
$blogurl = get_bloginfo('url');
$image_url = str_replace($blogurl, '', $image_url);
?>
<img src="<?php echo bloginfo('template_url'); ?>/thumb.php?src=<?php echo ($image_url); ?>&w=390&h=216&zc=1&q=100" alt="<?php echo the_title(); ?>" />
<?php }
else { ?>
<img src="<?php echo bloginfo('template_url'); ?>/thumb.php?src=<?php echo "http://www.nepaljapan.com/wp-content/uploads/2014/02/logo2.jpg"; ?>&w=390&h=216&zc=1&q=100" alt="<?php echo the_title(); ?>" />
<?php }?>
</a>
<a href="<?php the_permalink();?>" target="_blank">
<h2><?php the_title(); ?></h2></a>
<p><?php echo excerpt(37); ?>
<?php endwhile; ?>
</div>
</div>
But i am facing the problem with this code.
This gives out the error as
Fatal error: Call to a member function have_posts() on a non-object in /home/npjp/public_html/wp-content/themes/nepaljapan/content-category.php on line 15
The line 15 on my code is
<?php while($block1Featured->have_posts()): $block1Featured->the_post(); ?>
What is the problem? Am i actually doing it correct??
Much confused.
Please help me.
Thank you in advance
Your custom query has some problems. You can use this guid to write custom queries in wordpress:
<?php
$block1Featured= new WP_Query( 'category_name=staff+news' );
if ( $block1Featured->have_posts() ) : ?>
<!-- the loop -->
<?php while ( $block1Featured->have_posts() ) : $block1Featured->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php endwhile; ?>
<!-- end of the loop -->
<!-- pagination here -->
<?php wp_reset_postdata(); ?>
<?php else: ?>
<p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<?php endif; ?>

trying to insert php into img src attribute to display featured image on custom post archive page in Wordpress

The image is set to return a URL in the Custom Fields Plugin however it is just coming up with img src Unknown, everything else works on the page except this... code is as follows: Thanks in advance for any help!
<?php get_header(); ?>
<?php
$args = array(
'post_type' => 'artists',
);
$query = new WP_Query( $args );
?>
<section class="row artists">
<?php if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-sm-12 col-md-6 col-lg-3">
<a href="<?php if( get_post_field('artist_website') ) { ?>
<?php echo $artist_website; ?>
<?php } else { the_permalink(); } ?>">
<img src="<?php get_post_field('artist_feature_image'); ?>" alt="<?php echo the_title() ; ?>">
<p><?php echo the_title() ;?></p>
</a>
</div>
<?php endwhile; endif; wp_reset_postdata(); ?>
</section>
<?php get_footer(); ?>
The problem is that get_post_field('artist_feature_image') only return the image.
You need to display it with "echo"
<img src="<?php echo get_post_field('artist_feature_image'); ?>" />
And don't do echo the_title() ;, because the_title() is already doing an echo on get_the_title();
function the_title() {
echo get_the_title();
}
So if you want to display it you just have to do: the_title();

Wordpress/Woocommerce post was called incorrectly

I fixed all woocommerce deprecated functions except one,maybe someone can help me out.I am no professional. Thank You.
The only plugin activated is woocommerce so there is no plugin conflict problem.The wordpress is up to date so is woocommerce.
I am getting this notice,and from what I see the problem comes from page.php.
Notice: post was called incorrectly. Product properties should not be accessed directly. Backtrace: require('wp-blog-header.php'), require_once('wp-includes/template-loader.php'), include('/themes/barbuto/page.php'), WC_Abstract_Legacy_Product->__get, wc_doing_it_wrong Please see Debugging in WordPress for more information. (This message was added in version 3.0.) in /home/public_html/dev/wp-includes/functions.php on line 4139
This is the code from page.php file.
get_header(); ?>
<?php if(is_front_page()){ ?>
<!-- start of banner -->
<div class="banner" style="background: url('<?php echo wp_get_attachment_url(get_post_thumbnail_id($post->ID)); ?>') no-repeat scroll center center transparent;">
</div>
<!-- end of banner -->
<div class="wrapper">
<ul class="products">
<?php
$args = array( 'post_type' => 'product', 'posts_per_page' => 1, 'meta_key' => '_featured', 'meta_value' => 'yes', );
$loop = new WP_Query( $args );
echo "<h1>"; count($loop); echo "</h1>";
$i=1;
while ( $loop->have_posts() ) : $loop->the_post(); global $product; global $woocommerce; ?>
<div class="product_featured_img <?php echo $loop->post->ID; ?> <?php if(($loop->post->ID == '405') || ($loop->post->ID == '72')){ echo 'bottol';} ?>">
<a href="<?php echo get_permalink( $loop->post->ID ) ?>" title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">
<?php woocommerce_show_product_sale_flash( $post, $product ); ?>
<?php if (has_post_thumbnail( $loop->post->ID )) echo get_the_post_thumbnail($loop->post->ID, 'large'); else echo '<img src="'.woocommerce_placeholder_img_src().'" alt="Placeholder" />'; ?>
</a>
</div>
<div class="bottol_text product_featured_content">
<h3>
<a href="<?php echo get_permalink( $loop->post->ID ) ?>"
title="<?php echo esc_attr($loop->post->post_title ? $loop->post->post_title : $loop->post->ID); ?>">
<?php the_title(); ?>
</a>
</h3>
<p>
<?php
//$text_length = count($product->post->post_content);
//if($text_length > 1000){
// echo substr($product->post->post_content,0,2000).'...';
/*} else { */
echo $product->post->post_content;
//}
?>
</p>
<?php if ( is_user_logged_in() ) { ?>
<p class="price"><?php echo $product->get_price_html(); ?></p>
<div class="add_box">
<a class="add_to_cart_button button product_type_simple" data-product_sku="<?php echo $product->get_sku(); ?>" data-product_id="<?php echo $loop->post->ID;?>" rel="nofollow" href="<?php echo $product->add_to_cart_url(); ?>" > add to cart </a>
</div>
<?php }else{echo '' . __('PLEASE LOGIN/REGISTER TO VIEW PRICES', 'theme_name') . '';}?>
</div>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
</ul><!--/.products-->
</div>
Replace this line echo $product->post->post_content; with echo $loop->post->post_content;

CPT output on page breaks other fields

Not sure what i have done wrong here but i noticed that everything dissapears below my code.
If i take fields and put them in top of template then everything works fine.
Code
<?php
$blacklabelpost = array( 'post_type' => 'black-label', );
$loop = new WP_Query( $blacklabelpost );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php
$images = get_field('photos_of_product'); // get gallery
$image = $images[0]; // get first image in the gallery [1] for second, [2] for third, and so on.
if( $image ) : // only show the image if it exists ?>
<div class="col-sm-3 col-md-4 col-lg-3 product-col">
<a href="<?php the_permalink() ?>">
<img src="<?php echo $image['url']; ?>" class="img-responsive"/>
</a>
<div class="row text-center">
<div class="col-xs-12">
<h3 class="UC sTitle"><?php the_title()?></h3>
<div class="border-line center"></div>
<div class="subtitle about_product_short UC"><?php the_field('about_product_short'); ?></div>
</div>
<div class="col-xs-12">
Läs mer
</div>
</div>
</div>
<?php endif; ?>
<?php endwhile; ?>
Below i just have couple of if get field.
Example
<?php if( get_field('full_width_photo_footer') ): ?>
<div class="F-W sida archive">
<?php
$image = get_field('full_width_photo_footer');
if( !empty($image) ): ?>
<img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" class="img-responsive footer-fullwidth-img"/>
<?php endif; ?>
</div>
<?php endif; ?>
As soon as i delete this 'full_width_photo_footer' starts to work again:
<?php
$mypost = array( 'post_type' => 'white-label', );
$loop = new WP_Query( $mypost );
?>
What am i doing wrong ?

Inserting php inside wordpress query

i have this code
<?php $project_taxonomy_select = get_post_meta( $post->ID, '_ep_project_taxonomy_select', true );
$theCatSlug = get_term_by( 'id', $project_taxonomy_select[0], 'project_filter' );
$theCatSlug = $theCatSlug->slug;
echo $theCatSlug; ?>
how to put the php above in "project_filter=" inside my query in the below php code
<div id="project">
<?php $my_query = new WP_Query('post_type=project&posts_per_page=-1&project_filter=the php here');
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a class="all project-item <?php echo $tax ?>" href="<?php the_permalink(); ?>" title="<?php the_title(); ?>">
<img src="<?php if ( has_post_thumbnail()) { ?><?php $thumb_id = get_post_thumbnail_id(); $thumb_url = wp_get_attachment_image_src($thumb_id,'project-thumb-main', true); echo $thumb_url[0]; ?><?php } else { ?><?php echo esc_url(home_url('/')); ?>assets/img/no-project-thumb-main.jpg<?php } ?>">
<div class="magnifier">
<span class="text"><?php the_title(); ?></span>
</div>
</a>
<?php endwhile; wp_reset_query(); ?>
</div>
im using Custom-Metaboxes-and-Fields-for-WordPress
Please Help.. :)
You'd just use simple string concatentation:
WP_Query('post_type=project&posts_per_page=-1&project_filter='.$theCatSlug);

Categories