0

I have search all google about this. But many of theme show the way to make a new Template Page which you can choose template type for page.

But i want it directly show post title in category by using the functions.php in my theme.

The code is

<?php if ( is_category() ) : ?>
<li>
<h2>News</h2><ul>
<?php
$posts = get_posts('numberposts=-1&orderby=date&order=ASC');
 foreach($posts as $post) :
 ?>

<li>
<a>"><?php the_title(); ?></a>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endif ; ?>

Any suugestions on how to convert it to function for in use in functions.php?

1 Answer 1

0

I'm not sure what your exact approach here is, but the above can be converted easily into a function. I have commented the code so you can follow it. (Requires PHP 5.4 as it uses the short array syntax. Also, I have not included markup, you need to add it as needed)

function category_post_list()
{
    /*
     * Stop function and return null this function is used outside of a
     * a category archive page
     */
    if ( !is_category() )
        return null;

    /*
     * Get the current category ID with get_queried_object_id()
     */ 
    $category_id = get_queried_object_id();
    $args = [
        'cat' => $category_id,
        'nopaging' => true, // The same as posts_per_page => -1
    ];
    $q = new WP_Query( $args );
    while ( $q->have_posts() ) {
        $q->the_post();
        the_title( '<h1 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h1>' );
    }
    /*
     * Very important reset all postdata if a custom query changed it
     */
    wp_reset_postdata();
}

You can then use it as follow

category_post_list();

On the other hand, if you just going to use your category pages as a page to list post titles, you can simply use pre_get_posts to alter the main query accordingly to set the posts per page to -1, which will be more efficient. Add this into functions.php, this code will return all the posts in a category. (Requires PHP 5.3)

add_action( 'pre_get_posts', function ( $q ) 
{
    if ( !is_admin() && $q->is_main_query() && $q->is_category() ) {
        $q->set( 'nopaging', true );
    }
});

You can then just use the default loop in category.php

while ( have_posts() ) {
    the_post();

        the_title( '<h1 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark">', '</a></h1>' );

}

This will give you the same exact effect as the custom function

2
  • Any feedback on this? Apr 6, 2015 at 7:04
  • @Pieter Goosen, please end while loop Sep 17, 2018 at 13:17

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.