OptionTree: Display Posts From Selected Category in Theme Options

Last updated on: August 4th, 2015

Themes with multiple post sections with WP_Query is quite common these days specially it is used a lot in magazine an news wordpress themes. In this tutorial you will learn how to display posts from specific categories with WP_Query and then using OptionTree’s “Category Select” option type to create an option in theme option page to let user select a category from which you want to display posts in that particular section of posts.

Take a look at the loop code below. Line 1-3 is a standard OptionTree output code to display input value and then in the loop below in line 11, you can see the input value variable “$fcat1” which will filter posts and display it in specified location.

<?php if ( function_exists( 'ot_get_option' ) ) {
  $fcat1 = ot_get_option( 'featured_section_1_category' );
} ?>

$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;
// args
$args = array(
	'posts_per_page' => 1,
	'post_type'=> 'post',
	'cat' => $fcat1
// get results
$the_query = new WP_Query( $args );
// The Loop

  <?php if( $the_query->have_posts() ): ?>

    <?php $adcounter = 0; ?>
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>

<p class="section-cat"><?php the_category( ', ' ) ?></p>
<h2 class="section1title"><a href="<?php the_permalink(); ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h2>

<?php endwhile; ?>

// clean up after our query

<?php endif; ?>
<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>

This option is for wordpress themes that have multiple sections of posts from different categories on home page or any other section of the theme. I hope you guys found this tutorial useful. Please comment below if you’re stuck somewhere, i’d be happy to help as much as i can.