0

I am really a newbie in Wordpress and php. I created a theme for my website as follows:

enter image description here

I think my question is clear: in wordpress admin page I have four categories: 1,2,3,4. I want last 2 posts in category 1 to be displayed in section (div) 1 (shown above), last 2 posts in category 2 to be displayed in section (div) 2, and so on.
As I said, I am novice and I faced a tons of functions in Wordpress documentation.
for example I used the code below inside index.php (of my custom theme) in section 2 which outputs: "Sorry, no posts matched your criteria."

   <?php 
                    $args = array( 'post' => 'post', 'posts_per_page' => 1,'category_name'=>'تازه ها');
                    $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>
                    <div class="entry-content">
                    <?php the_content(); ?> 
                    </div>
                    <?php endwhile; ?>
                    <?php wp_reset_postdata(); ?>
                    <?php else:  ?>
                    <p><?php _e( 'Sorry, no posts matched your criteria.' ); ?></p>
                    <?php endif; 
                ?>

Please give a piece of code to do this.

1
  • I changed tag to category in the post and also changed the code, which still fails, though everything seems ok Commented Oct 20, 2014 at 6:38

1 Answer 1

2

This should work:

$posts = get_posts ("cat=1&showposts=2");
if ($posts) 
{
    foreach ($posts as $post):
    setup_postdata($post); ?>
    <h2><?php the_title(); ?></h2>
<?php endforeach;
}

Change cat=1 to the id of each of the four categories.

Sign up to request clarification or add additional context in comments.

5 Comments

How to get id for any category?
Maybe through this? $category_id = get_cat_ID('Category Name');
That would work as well, but if you go to the backend of wordpress and edit the post category the link will be something like http://example.com/wp-admin/edit-tags.php?action=edit&taxonomy=category&tag_ID=1&post_type=post, the tag_ID=1 is the category id.
what do you mean by tag_ID=1 is the category id?
The number 1 is the category id to be used in get_posts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.