How to programmatically assign a WordPress author to post on pageview

Facebook
Twitter
LinkedIn

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] );
		} 			
	}
});

Matt Pramschufer is a seasoned technology expert and co-founder of E-Moxie, where he specializes in transforming visionary ideas and business goals into thriving online ventures. With over two decades of experience in website design, development, and custom application creation, Matt understands that success requires more than just a visually appealing website or a well-built app. He combines proven methodologies with the latest internet technologies to deliver digital solutions that not only look great but also drive measurable growth.

Related Posts