WordPress.org

Ready to get started?Download WordPress

Forums

Is ther a Posts in same Category Widget (2 posts)

  1. kilpatrick
    Member
    Posted 5 years ago #

    Ive been doing some searching around for a widget that will detect what category the current post is from and then display the most recent posts from that category in the sidebar.

    I feel pretty certain something like this must exist. A hand in locating it would be appreciated.

  2. Austin Matzko
    Member
    Posted 5 years ago #

    I don't know if there exists such a thing, but here is the code to do it:

    <?php
    
    /*
     Plugin Name: Post Category Widget
     Version: 1.0
     Description: Widget to show a list of posts from the current post's category.
     Author: Austin Matzko
     Author URI: http://www.ilfilosofo.com/
     */
    
    function current_category_widget_list($args) {
    	if ( have_posts() && ( is_single() || is_category() ) ) :
    		the_post();
    		$post_id = get_the_ID();
    		$post_id = intval($post_id);
    		rewind_posts();
    		wp_reset_query();
    		extract($args);
    		$cats = (array) wp_get_post_categories($post_id);
    		$cat_id = ( is_category() ) ? intval(get_query_var('cat')) : intval(array_shift($cats));
    		$r = new WP_Query("cat=$cat_id");
    		if ($r->have_posts()) :
    			echo $before_widget . $before_title . sprintf('Recent Posts in "%s"', get_cat_name($cat_id)) . $after_title; ?>
    				<ul>
    				<?php  while ($r->have_posts()) : $r->the_post(); ?>
    				<li><a href="<?php the_permalink() ?>"><?php if ( get_the_title() ) the_title(); else the_ID(); ?> </a></li>
    				<?php endwhile; ?>
    				</ul>
    			<?php echo $after_widget;
    			rewind_posts();
    			wp_reset_query();
    		endif;
    	endif;
    }
    
    function current_category_widget_list_init() {
    	wp_register_sidebar_widget( 'current-post-category-list', 'Current Category List', 'current_category_widget_list');
    }
    
    add_action('init', 'current_category_widget_list_init');

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.