Wagner Moreira
Wagner Moreira

Reputation: 1088

WP: How to get just one post, from one category and show it

Hello guys! Well i have this code, that shows the one post from each category but i need to show just ONE post, and need to set the "name" of category i'm trying this:

    <?php 
$cat_args = array(
  'orderby' => 'name',
  'order' => 'ASC',
  'child_of' => 0
);

$categories =   get_categories($cat_args); 

foreach($categories as $category) { 
    echo '<dl>';
    echo '<dt> <a href="' . get_category_link( $category->name ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>' . $category->name.'</a></dt>';

     $post_args = array(
      'numberposts' => 1,
      'category' => $category->term_id 
    );

    $posts = get_posts($post_args);

    foreach($posts as $post) {
    ?>
        <dd><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></dd>
                <div class="entry">
                            <?php the_content(); ?>
                        </div>
    <?php 
    } 
    echo '<dd class="view-all"> <a href="' . get_category_link( $category->term_id ) . '" title="' . sprintf( __( "View all posts in %s" ), $category->name ) . '" ' . '>View all posts in ' . $category->name.'</a></dd>';
    echo '</dl>';
} 
?>

I then searched the codex and have not found a way to get categories by name, someone can help me??

Upvotes: 0

Views: 208

Answers (1)

Spencer Cameron-Morin
Spencer Cameron-Morin

Reputation: 1430

What you're looking for is get_cat_ID.

Change $post_args to something like this:

$post_args = array(
    'posts_per_page' => 1,
    'cat' => get_cat_ID( 'My Category Name' )
);

Let me know how it goes. :)

Upvotes: 1

Related Questions