Check if Wordpress loop has posts - wordpress

I have a custom loop with posts which are added from the custom meta field checkbox. Only if the checkbox is checked, then the post is being added to the loop. I have a container that holds that loop. What i want to do is to check if that loop got any posts and if it is empty - just hide that container. Because otherwise when the loop is empty the container is remaining on the page:
<div>
<ul>
</ul>
</div>
This is the loop:
<?php
/* Slider ------- */
$slider = new WP_Query('showposts=-1');
if ( $slider->have_posts() ):
?>
<div>
<ul>
<?php while ( $slider->have_posts() ) : $slider->the_post(); ?>
<?php if ( get_post_meta($post->ID, "mf_homeslider", true) == 'slider_on' ){ // Check if post was added to slider ?>
<li>
<?php if (has_post_thumbnail()) { ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('large'); ?>
</a>
<?php } ?>
<div>
<?php get_template_part('includes/post_meta'); ?>
<h2>
<?php the_title(); ?>
</h2>
</div>
</li>
<?php } ?>
<?php endwhile; ?>
</ul>
</div>
<?php
endif;
wp_reset_query();
?>
Thank you in advance for your help.

You should filter your query by the custom field (see details here), it could also improve performance (an SQL condition vs. a while-if loop). After that, have_posts() returns whether the loop contains any posts.
So instead of
$slider = new WP_Query('showposts=-1');
use
$slider = new WP_Query(array(
'meta_key' => 'mf_homeslider',
'meta_value' => 'slider_on',
'posts_per_page' => -1)
);
and there's no further need for if ( get_post_meta(...
(showposts is deprecated, use posts_per_page instead).
Note: you are mixing braces and if-endif style, the latter would be much readable when nesting.

Related

Issue on custom post type shortcode ordering by ids

For a special purpose, i've to create a custom post type and display it like a carousel by indicating IDS of each custom post by it's ID on my shortcode.
The problem is that when i'm using it, the last id of custom shortcode is not displayed in on the correct place, sometimes in first, sometime in last but never in the correct place( for exemple I set 3527 ID on the 4 place, its shows this prodect on the last position.
I tried to show the array of the id and it seems that there isn't any problem with (array modification etc.) the Ids are in the correct place on Array
Here is the code :
//Carousel Shortcode Produits By ID
function carousel_products_ids_shortcode( $atts ) {
$c=extract(shortcode_atts( array(
'ids'=>''
), $atts ));
$args = array(
'post_type' => 'pp_produit',
'posts_per_page' => -1,
'publish_status' => 'published',
'order'=>'ASC'
);
if(!is_null($ids) && $ids!=""){
$args['post__in']=explode(",",$ids);
print_r($args['post__in']);
}
ob_start();
$query = new WP_Query($args);
if ( $query->have_posts() ) { ?>
<div class="carousel-custom-products">
<div class="owl-carousel owl-custom-products">
<?php while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="single-produit">
<div id="produit-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php if(has_post_thumbnail()) { ?>
<div class="img-container">
<a class="thumb-produit" href="<?php the_permalink(); ?>"><?php the_post_thumbnail(); ?></a>
</div>
<?php }else{ ?>
<div class="img-container">
<a href="<?php the_permalink(); ?>" class="thumb-produit">
<img src="<?php echo get_stylesheet_directory_uri()."/img/defaultpp.jpg" ?> ">
</a>
</div>
<?php } ?>
<div class="produit-single-content">
<h3><?php echo (strlen(get_the_title())>30)? substr(get_the_title(),0,30)."..." : substr(get_the_title(),0,30); ?></h3>
<?php the_excerpt(); ?>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
</div>
<?php $myvariable = ob_get_clean();
return $myvariable;
}
}
add_shortcode( 'carouselproductsids', 'carousel_products_ids_shortcode' );
Here is the shortcode :
[carouselproductsids ids="3477,3479,3481,3527,3487,3483,3485,3489,3491,3496,3493"]
For example, the ID 3257 is on the last position when the carousel is generated !
the wp_query will fetch the posts from db according to "order" arg you passed so it will check if the post id is in the array or not but it will not preserve the order of array
if you want to show the posts in specific order you can either pass some custom field (like meta key or someting) to posts to get them in the specific order or you can run loop on post_id array calling wp_query on each id

How to get from post_class from relationship (related)

