0

Is there any hook or filter I can use programmatically to restrict posts displayed in the frontend archives and in the dashboard to posts only from specified author ID's? We've been getting a lot of spam authors lately and I'll like to also try this this approach while trying other means to get rid of spam.

2 Answers 2

0

Yes, you can use the pre_get_posts hook. From the docs:

Fires after the query variable object is created, but before the actual query is run.

In other words, this hook allows you to alter the WP query before it runs, so you can throw in whatever conditionals to suit your needs.

Here is the structure of how you would use this hook with add_action():

// Define your callback for the action
function wpse_modify_original_query($query){
    // Here you can do whatever you want with the $query
}

// Attach your callback to the pre_get_posts action hook
add_action('pre_get_posts', 'wpse_modify_original_query');

You may also combine it with other conditionals to only apply its effect when you need it, like only for archive or admin pages, using is_archive() or is_admin().

For example:

function wpse_modify_original_query($query){
    if(is_archive() or is_admin()){
    // This query is for an archive or admin page, restrict to specific authors
    $query->set('author__in', array(2,4,6)); // Your desired authors ids
    }
}
add_action('pre_get_posts', 'wpse_modify_original_query');

But as you mentioned in your question, just "hiding" posts is not a clean approach to solve your problems with spam. If you provide more information about how those authors are making it to your dashboard we can help you find a better solution.

For example, a good solution would be to verify posts before they get published or at least verifying the first post a new user publishes. If it's a good one then you allow them to keep publishing.

0

Yes, you can use pre_get_posts action to modify the query parameters, for example limit it to only certain authors, before the query is run.

add_action(
    'pre_get_posts',
    function( $query ){

        // Don't change custom queries, only the main one
        if ( ! $query->is_main_query() ) {
            return;
        }
        
        // Add additional conditional checks here as needed

        // Query posts only from auhtors with the following IDs
        $query->set(
            'author__in',
            array( 1, 2, 3, 4, 5 ) // update this
        );
        
    }
);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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