I wanted to allow users to put custom code to placed in between the wordpress query. say If I create a post query I want display an image in between--eg after 2nd, or after 5th post. is it possible to do with add action? so that with apply action code can be placed inbetween.
I wanted to allow users to put custom code to placed in between the wordpress query. say If I create a post query I want display an image in between--eg after 2nd, or after 5th post. is it possible to do with add action? so that with apply action code can be placed inbetween.
Share Improve this question asked May 17, 2019 at 10:48 user145078user145078 3 |1 Answer
Reset to default 0Yes, absolutely, it is possible.
And here's an example: Use an action and pass the post's position in the loop to the action's callback/function, and let the callback run the conditional and display the image if applicable.
$position = 1; // start at 1
while ( have_posts() ) : the_post();
the_title( '<h3>', '</h3>' );
// Show custom image, if any.
do_action( 'my_loop_custom_image_at_position', $position );
$position++;
endwhile;
Callback: (yes, the conditional could be done in the above loop, but based on your question, I think this is what you're looking for?)
add_action( 'my_loop_custom_image_at_position', function( $position ){
if ( $position > 2 ) {
echo '<img src="https://placeimg/728/90/any" />';
} else { // optional 'else'
echo 'Position is less than 2. So we don\'t show custom image.';
}
} );
PS: In the callback, you can use get_post()
to get the current post's data.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745483686a4629671.html
add_action()
orapply_filters()
anwhere in your PHP/WordPress code. Just determine the proper position based on your specific requirements. – Sally CJ Commented May 17, 2019 at 10:54