I have created two custom post types, 'offers' and 'brands'. I have made the relationship using an advanced custom fields relationship field 'related_brand'.
Each brand uses a single post and the related posts are shown on the same page, however, when using post_class on the related posts I just noticed they are displaying the brands post classes and not the related posts classes, which are different.
How can I pull in the correct post_class for the related posts bearing in mind they are two separate post types.
The following pulls in the related posts.
$offers = get_posts(array(
'post_type' => 'offers', // name of custom post type
'meta_query' => array(
array(
'key' => 'related_brand', // name of custom field
'value' => '"' . get_the_ID() . '"',
'compare' => 'LIKE'
)
)
));
Watered down code that displays the related posts.
<?php if ($offers) : ?>
<?php foreach ($offers as $offer) : ?>
<div <?php post_class(); ?>> <!--Displaying the incorrect post classes-->
<div>
<a href="<?php the_permalink($offer->ID); ?>">
<?php echo get_the_post_thumbnail($offer->ID,); ?>
</a>
</div>
<div>
<a href="<?php the_permalink($offer->ID); ?>">
<?php echo get_the_title($offer->ID); ?>
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>
In his case he is taking the post_class with the id of the current loop and not that of foreach but of the current loop of the tag.
To get it right you should use post_class with two arguments post_class ('', $ post_id); where the second is the post id. In your case the code should be + - like this:
<?php if ($offers) : ?>
<?php foreach ($offers as $offer) : ?>
<div <?php post_class('', $offer->ID ); ?>> <!--Displaying the incorrect post classes-->
<div>
<a href="<?php the_permalink($offer->ID); ?>">
<?php echo get_the_post_thumbnail($offer->ID,); ?>
</a>
</div>
<div>
<a href="<?php the_permalink($offer->ID); ?>">
<?php echo get_the_title($offer->ID); ?>
</a>
</div>
<?php endforeach; ?>
<?php endif; ?>

Assign a number to each post in a custom post type?

I'm building a page that is displaying a list of posts (potentially they will be randomly displayed) in a grid.
These posts are a custom post type, and each post is assigned to a single taxonomy for organization.
For each post I'd like to display an associated number. I don't mean the post ID, as that isn't specific enough. Basically, I'd like to treat the custom post type as its own list of posts. So the first post in that post type will be post #1, the second would be #2, and so on.
As well, if it's possible to do this by taxonomy, that would be even better. But I'd settle for just numbering the posts in the custom post type in general.
My solution so far is this: create a function in functions.php that loops through the custom post type, and assigns a number (starting at 1 for the first post) to each post as a custom field. This function runs whenever the page that displays the posts is loaded. So that function runs first in its own loop, and then the page does a normal loop and gets each number.
This solution works cosmetically. I'm getting the result that I want. However, it's not very efficient as it will run any time the page is loaded.
Is there a better way to do this? Perhaps a way to automatically assign a number to a post whenever a post is published? I understand that if a post is deleted, there'd be a skipped number. That's acceptable.
I hope this is clear.
I edited this for clarity, as well as updating the current solution which has changed. I also removed the block of code I have here because it's no longer necessary.
I added 2 lines below, one setting the post count, and one printing the number sequentially look for: $postNumber
<ul id="uselist">
<?php
query_posts( array(
'post_type' => 'use',
'order' => 'desc',
'posts_per_page' => 6
) );
if ( have_posts() ) :
$postNumber = 1; //add a sequential post number!
while ( have_posts() ) : the_post();
$usecategory = get_term_by('id', get_field('use_category'), 'usecategory');
?>
<li>
<div class="use" style="border-bottom:15px solid <?php the_field('category_colour', $usecategory); ?>;">
<div class="useimage" style="background-image:url(<?php the_field('image'); ?>);">
<?php if (get_field('display_vimeo_video') == 'yes') { ?>
<div class="playicon"><img src="<?php echo bloginfo('template_url'); ?>/images/playicon.png" /></div>
<?php } ?>
</div>
<div class="useinfo">
<div class="usecatimage">
<img src="<?php the_field('category_image', $usecategory); ?>" />
</div>
<div class="usecatandtitle">
<h2 class="usecat"><?php echo $usecategory->name; ?> / # <?php echo $postNumber++; ?> //POST NUMBER WILL INCREASE SEQUENTIALLY HERE</h2>
<h3 class="usetitle"><?php the_title(); ?></h3>
</div>
<div class="usename">
<?php the_field('name'); ?>, <?php the_time('M d'); ?>
</div>
</div>
</div>
</li>
<?php
endwhile;
else :
endif;
?>
</ul>
Try this code
EDITED CODE
Add the function in your functions.php file
function Get_Post_Number($postID){
$temp_query = $wp_query;
$postNumberQuery = new WP_Query('orderby=date&posts_per_page=-1');
$counter = 1;
$postCount = 0;
if($postNumberQuery->have_posts()) :
while ($postNumberQuery->have_posts()) : $postNumberQuery->the_post();
if ($postID == get_the_ID()){
$postCount = $counter;
} else {
$counter++;
}
endwhile; endif;
wp_reset_query();
$wp_query = $temp_query;
return $postCount;
}
This is your loop
<ul id="uselist">
<?php
query_posts( array(
'post_type' => 'use',
'order' => 'desc',
'posts_per_page' => 6
) );
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$currentID = get_the_ID();
$currentNumber = Get_Post_Number($currentID);
$usecategory = get_term_by('id', get_field('use_category'), 'usecategory');
?>
<li>
<div class="use" style="border-bottom:15px solid <?php the_field('category_colour', $usecategory); ?>;">
<div class="useimage" style="background-image:url(<?php the_field('image'); ?>);">
<?php if (get_field('display_vimeo_video') == 'yes') { ?>
<div class="playicon"><img src="<?php echo bloginfo('template_url'); ?>/images/playicon.png" /></div>
<?php } ?>
</div>
<div class="useinfo">
<div class="usecatimage">
<img src="<?php the_field('category_image', $usecategory); ?>" />
</div>
<div class="usecatandtitle">
<h2 class="usecat"><?php echo $usecategory->name; ?> / Use <?php echo $currentNumber ; ?></h2>
<h3 class="usetitle"><?php the_title(); ?></h3>
</div>
<div class="usename">
<?php the_field('name'); ?>, <?php the_time('M d'); ?>
</div>
</div>
</div>
</li>
<?php
endwhile;
else :
endif;
?>
</ul>
I have not tried this code, but it should work.
I guess you could pull this off easily using Custom Fields. For each post in your custom post type, add a custom meta field, say post_number and manually enter the value for that field.
And, display the value in your page using get_post_meta().
<ul id="uselist">
<?php
query_posts( array(
'post_type' => 'use',
'order' => 'desc',
'posts_per_page' => 6
) );
if ( have_posts() ) :
while ( have_posts() ) : the_post();
$usecategory = get_term_by('id', get_field('use_category'), 'usecategory');
?>
<li>
<?php echo get_post_meta($post->ID, 'post_number', true); ?>
<div class="use" style="border-bottom:15px solid <?php the_field('category_colour', $usecategory); ?>;">
<div class="useimage" style="background-image:url(<?php the_field('image'); ?>);">
<?php if (get_field('display_vimeo_video') == 'yes') { ?>
<div class="playicon"><img src="<?php echo bloginfo('template_url'); ?>/images/playicon.png" /></div>
<?php } ?>
</div>
<div class="useinfo">
<div class="usecatimage">
<img src="<?php the_field('category_image', $usecategory); ?>" />
</div>
<div class="usecatandtitle">
<h2 class="usecat"><?php echo $usecategory->name; ?> / Use #</h2>
<h3 class="usetitle"><?php the_title(); ?></h3>
</div>
<div class="usename">
<?php the_field('name'); ?>, <?php the_time('M d'); ?>
</div>
</div>
</div>
</li>
<?php
endwhile;
else :
endif;
?>
</ul>

