Creating a related posts section in wordpress - wordpress

I'm trying to create a related post section in my wordpress custom theme. The objective here is if the user views a post to a certain category it will also show all the post from that category below. I have attached an image below.
http://i255.photobucket.com/albums/hh140/testament1234/relatedposts_zpsa830adfc.jpg
How do i achieve this? Do i use wp_query just like this?
<?php query_posts('cat=6', 'posts_per_page=-4=-'); if(have_posts()) : while(have_posts()) :the_post(); ?>
The code above sets what category it obtains the post. 'cat'
Solution of kwncc
<div id="post-container" class="eleven columns alpha omega post">
<?php $postCategories = ''; while ( have_posts() ) : the_post(); ?>
<h2 class="post-title"><?php the_title() ?></h2>
<?php setPostViews(get_the_ID()); ?> <!-- Set Post Views -->
<ul class="meta-icons-large">
<li id="meta-author-large"><span><?php the_author_posts_link() ?> /</span></li>
<li id="meta-categories-large"><span><?php the_category(', ') ?> /</span></li>
<li id="meta-comments-large"><span><?php comments_number() ?> /</span></li>
<li id="meta-date-large"><span><?php the_time('F jS, Y') ?> /</span></li>
<li id="meta-views-large"><span><?php echo getPostViews(get_the_ID()); ?></span></li> <!-- Display Post Views -->
</ul>
<?php the_content(); ?>
<?php endwhile; ?>
</div>
<div id="related-posts-container" class="eleven columns alpha omega related-post">
<h2>related posts</h2>
<?php $postCatIds = ''; foreach($postCategories as $catIndex => &$catValue){
$postCatIds .= $category->cat_ID; if( $catIndex < (count($postCategories)-1)){ $postCatIds .= ', ';
}
}
?>
<?php query_posts('cat='.$postCatIds, 'posts_per_page=4'); if(have_posts()) : while(have_posts()) { the_post(); } ?>
<div id="related-post-thumbnail-container" class="three columns alpha related-posts">
<h3><?php the_title(); ?></h3>
</div>
<?php endwhile; endif; wp_reset_query();?>
</div>
<div id="comments-container" class="eleven columns alpha omega comments">
<?php comments_template('', true); ?>
</div>
</div>

I'd suggest you don't load related posts on page load because this will dramatically hurt your website's performance.
The free WordPress plugin Related Posts for WordPress automatically finds related posts (amongst others based on title) and caches them for you, offering you real related posts without hurting your website's performance. After the automatic linking is done you can, if required, manually add, edit or delete related posts. The plugin also comes with template tags so you can display the related posts anywhere in your custom theme you want. Simply use rp4wp_children() in your theme where you want the related posts to be displayed.
You can give it a try via the WordPress.org repo: http://wordpress.org/plugins/related-posts-for-wp/

This page consists of 2 different loops:
1. for the main content - article of the post
2. for the related posts.
For the first part, you have just to include the loop. In addition, since you want to find the related to this article posts you have to also get the current post categories.
PHP code:
$postCategories = '';
if(have_posts()) : while(have_posts()){
the_post();
$postCategories = get_the_category();
...
}
Then for the second part where you want to include the related posts you can get the category IDs related to the current post and create the query you need.
// get comma separated category IDs
$postCatIds = '';
foreach($postCategories as $catIndex => &$catValue){
$postCatIds .= $category->cat_ID;
if( $catIndex < (count($postCategories)-1)){
$postCatIds .= ', ';
}
}
//query the related categories posts
query_posts('cat='.$postCatIds, 'posts_per_page=4');
if(have_posts()) : while(have_posts()) {
the_post();
...
}
Hope that helps!

Related

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

Custom templates, custom post type, and single page problems

I have set up a custom post type for a few sub sections of the website I am currently working on in wordpress. I need the custom post types to feed onto a template (which I have working) but I have a few questions and non working things. The read more link is not working, as in not showing up at all even? Also when I click the title links n the posts to go to the full post, they go to the correct url but there is no content in the body. I'm thinking I need to add more in the custom template.
Here is the template code :
<?php
/* Template Name:News */
?>
<?php get_header(); ?>
<div class="decade1">
<ul id="news_list">
<?php global $post; query_posts( 'post_type=news&orderby=ID&order=desc' ); while (have_posts()) : the_post(); ?>
<li>
<div class="fea_del">
<h2><?php the_title(); ?></h2>
<p><?php the_field('post_content',$post->ID); ?></p>
<a <?php $p=get_permalink( $post->ID ); ?> href="<?php echo $p; ?>" class="entire_job">Read More</a>
</div>
</li>
<?php endwhile; wp_reset_query(); ?>
</ul>
</div>
<?php get_footer(); ?>
The most important issue is the posts not showing up on their individual pages. Thanks!!

Wordpress homepage with latest posts and Advanced Custom fields - How?

