How to prevent writing duplicate loops?

Move the control structure outside the template file and just put the repeatable markup and template tags inside. $event_query = new WP_query($args); if( $event_query->have_posts() ){ while( $event_query->have_posts() ){ $event_query->the_post(); get_template_part(‘loop’, ‘home’); } } wp_reset_postdata();

Why do I get `Call to a member function have_posts() on a non-object `? [closed]

Change if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); to if ( $the_query->have_posts() ) : while ( $the_query->have_posts() ) : $the_query->the_post(); Why? When you call $the_query = new WP_Query($query); you’re storing the loop in a variable called $the_query. $query is an array of arguments that you’re passing to the new WP_Query() function. … Read more

How to check if “is single” page

You can use is_singular() with post types like this: if( is_singular(‘event’) ) { // We are in single view of event post type } So, your code could be: add_filter( ‘the_title’, ‘event_page_title’ ); function event_page_title( $title ) { if ( is_singular( ‘event’ ) ) { $title = “Title: ” . $title; } return $title; }

Can I use both a custom excerpt and a trimmed excerpt?

We can try to filter the excerpt through the get_the_excerpt filter. By default, if we have a manual excerpt, the manual excerpt will be used and not the automatically created excerpt which is created by the wp_trim_excerpt() function. We can alter this behavior. What we will do is, when we are inside the main query … Read more

Make a custom loop inside single.php with pagination

As I far I know, get_posts() function can not be used to paginated results. It is intended to get an array of posts and it sets no_found_rows to true by default from WP 3.1. Pagination won’t work unless you set it to false, or better, use WP_Query. numberposts is also a invalid argument. $paged = … Read more

Does get_template_part pull data once in a loop?

get_template_part() calls locate_template(), and both functions are running file_exists() checks for the same file over and over. There is no caching. Meh. But … PHP has an internal cache for file look-ups, so a direct file access will not happen on every call. There is an edge case, most developers aren’t aware of: A file … Read more

Loop on front-page.php

This is how you would do it. You’re loop is based on being in an archive or index page. (or home) $args = array( ‘posts_per_page’ => 3, ‘post_type’ => ‘post’, //choose post type here ‘order’ => ‘DESC’, ); // query $the_query = new WP_Query( $args ); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); get_template_part(‘loop’); … Read more