Wordpress latest posts featured image from category

quick Wordpress question.
I want to display the last 30 posts from my category "photos", but to only display the featured image on the relevant page as a link that will take the user to the actual post.
I have managed to do this, but it displays posts from all categories, not the "photos" category. Code I'm using is below.
I'm sure it's simple, but would love to know how to display just the recent posts from the photo category only (as the featured image).
Thanks
<!-- In functions.php -->
function recentPosts() {
$rPosts = new WP_Query();
$rPosts->query('showposts=100');
while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
<div class="photos">
<li class="recent">
<?php the_post_thumbnail('recent-thumbnails'); ?>
</li>
</div>
<?php endwhile;
wp_reset_query();
}
<!-- this is on the page template -->
<?php echo recentPosts(); ?>
Just add the category selection to your query.
Replace:
$rPosts = new WP_Query();
$rPosts->query('showposts=100');
With:
$rPosts = new WP_Query('category_name=photos&showposts=100');
Reference: http://codex.wordpress.org/The_Loop#Exclude_Posts_From_Some_Category
You need to provide the loop argument that you want post only of certain category by providing category id cat=1. Replace 1 with the id of your photos category
<!-- In functions.php -->
function recentPosts() {
$rPosts = new WP_Query();
$rPosts->query('showposts=100&cat=1');
while ($rPosts->have_posts()) : $rPosts->the_post(); ?>
<div class="photos">
<li class="recent">
<?php the_post_thumbnail('recent-thumbnails'); ?>
</li>
</div>
<?php endwhile;
wp_reset_query();
}
<!-- this is on the page template -->
<?php echo recentPosts(); ?>
Add the category ID to your query arguments. echo on the last line is redundant by the way. Your function outputs the HTML directly rather than returning it.
Finally your original markup was invalid. An li can't be the child of a div so I've corrected that in my example.
function recentPosts() {
$rPosts = new WP_Query( array(
'posts_per_page' => 30,
'cat' => 1
'no_found_rows' => true // more efficient way to perform query that doesn't require pagination.
) );
if ( $rPosts->have_posts() ) :
echo '<ul class="photos">';
while ( $rPosts->have_posts() ) : $rPosts->the_post(); ?>
<li class="recent">
<?php the_post_thumbnail( 'recent-thumbnails' ); ?>
</li>
<?php endwhile;
echo '</ul>';
endif;
// Restore global $post.
wp_reset_postdata();
}
<!-- this is on the page template -->
<?php recentPosts(); ?>

