Child-theme post-randomizing PHP interferes with WP Site Health
-
I use the posts page of a portfolio site to display work samples. I developed the site back in 2017.
Displaying samples in chronological order made no sense, so I wanted to randomize them.
At the suggestion of my theme developer, I added code to my child theme. The initial suggestion had the (negative) effect of randomizing the posts in the Dashboard as well, which made it difficult to find specific posts to edit. The developer recommended the following, which I added instead:
function tu_rand_posts( $query ) { if ( $query->is_main_query() && ! is_admin() ) { $query->set( 'orderby', 'rand' ); } } add_action( 'pre_get_posts', 'tu_rand_posts' );
To avoid seeing repeats when I use the “Continue” button to scroll past the first batch that loads, I also added the following code to my child theme:
session_start(); add_filter('posts_orderby', 'edit_posts_orderby'); function edit_posts_orderby($orderby_statement) { $seed = $_SESSION['seed']; if (empty($seed)) { $seed = rand(); $_SESSION['seed'] = $seed; } $orderby_statement = 'RAND('.$seed.')'; return $orderby_statement; }
Unfortunately, that second set of code now creates another problem: It interferes with Site Health in WordPress. (The “session_start” was the clue.)
“An active PHP session was detected,” Site Health reports, among other things, chiding me for “critical information about your WordPress configuration and items that require your attention.”
My question is pretty simple: Does WP do a better job of randomizing post display than it did in 2017? Can I remove any of this code from my child theme without losing the ability to randomize posts without repeats?
[ETA: WP 5.5, theme and all plug-ins up to date.]
The page I need help with: [log in to see the link]
- The topic ‘Child-theme post-randomizing PHP interferes with WP Site Health’ is closed to new replies.