0

私は WordPress クエリを実行しようとしてきましたが、かなり大きな障害にぶつかりました。投稿をクエリする方法は次のとおりです。

<?php query_posts( 's=@' . $user_login . '&author=-4,-5,-6&posts_per_page=25&paged='. $paged ); ?>

このコードからわかるように、ID が 4、5、および 6 の作成者を除外しようとしています。ただし、WordPress は現在、この機能を許可していません (カテゴリの場合と同様)。

この目標を達成する方法を知っている人はいますか? カスタム クエリ/結合でしょうか? どんな助けでも大歓迎です!

4

3 に答える 3

0

WordPress currently doesn't support removing multiple author posts from the query at a time.

But we can make use of another hook posts_where to remove the authors we do not need. But if we use this hook it will affect all the places in WordPress. So we should be careful when hooking this filter.

If you add it in the functions.php file it will run throughout all the queries which have post_where hook.

Add this function in your functions.php of the theme.

function remove_author_posts ($where) {
    global $wpdb; 

    //add the author id's you need to remove
    $removed_authors   = array ('4', '5', '6');

    $where .= ' AND ' .  $wpdb->posts . '.post_author !=' . implode(' AND ' .  $wpdb->posts . '.post_author !=', $removed_authors);
    return $where;
}

Now add this filter to the place where you are calling the query_posts

add_filter ('posts_where', 'remove_author_posts');

Don't add this filter hook in your themes functions.php file. Only add in the place you need.

Now change your query posts and add the filter in the page you need like this:

query_posts( 's=' . $user_login . '&posts_per_page=25&paged='. $paged );

So the complete thing will look like

add_filter ('posts_where', 'remove_author_posts');
query_posts( 's=' . $user_login . '&posts_per_page=25&paged='. $paged );

UPDATE :

You can use global variable if you need to change the author id's dynamically. Add a new global variable $remove_authors before you add the filter.

global $removed_authors ;
//add the author id's you need to remove
$removed_authors   = array ('4', '5', '6');

add_filter ('posts_where', 'remove_author_posts');
query_posts( 's=' . $user_login . '&posts_per_page=25&paged='. $paged );

Now change the remove_author_posts in functions.php file

function remove_author_posts ($where) {

    global $wpdb, $removed_authors;

    if (empty ($removed_authors) || !is_array($removed_authors))
        return $where;

    $where .= ' AND ' .  $wpdb->posts . '.post_author !=' . implode(' AND ' .  $wpdb->posts . '.post_author !=', $removed_authors);

    return $where;
}

Hope this helps you :)

于 2013-04-01T19:01:34.850 に答える