Wordpress - Query for custom post type?
query_posts( array( 'post_type' => array('post', 'portfolio') ) );
which shows both normal posts and posts inside portfolio
type
or
query_posts('post_type=portfolio');
for only portfolio
.
Use as normal WP Query - read the Codex: http://codex.wordpress.org/Function_Reference/query_posts#Usage and http://codex.wordpress.org/Function_Reference/query_posts#Post_.26_Page_Parameters
<?php
query_posts(array(
'post_type' => 'portfolio',
'showposts' => 10
) );
?>
<?php while (have_posts()) : the_post(); ?>
<h2><a href="<?php the_permalink() ?>"><?php the_title(); ?></a></h2>
<p><?php echo get_the_excerpt(); ?></p>
<?php endwhile;?>
Late answer as the main answer uses query_posts()
, which should never be done.
Use a filter
Use the pre_get_posts
filter and just set the portfolio
post type for the main query. Use Conditional Tags to determine where you want to have this filter.
Quick Example
<?php
defined( 'ABSPATH' ) OR exit;
/* Plugin Name: (#6417) "Portfolio" post type in query */
add_filter( 'pre_get_posts', 'wpse_6417_portfolio_posts' );
function wpse_6417_portfolio_posts( $query )
{
if (
! $query->is_main_query()
// Here we can check for all Conditional Tags
OR ! $query->is_archive() // For e.g.: Every archive will feature both post types
)
return $query;
$query->set( 'post_type', array( 'post', 'portfolio' ) );
return $query;
}
Disclaimer
The above code is a plugin, but can simply get stuffed in the functions.php
file of your theme (which is not recommended).
Add this code to your child themes functions file (recommended) to add your single CPT pages to your main loop
add_action( 'pre_get_posts', 'add_custom_post_types_to_loop' );
function add_custom_post_types_to_loop( $query ) {
if ( is_home() && $query->is_main_query() )
$query->set( 'post_type', array( 'post', 'portfolio' ) );
return $query;
}
Source http://codex.wordpress.org/Post_Types
Or create a custom archive-portfolio.php page template which will only display your CPT pages. This only needs to be done if you haven't added a archive page using the plugin settings.
Example: 'has_archive' => true,
You can also control how many pages are displayed and the order in which they're displayed on the archive page using this code:
add_action( 'pre_get_posts', 'cpt_items' );
function cpt_items( $query ) {
if( $query->is_main_query() && !is_admin() && is_post_type_archive( 'portfolio' ) ) {
$query->set( 'posts_per_page', '8' );
$query->set( 'order', 'ASC' );
}
}