admin管理员组

文章数量:1426594

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
  • 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 Commented May 17, 2019 at 10:54
  • @SallyCJ Thank you, how can I be specific to a certain position in the query? any reference pls if possible – user145078 Commented May 17, 2019 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 Commented May 17, 2019 at 18:27
Add a comment  | 

1 Answer 1

Reset to default 0

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

    $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.

本文标签: add action for wordpress query at a specific position