show wordpress posts only under current category

i'm trying to build a navigation for a website, and i'm struggling with it. I'm trying to make a foldable navigation that shows only categories at first, when clicked, they link to the category, and show current category posts only.
I came this far:
<?php
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// Make a header for the cateogry
echo '<h2><a href="./?cat='.$cat->term_id.'">'.$cat->name.'</h2>';
// create a custom wordpress query
query_posts("cat=$cat_id");
// start the wordpress loop!
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php // create our link now that the post is setup ?>
<?php the_title(); ?><br>
<?php endwhile; ?> <?php endif; // done our wordpress loop. Will start again for each category ?>
<?php } // done the foreach statement ?>
The problem with this is: when i fill in the query so that it only takes the current cat, it displays current cat posts on both my categories.
this is what i want for the nav actually:
graphic design
Other Projects
when clicked on graphic design:
graphic design
Project 1
Project 2
Other Projects
when clicking on Other projects:
graphic design
Other Projects
Project 1
Project 2
so basically:
- when clicking from Index page to a category, only that category should expand
- when clicking the other category, the current category changes, so the previous category collapses and the other one expands.
and a bonus: is it possible, that when on a single post, there expands another level of info? for example, a few custom fields per post. like this:
graphic design
Other Projects
Project 1
custom field 1
custom field 2
…
Project 2
thank you very much
Try this code
<?php $article_categories = get_categories(array(
'child_of' => get_category_by_slug('graphic design')->term_id
));
$talentChildren = get_categories(array('child_of' => get_category_by_slug('Project 1')->term_id));
?>
<div id="content" class="narrowcolumn" role="main">
<?php if (have_posts()) : ?>
<div class="post-list">
<?php foreach($talentChildren as $talent): ?>
<?php
$talentSubChildren = new WP_Query();
$talentSubChildren->query(array('category_name' => $talent->slug));
?>
<h2><?php echo $talent->name; ?></h2>
<ul>
<?php while ($talentSubChildren->have_posts()) : $talentSubChildren->the_post(); ?>
<li>
<?php talent_thumbnail(); ?>
<h4>
<?php the_title(); ?>
</h4>
<p><?php the_excerpt(); ?></p>
read on »
</li>
<?php endwhile; ?>
</ul>
<?php endforeach; ?>
<?php if($wp_query->max_num_pages!=1):?>
<div class="pagination">
<?php previous_posts_link('« prev') ?>
<span class="current"><?php echo $wp_query->query['paged']; ?></span>
of <span class="total"><?php echo $wp_query->max_num_pages; ?></span>
<?php next_posts_link('next »') ?>
</div><!-- .pagination -->
<?php endif; ?>
</div>
<?php else : ?>
<h2 class="center">Not Found</h2>
<p class="center">Sorry, but you are looking for something that isn't here.</p>
<?php get_search_form(); ?>
<?php endif; ?>
</div>
Ive gotten a bit further, but i need some help now.
<?php
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= $cat->term_id;
// Make a header for the cateogry
echo '<h2><a href="./?cat='.$cat->term_id.'">'.$cat->name.'</h2>';
// create a custom wordpress query
query_posts("cat=$cat_id"); ?>
<?php if (in_category($cat_id)) { ?>
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php // create our link now that the post is setup ?>
<?php the_title(); ?><br>
<?php endwhile; ?> <?php endif; // done our wordpress loop. Will start again for each category ?>
<?php } else { ?>
<?php } ?>
<?php } // done the foreach statement ?>
So this is working now: it lists the posts per category, if in the current category, else it doesnt show anything.
now what i still want: i want to add something extra within the loop IF i'm on a single page. I have this code:
<?php wp_reset_query(); ?>
<?php if (is_single('84')) { ?>
Yes
<?php } else { ?>
no
<?php } ?>
But that would mean i have to break a query in the middle of a loop. and the is_single thing does not work inside a loop / without the query reset.
I want it looking like this with above code:
Graphic Design
project 1 (for example id=84)
Yes
project 2 (for example id=101)
No
thanks

Resources