Reputation: 573
I have a simple function that I need to get all post via category,
I have two categories Uncategorised
with id=1
and bank
with id=6
I have three post, bank
category has 2 and uncategorised
has 1 post.
I have a PHP file as:
cat_post.php
<?php
global $post;
$myposts = get_posts(array(
'posts_per_page' => $noOfPost,
'offset' => 1,
'category' => $categoryName // set cat here
));
echo '<div class="recent-post">';
if ($myposts)
{
foreach ($myposts as $post) :
setup_postdata($post);
?>
<a class="col-xs-3 col-md-2" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('thumbnail'); ?>
</a>
<div class="col-xs-3 col-md-10">
<a class="" href="<?php the_permalink(); ?>">
<h2><?php the_title(); ?></h2>
</a>
<?php the_excerpt() ?>
<a href="<?php the_permalink(); ?>">Read Full</a>
<br>
<a class="" href="<?php comments_link(); ?>">
<?php comments_number('0 Comments', '1 Comments', '% Comments'); ?>.
</a>
</div>
<hr/>
<?php
endforeach;
wp_reset_postdata();
}
echo '</div>';
and I use this PHP file and set the parameters as:
second_page.php
<div class="tab-content">
<div class="tab-pane active" id="banks">
<?php
$categoryName = 6; // sets category
$noOfPost = 5; // no of post
get_template_part('cat_post', get_post_format()); // gets function from cat_post.php
?>
</div>
<div class="tab-pane" id="morebank">
<h2>more content</h2>
</div>
</div>
It is showing two post from different categories, but it should be showing both post from bank category.
Any one know whats I'm doing wrong and why my code is not working as expected?
Thank you.
Upvotes: 1
Views: 154
Reputation: 10809
Try by using global
variable like this:
in cat_post.php
<?php
global $post;
global $categoryName; //access it through a global variable.
$myposts = get_posts(array(
'posts_per_page' => $noOfPost,
'offset' => 1,
'category' => $categoryName // set cat here
));
and set global $categoryName
value in second_page.php
as like this:
...
<?php
global $categoryName;
$categoryName = 6; // sets category
$noOfPost = 5; // no of post
Hope this helps!
Upvotes: 1