Adding content before the loop

2019-09-01 02:29发布

问题:

Is there a way to add content before the loop through a WordPress plugin?

Specifically, I'm looking to add HTML to the content area, before the posts (both in post lists AND individual posts)

Here's a screenshot of the ideal placement: http://note.io/1ne3J73

Is this at all possible to work across all themes?

回答1:

This could be tricky simply because every theme differs with how the loop is displayed, however you could create a plugin to use the loop_start action, which is called before the first post of the standard WP loop:

add_action( 'loop_start', 'test_loop_start' );

function test_loop_start( $query ){
    echo 'this is my inserted text';
}

Now using this would display it every single time the loop is called (whether on a page, a post, category page, search page, etc.), which you may not want. So you could fine tune it with is_category(), is_archive(), is_singular(), etc. (basically any of the built in WP functions that can help identify what kind of page the user is on):

add_action( 'loop_start', 'test_loop_start' );

function test_loop_start( $query ){

    if(is_category() OR is_singular()) { 
    echo 'this is my inserted text';
    }
}