I'd like my homepage to display my latest posts which are portfolio projects of mine. Beneath these project thumbnails I've got my static content which I'm using the Repeater add-on from Advanced Custom Fields to grab. I cant get it all to work on the same page... either get the blog to work or the ACF stuff to work. Never both because one needs to be a designated static page and one needs to be a posts page. I don't understand how to tie it together and make it appear as one page.
I've experimented with the settings in the reading panel..
I've tried using front-page.php
I've read up on the WP hierarchy etc
I've tried using templates...
I've tried wp_reset_postdata(); which I read about elsewhere on Stack Overflow.
What settings must I use in the reading panel. Do I need to use a template file?
Here's the code I'm working with, I've split the code between templates and different files already, but just for ease of reading its all together here (maybe that's the right way to do it anyway, I wouldn't know..)
<!-- The posts/portfolio items -->
<?php get_header(); ?>
<div>
<?php if(have_posts()) : ?>
<ul>
<?php while ( have_posts() ) : the_post(); ?>
<li>
<!-- Permalink,title and post thumbnail here (omitted) -->
</li>
<?php endwhile; ?>
</ul>
<?php else: ?>
<h2>No Posts found</h2>
<?php endif; ?>
</div>
<!-- Now for the ACF Stuff -->
<?php if(get_field('care_list')): ?>
<?php while(has_sub_field('care_list')): ?>
<div class="grid_2 what-i-care-about gap">
<div class="important-img-container">
<?php the_sub_field('care_list_image'); ?>
</div>
<h3><?php the_sub_field('care_list_title'); ?></h3>
</div>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>
Please help a frustrated learner! Thanks in advance.
It looks like you're going to need to add the post id of your 'home page' (the one with the ACF repeater on it) to the get_field() function like so:
<?php $post_id = **post_id_of_your_homepage_here**; ?>
<?php if(get_field('care_list', $post_id)): ?>
<?php while(has_sub_field('care_list')): ?>
<div class="grid_2 what-i-care-about gap">
<div class="important-img-container">
<?php the_sub_field('care_list_image'); ?>
</div>
<h3><?php the_sub_field('care_list_title'); ?></h3>
</div>
<?php endwhile; ?>
This is because the $post_id parameter defaults to the current post being brought up by wordpress, which means ACF is looking for the repeater on the last Portfolio item/post you are displaying. If you set the $post_id parameter to the ID of your homepage, ACF will instead look for the repeater on that page.
Source: http://www.advancedcustomfields.com/resources/functions/get_field/#parameters
If I'm understanding correctly, you have a bunch of posts and you want to display a list of them with title and post thumbnail on your homepage, and then display a custom field you've assigned to the homepage underneath the list of posts?
Step 1: Create a new page template by copying page.php, changing the name to homepage.php and adding this to the top:
<?php
/*
Template Name: Homepage
*/ ?>
Step 2: Crete a Wordpress page called "Homepage" and in the attributes module in the right sidebar of the page creation tool, select "Homepage" as your page template.
Step 3: In your reading settings, change the front page from posts page to "Homepage." Now your homepage is your page called "Homepage."
Step 4: Make something like this the full code on your new page template homepage.php. It will output your posts list followed by your page custom field:
<?php get_header(); ?>
<?php $the_query = new WP_Query( $args );
<?php if ( $the_query->have_posts() ) : ?>
<?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><?php the_title(); ?></h2>
<?php the_post_thumbnail(); ?>
<?php endwhile; ?>
<?php wp_reset_postdata(); ?>
<?php endif; ?>
<?php if(get_field('repeater_field_name')): ?>
<?php while(has_sub_field('repeater_field_name')): ?>
<?php the_sub_field('sub_field_1'); ?>
<?php endwhile; ?>
<?php endif; ?>
<?php get_footer(); ?>

Pull latest posts from a specific category

I am trying to pull latest posts from a specific category.
I am currently able to pull all latest posts and display them the way I want using the code below but I am unable to do the same thing from a specific category.
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<div id="content"><div id="circle"><div id="circle_text1"><p><?php the_time('M') ?></p></div>
<div id="circle_text2"><p><?php the_time('dS') ?></p></div></div>
<div id="text"><div id="title"><p><?php the_title(); ?></p></div>
<div id="name"><p>By <?php the_author(); ?></p></div>
<div id="blurb"><p><?php the_content('<br />Read More'); ?></p></div></div>
<div id="line_rule"><p> </p><hr /></div></div>
<?php endwhile; ?><?php else : ?><h2>Not Found</h2><?php endif; ?>
Thanks in advance
This is a basic WP query that resets itself and can be used multiple times in a template. You can add your html to it. showposts is the number of posts to show; -1 shows all posts.
<?php $my_query = new WP_Query('category_name=mycategoryname&showposts=10'); ?>
<?php while ($my_query->have_posts()) : $my_query->the_post(); ?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>">
<?php the_title(); ?></a>
<?php endwhile; ?>
if you are getting posts from database then use order by ID desc that will show latest post on the top. if ID is auto-incremented. like
select * from posts order by ID desc
I do this all the time. This will work:
Change the cat= number to whatever category ID you want to use.
Add html markup as you please and whatever other content you want to pull.
<?php query_posts('cat=4&order=ASC');
if (have_posts()) : while (have_posts()) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); ?>
In the example I am only grabbing the post content, but you could put in the title, meta-data, etc. The important parts are all here.
Try it out.
Add this line of code above your opening IF statement.
<?php query_posts( 'cat=1' ); ?>
And then change the 1 to match the ID of the category you are trying to display.
:)
You can do that by simply by adding this first line to your code:
<?php query_posts( 'category_name=slug_of_your_category&posts_per_page=10' ); ?>
Replace "slug_of_your_category" with the slug of your category, and "10" with the amount of posts you need.

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