There is a multitude issues wrong with the above. For one, post_parent
in the query arguments needs to be an integer. You’re assigning it a string. A number of your calls to wordpress functions, such as the_excerpt()
and wp_reset_query()
are missing ending semicolons. $atts
is an associative array of attributes for the shortcode. If you want to use attributes, they need to be extracted in the shortcode function. There is no need to pass them to the looping function, especially in the light of you not having extracted them beforehand. Also, you’re not even attempting to use them in it anyway.
Further I don’t see why you’d want to separate it into two functions. And I wouldn’t include direct markup in functions and use ob_get_clean
either, but echo
or return
the desired result directly. The latter two are more or less personal preferences.
That being said, this will do what you want:
function andrew_loop_shortcode( $atts ) {
extract( shortcode_atts( array(
'parent' => 8,
'type' => 'page',
'perpage' => 4
), $atts ) );
$output="<div class="clear"></div><div class="childs grid_12">";
$args = array(
'post_parent' => $parent,
'post_type' => $type,
'posts_per_page' => $perpage,
'sort_column' => 'menu_order'
);
$andrew_query = new WP_Query( $args );
while ( $andrew_query->have_posts() ) : $andrew_query->the_post();
$output .= '<div id="service-hp">'.
get_the_post_thumbnail('home-thumb').
'<h2 style="margin-bottom:5px">'.
get_the_title().
'</h2>'.
get_the_excerpt().
'<a class="read-more" href="'.
get_permalink().
'">en savoir plus <img src="'.
get_bloginfo( 'template_url' ).
'/images/read-more.png"></a></div><!-- ends here -->';
endwhile;
wp_reset_query();
$output .= '</div>';
return $output;
}
add_shortcode('andrewloop', 'andrew_loop_shortcode');
Lines 2 – 6 of the above are not strictly necessary, but add to the functionality of your shortcode.
If you simply use [andrewloop]
in a page now, it will display what you are currently aiming at. To only achieve that, you could set the query arguments statically in the shortcode function. With lines 2- 6 however, those are now the default values of the shortcode but they are changeable on the fly without modifying the function again.
With the above, you can now use [andrewloop parent="6" perpage="3"]
for instance. The shortcode can thus be used for multiple different queries.
Further reading, in case you care: