Wordpress latest posts featured image from category - wordpress

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(); ?>

Related

Custom fields in WP and get_pages function

I have in my template-parts file where I created this code to list pages under page with ID=347 (I just wanted to create list of products using template file on one, single page). Code looks like this:
<?php $pages = get_pages(array('child_of' => 347, 'sort_column' => 'post_date', 'sort_order' => 'desc')); ?>
<?php foreach ($pages as $page): ?>
<div class="fw-col-xs-12 fw-col-sm-4 product-box">
<?php echo get_the_post_thumbnail($page->ID, 'large');?>
<div class="fw-heading fw-heading-h3 naglowek-maly"><h3><?php echo $page->post_title; ?></h3></div>
<a class="fw-btn fw-btn-1 button1" href="<?php echo get_permalink($page->ID); ?>" title="<?php echo esc_attr($page->post_title);?>"><span>check more</span></a>
</div><!--product box-->
<?php endforeach; ?>
And now I want to add extra field there using Advanced Custom Fields plugin. I need to display below the small info (it will be product dimensions). So I created custom field and I am able to show field only if I add an ID of this page for example:
<?php the_field('product_dimensions', 200); ?>
How to make it dynamic? I was trying to use simply:
<?php the_field('product_dimensions'); ?>
But nothing shows then. Do I have to add there some extra code to read the ID for each page?
just add $post->ID
the_field('product_dimensions', $post->ID);

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

How to make a page template for displaying custom type posts

I just started WP, and made a table with many rows arrived at WP house. But don't know how to show. basic content well shown but custom fields. learnt that a page have to be created to deal them in order to retrieve custom typed posts.
the following is from my content-movie.php under twentyfourteenchild:
/* translators: %s: Name of current post */
the_content();
// handling movie stuff starts
$p_id = $post->ID;
$ar_fields = array( 'studio','director','starring','grade');
.
.
foreach $ar_fields as $field
$some_field = get_post_custom_values($field, $p_id);
do some thing dealing $some_field...
end for
===================
In order to make a regular page to populate movie-typed custom posts, do I have to put such codes in archive-movie, page-movie single-movie etc ?
I guess, somewhere it can be dealt instead of putting same scripts in many files.
I really want someone to help me go right direction.
firstly create a custom page template by doing the following:
Copy the regular page.php and rename it to page-movies.php.
In the page header add the following php code:
/**
* Template Name: Movie Page
*/
Now the page template should be available in the backend, select the Movie Page as your page template.
Now replace the regular page query with your query, here is an example below:
<?php $args = array( 'numberposts' => 7, 'order'=> 'ASC', 'post_type' => 'movies');
$postslist = get_posts( $args );
foreach ($postslist as $post) : setup_postdata($post); ?>
<div class="item">
<div class="item-content">
<?php if ( has_post_thumbnail() ) : ?>
<div class="thumbnails"> <a class="ajax" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail( 'projects-thumbnail' ); ?>
</a>
<div class="copy">
<h3><a href="<?php the_permalink(); ?> ">
<?php the_title(); ?>
</a></h3>
</div>
</div>
<?php endif; ?>
</div>
</div>
<?php endforeach; ?>
This should do the trick...

Check if Wordpress loop has posts

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.

Make WordPress homepage a post category?

I am trying to set my WordPress homepage to a category but it only allows me to set it to either the latest posts or a static page.
Is it possible to set your homepage as a post category?
I am hoping that you know about how to set static page. So first create an empty .php file and name it whatever you like and put it along the other files (index.php, arhive.php etc).
and then enter following code
<?php
/*
* Template Name: Category based Homepage
*/
?>
<?php get_header(); ?>
<div class="main">
<?php
$cat_ID = '1'; //it should be your category ID, you can get the id of the category by going to categories and edit and then in url you can find the tag_ID.
$posts_to_show = '10'; // number of posts from the category you want to show on homepage
//query_posts("cat=$cat_ID&showposts=$posts_to_show");
$category_posts = new WP_Query("cat=$cat_ID&showposts=$posts_to_show");
//if (have_posts())
if ($category_posts->have_posts())
: $first = true;
?>
<ul class="post-list">
<?php
//while (have_posts()) : the_post();
while ($category_posts->have_posts()) : $category_posts->the_post();
if ($first)
$class = "first-in-row";
else
$class = "";
$first = !$first;
?>
<!-- Start: Post -->
<li <?php post_class($class); ?>>
<?php the_post_thumbnail(); ?>
<p class="categories"><?php the_category(", "); ?></p>
<h2><?php the_title(); ?> <?php edit_post_link(__('Edit', 'your_theme_text_domain'), '', ''); ?></h2>
<p class="post-meta"><span class="date"><?php the_time(get_option('date_format')) ?></span> <?php if (comments_open()) : ?>, <span class="comments"><?php comments_popup_link(_x('0', 'comments number', 'your_theme_text_domain'), _x('1', 'comments number', 'your_theme_text_domain'), _x('%', 'comments number', 'your_theme_text_domain')); ?></span> <?php endif; ?> <span class="author"><?php the_author() ?></span></p>
<?php the_excerpt(); ?>
<p class="more"><?php _e('Read More »» ', 'your_theme_text_domain'); ?></p>
<?php if (has_tag()): ?><p class="tags"><span><?php the_tags(""); ?></span></p><?php endif; ?>
</li>
<!-- End: Post -->
<?php endwhile; ?>
</ul>
<?php else : ?>
<h2 class="center"><?php _e('Not found', 'your_theme_text_domain'); ?></h2>
<p class="center"><?php _e('Sorry, but you are looking for something that isn\'t here.', 'your_theme_text_domain'); ?></p>
<?php
endif;
//wp_reset_query();
wp_reset_postdata();
?>
</div>
<?php get_sidebar(); //optional?>
<?php get_footer(); ?>
and replace $cat_ID and $posts_to_show to your liking. And I have used both query methods adjust it to your needs.
Hope it helps somebody who is looking for similar solution.
You can create a custom template that mimics a category page using get_posts and set a page using that template to home, but it won't be perfectly dynamic in the sense that you have to hard code the category slug or ID into that query. Assuming that you don't want to change that category often, that shouldn't be an issue. Alternatively, you could use wp_safe_redirect in a template to redirect to the category page - that would be if you want the user to be put directly on the real category page, URL and all.
I'm not sure what you mean by having your home page as a category, you mean that in your home page posts that will be displayed will be only from a certain category ?
You only need to perform a WP_Query before the loop;
$query = new WP_Query("cat=10, paged=".get_query_var('paged'));
Then use use the WP_Query object to perform the loop;
if($the_query->have_posts()):
while($the_query->have_posts()):
the_title();
the_content();
//Use all the loop function normally
endwhile;
endif;
The paged parameter is used to determine in which page you are, if you need paginantion.
Instead of using the category id, it is good to retrieve the id by the slug.
$home = get_category_by_slug('home-category-slug');
Then your query will be like this
$the_query = new WP_Query("cat=".$home->cat_ID.", paged=".get_query_var('paged'));
Yes this is possible Go to dashboard>>Setting>>Reading>>Static page Choose page from drop down and SAVE. On that page you can create your own stuff...

Resources