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.

  • 2
    You can call add_action() or apply_filters() anwhere in your PHP/WordPress code. Just determine the proper position based on your specific requirements. – Sally CJ May 17 at 10:54
  • @SallyCJ Thank you, how can I be specific to a certain position in the query? any reference pls if possible – Latheesh V M Villa May 17 at 11:45
  • 1
    I've posted an answer. But I'm not very sure if that's what you meant. Let me know, though. – Sally CJ May 17 at 18:27

Yes, 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 );


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.com/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.

  • Thank you, The method is totally clear for me now :) – Latheesh V M Villa May 17 at 18:34
  • You're welcome! :) – Sally CJ May 17 at 19:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.