Recently, I faced a scenario where I needed to dynamically set the author of a post based on user interaction when they visited the page. This requirement came up while using the Feedzy RSS aggregator plugin, which restricts author assignment to its premium version. Rather than opting for the premium upgrade just for this functionality, I decided to create a custom solution that would address this specific need.
The code snippet below offers a practical approach to achieving this. It starts by checking if a post belongs to a particular category. If the post is within the specified category, the snippet then assesses whether the current author is the one intended. If not, it updates the post author to the correct one.
<?php
add_action('template_redirect', function(){
if(in_category('nearview-media')){
$author = get_post_field( 'post_author', get_the_ID() );
if($author !== 4){
wp_update_post( ['ID' => get_the_ID(), 'post_author' => 4] );
}
}
});