Eli
Eli

Reputation: 1276

How to post a certain post category in a selected wordpress page using post ID or page permalink?

I have created a news dispatches post category. I also created a news releases page, this is the page where I want to show my news dispatches post category posts. How can I show my news dispatches posts in news releases page using post ID or using page permalink in a query? Here is my example code.

add_action('pre_get_posts', 'ad_filter_categories');

   function ad_filter_categories($query) {
      if ($query->is_main_query() && is_home()) {
      $query->set('category_name','news dispatches');
   }
  }

How can I replace the is_home code line with the page/post ID or the page permalink? Thanks for the help.

Upvotes: 0

Views: 101

Answers (1)

manishie
manishie

Reputation: 5322

Can't use is_page in pre_get_posts (see http://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts).

So in the news releases page, add this in:

// Modify the page query
query_posts( 'category_name=news-dispatches');    

// The Loop
if ( have_posts() ) {
    echo '<ul>';
    while ( $have_posts() ) {
        the_post();
        echo '<li>' . get_the_title() . '</li>';
    }
    echo '</ul>';
} else {
    // no posts found
}
/* Restore original Post Data */
wp_reset_postdata();

UPDATE: To answer this question: "What php file I am gonna look into to insert this code? ":

It's hard to give exact instructions because it really depends on how your theme is setup.

You need to create a page called page-news-releases.php. See http://codex.wordpress.org/images/1/18/Template_Hierarchy.png for an explanation of page templates. So when wordpress shows the page with the slug news-releases, it will use this file instead of the default.

You'll put my code in this new page for the main loop. You'll also need to look at your other theme files and copy code that needs to go before and after it (for your header and footer and that sort of stuff). It's a little out of the scope of stackoverflow to teach wordpress template design, but hopefully this will get you started. Good luck!

Upvotes: 1

Related Questions