Dejsa Cocan
Dejsa Cocan

Reputation: 1569

Getting first paragraph of most recent post based on category ID

It's been a while since I've worked with PHP and WordPress, so I am a bit rusty. What I want to do is to display the opening paragraph for the most recent post under a category for a WordPress site. Based on some research I did, I've compiled this piece of code:

<?php
$category_id = get_cat_ID('Downtown News');
$post = get_posts( $category_id );
if( !empty( $post ) ) {
    setup_postdata( $post );
    ?><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
    <?php the_excerpt();
} ?>

<?php
$post = $wp_query->post;
setup_postdata( $post );
?>

I have code to get the category ID I want, and I have the code to display the first paragraph of the most recent article. However, the code does not seem to work. What is displayed is the first paragraph under an "uncategorized" category of postings, which is not what I want. How can I fix what I have so that it gets the correct category?

Upvotes: 0

Views: 206

Answers (2)

Dustin Robinson
Dustin Robinson

Reputation: 1

I had the similar issue with yours, maybe this one will work for you

notice the $category_id gets pulled from get_cat_ID() function, this tells me you do not know the cat_id, you can go to the category where you created the downtown news, move your mouse over it to reveal the url address which it will tell you the category id, find that number and replace the line:

query_posts('cat='.$category_id.'&posts_per_page=1');

(using 99 as an example)

query_posts('cat=99&posts_per_page=1');

<?php
global $post;
$category_id = get_cat_ID('Downtown News');
query_posts('cat='.$category_id.'&posts_per_page=1');
if ( have_posts() ) { 
      ?>
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
      <?php the_excerpt();
}
wp_reset_query();
?>

Upvotes: 0

Yan Foto
Yan Foto

Reputation: 11378

You have started at the right place: get_posts, however you don't have the correct parameters. So try the following out:

<?php 
$args = array(
    'category'         => 'CAT_ID_1,CAT_ID_2',
    'orderby'          => 'post_date',
    'order'            => 'DESC'); 

$posts_array = get_posts( $args );
?>

From the function reference we know that:

The category parameter needs to be the ID of the category, and not the category name

which means that you can have one or more category IDs (comma separated).

A list of all parameters can be found here.

Upvotes: 1

Related Questions