问题的标题不准确。我认为您不想逃避第一篇帖子,而是想排除当前帖子。您可以使用post__not_in
中的参数WP_Query
.
$args = array( \'s\' => \'searchTerm\' );
//Check if we are in a post of any type
if( is_singular() ) {
$post = get_queried_object();
$args[\'post__not_in\'] = array( $post->ID )
}
$query = new WP_Query( $args );
if ($query->have_posts()){
while ($query->have_posts()){
$query->the_post();
//echo the post
}
wp_reset_postdata();
}
UPDATE
当您在ajax请求中使用代码时,您无法访问ajax操作挂钩中的当前post数据。您需要在ajax请求数据中传递当前的post ID。
例如(未测试。仅在此处书写):
//Enqueue the scripts and localize js variables
add_action(\'wp_enqueue_scripts\', \'cyb_scripts\');
function cyb_scripts() {
//register my-script
wp_register_script( \'my-script\', \'/url/to/my-sript.js\', array(\'jquery\') );
//enqueue my-sript and dependencies
wp_enqueue_script(\'jquery\');
wp_enqueue_script(\'my-script\');
//Localize script data to use in my-script. Set here the post ID to exlude
$exclude_post = 0;
if( is_singurlar() ) {
$current_post = get_queried_object();
$exclude_post = $current_post->ID;
}
$scriptData = array(
\'ajaxurl\' => admin_url(\'admin-ajax.php\');
\'exclude_post\' => $exclude_post
);
wp_localize_script(\'my-script\', \'my_script_data\', $scriptData);
}
//Ajax action hooks
add_action(\'wp_ajax_nopriv_process_ajax\', \'cyb_process_ajax\');
add_action(\'wp_ajax_process_ajax\', \'cyb_process_ajax\');
function cyb_process_ajax(){
$args = array( \'s\' => \'searchTerm\' );
//Check for post to exlude
if( isset($_GET[\'exclude_post\']) ) {
$args[\'post__not_in\'] = array( intval( $_GET[\'exclude_post\'] ) );
}
$query = new WP_Query( $args );
//....
wp_reset_postdata();
}
javascript:
jQuery(document).ready(function($){
$.ajax({
type: "GET",
url: my_script_data.ajaxurl,
data: {
action: "process_ajax",
exclude_post: my_script_data.exclude_post
}
})
.done( function( response ) {
//....
})
.fail( function( response ){
//....
});
});