I'm building a WordPress plugin that uses dummy pages to display data fetched from an API.
The setup is relatively simple. I have a rewrite rule for the URLs that the plugin wants to work on, and when I hit specific query_vars I launch a dummy page.
public function __construct() { require_once plugin_dir_path(__FILE__).'vendor/autoload.php'; add_action('init', [$this, 'rewrite_rule'], 1); // add query vars add_action('query_vars', [$this, 'add_query_vars_filter'], 1); // virtual page init add_filter('the_posts', [$this, 'virtual_page'], 1); } public function virtual_page($posts) { global $wp, $wp_query; if (!empty(get_query_var('plugin'))) { $plugin = get_query_var('plugin'); } if (!empty($plugin)) { $post = new stdClass(); $post->post_author = 1; $post->post_name = 'lorem ipsum'; $post->guid = get_bloginfo('wpurl').'/'; $post->post_title = 'title'; $post->post_content = 'content'; $post->ID = -999; $post->post_type = 'page'; $post->post_status = 'static'; $post->comment_status = 'closed'; $post->ping_status = 'open'; $post->comment_count = 0; $post->post_date = current_time('mysql'); $post->post_date_gmt = current_time('mysql', 1); $posts = NULL; $posts[] = $post; $wp_query->is_page = true; $wp_query->is_single = false; $wp_query->is_singular = true; $wp_query->is_home = false; $wp_query->is_archive = false; $wp_query->is_category = false; unset($wp_query->query["error"]); $wp_query->query_vars["error"] = ""; $wp_query->is_404 = false; remove_filter('the_content', 'wpautop'); remove_filter('the_excerpt', 'wpautop'); return $posts; } }
This code does what is expected, which is to display a dummy page with the content I need, but I get a warning in PHP 8.0:
"Attempt to read property "post_type" on null"
I believe the order of execution here is wrong because I'm getting empty $post and $wp_query in xdebug. My guess is that the virtual page function is executed too early.
I tried debugging this issue for a long time but unfortunately I lacked backend/WordPress knowledge.
If anyone can help, I would be more grateful.
P粉0020233262024-01-17 10:01:10
If you try to use virtual pages in WP 6.1, you will no longer have a post ID. This line causes it to break.
$post->ID = -999;