Search code examples
phpwordpressposts

WordPress custom posts section


I'm trying to create an extra content area that is similar to the default posts WordPress provides. My outcome is to loop these posts on a page without needing WordPress default posts as they will be used for my blog.

I've setup the admin area to create posts and it's displayed into my theme but I'm having trouble. It's only displaying the recent post, instead of looping all posts

I used a guide that helped me build this. adding editable areas which may help you guys understand.

Anyone know how to fix it, so it displays all posts, not just the most recent?

my code so far:

example-page.php

<p>   
  <?php $content_block = new WP_Query(array('post_type'=>'content-block', 
  'posts_per_page'=>10, 'content-position'=>'about-bottom'))?>
  <?php if($content_block->have_posts()): $content_block->the_post(); ?>
  <?php the_content();?>
  <?php endif; ?>
</p>

functions.php

function initialize_content_blocks()  {
  register_post_type('content-block', array(
    'labels' => array(
      'name' => 'Page Content ',
      'singular_name' => 'Content Block',
      'add_new_item' => 'Add New Content Block',
      'edit_item' => 'Edit Content Block',
      'new_item' => 'New Content Block',
      'view_item' => 'View Content Block',
      'search_items' => 'Search Content Blocks',
      'not_found' => 'No content_blocks found',
      'not_found_in_trash' => 'No content blocks found in Trash',
      'view' => 'View Content Block'
    ),
    'publicly_queryable' => false, 
    'exclude_from_search' => true,
    'public' => true,
    'rewrite' => false, 
    'supports' => array('title', 'editor'),
    'taxonomies' => array()
  ));

  register_taxonomy('content-position', array('content-block'), array(
  'rewrite' => false,
  'labels' => array(
    'name' => 'Content Positions',
    'singular_name' => 'Content Position',
    'search_items' => 'Search Content Positions',
    'popular_items' => 'Popular Content Positions',
    'all_items' => 'All Content Positions',
    'edit_item' => 'Edit Content Position',
    'update_item' => 'Update Content Position',
    'add_new_item' => 'Add New Content Position',
    'new_item_name' => 'New Tag Content Position'
  ),
  'show_tagcloud' => false,
  'hierarchical' => true
));

}
add_action('init', 'initialize_content_blocks');

Solution

  • Yes, you missed the actual looping. And it is also good to reset your custom query. Add wp_reset_postdata() after your code.

    $content_block = new WP_Query(array('post_type'=>'content-block' ... ));
    
    if( $content_block->have_posts() )
    {
        while( $content_block->have_posts() )
        {
            $content_block->the_post();
            the_content();
        }
    }
    
    wp_reset_postdata();