I just added following code to functions.php.

$my_post = array(
  'post_title'    => 'Test Title 02',
  'post_content'  => 'Test Des 02',
  'post_status'   => 'publish',
  'post_author'   => 1
);

wp_insert_post( $my_post );

There are 8 posts were created just one page load. Seems like functions.php file is called 8 time for just one page load. Why is that? How it happens?

2 Answers
2

Add a plugin like Kint Debugger + Debug Bar and add the following code to your functions.php.

    global $wp;
    ob_start('kint_debug_ob');
    d($wp);
    ob_end_flush();

When you check the Debug Bar you should see the backtrace which will tell you which order functions were fired in. Loading 8 times is quite high for a single request.

There is also a backtrace function you can use that is less detailed if you don’t want to go the plugin route – wp_debug_backtrace_summary.

echo "<!----- BACKTRACE / START ----->";

print_r ( wp_debug_backtrace_summary() );

echo "<!----- BACKTRACE / END ----->";

It is a bit odd to just have a random wp_insert_post in your functions.php so perhaps wrapping your logic in a hook like init could help in the mean time.

There is also a possibility this is not just a single request. heartbeats will ping the backend if you’re in the admin section and It’s possible wp-cron can trigger it to load as well (but I’m not sure).

To double check it all, enable WP_DEBUG_LOG and log the events.

Tags:

Leave a Reply

Your email address will not be published. Required fields are marked *