• Hi there,

    I am creating a website that integrates a portfolio which uses custom post types, this was done based off of this tutorial.

    So far it is exactly what I am looking for and works great except for one small detail. In order to fetch the posts from the new custom post type the author of the tutorial used the query_posts() codex. So the top of my portfolio page looks like this:

    <?php
    /* Template Name: Portfolio */
    get_header();
    query_posts('post_type=portfolio&posts_per_page=10');
    ?>

    What I gather is that this declares “get posts from “post type” portfolio and show 10 per page”. My problem is that I can’t go get content from my portfolio page. It seems that now my portfolio page only fetches the content from the custom post type, and I can’t use:

    <?php while ( have_posts() ) : the_post(); ?>
      <?php the_content(); ?>
    <?php endwhile; // end of the loop. ?>

    to get content from the actual page.

    Any ideas how I could modify this? I am also still learning so being clear with explanations would be greatly appreciated.

    Thank you!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Thread Starter bouinfrederic

    (@bouinfrederic)

    By the way this is what I am trying to do, I’ve replaced:

    query_posts('post_type=portfolio&posts_per_page=10');

    with:

    add_action( 'pre_get_posts', 'add_my_post_types_to_query' );
    
    function add_my_post_types_to_query( $query ) {
    	if ( is_page( 8 ) && $query->is_main_query() )
    		$query->set( 'post_type', array( 'portfolio' ) );
    	return $query;
    }

    This seems like the right track, but it stills doesn’t work. I’m not getting the posts from my custom post type.

    Hi.

    So you have a page using a page template ‘portfolio’. WordPress will fetch that page from database with its own page content. What you want to do is after page load add the portfolio right?
    So, I would replace the query_posts by a custom query using the WP_Query class:

    $args = array(
    	'post_type' => 'portfolio',
    	'posts_per_page' => 10
    );
    
    $my_portfolio = new WP_Query( $args );

    And then use it as a custom loop:

    // The Loop
    if ( $my_portfolio->have_posts() ) {
    	while ( $my_portfolio->have_posts() ) {
    		$my_portfolio->the_post();
    		echo '<li>' . get_the_title() . '</li>';
    		/* other functions here */
    	}
    }
    /* Restore original Post Data */
    wp_reset_postdata();

    Place this code on the page template in the spot where you’d like to render the portfolio. Keep the existing page loop if you would like to show the page title and content.

    This helped me out a lot. Saved my life. Thanks!

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘query_posts alternative’ is closed to new replies.