Using "dt_push_post" filter results in code being ran 2 to 8 times
I "solved" distributing related post that are saved in custom meta fields data als post_id's or an array of post_id's.
I'm parsing the post_content to find post_id's in ACF Blocks or checking custom field meta data. When needed I'm pushing a related post and then find this related post in the destination connection site.
But... I noticed that my code is ran multiple times, which is quite resource full. e.g. I logged this action, dt_push_post, here which with Ray and saw my debug info being triggered 6 times. https://github.com/burovoordeboeg/distributor-meta-data/blob/master/src/InternalConnections/BlockMeta.php#L26
I tried adding checks like doing_ajax, run the on save_post or even the wp_ajax_dt_push action... but no luck in getting the amount of triggeres down.
Do you have a tip / pointer to help?
Nothing stands out to me at first glance from the code you provided. I guess my main question is are you testing pushing to a single connection? In theory, the dt_push_post action should only be fired once for each connection that has been selected. If you're pushing to multiple connections, it will run once for each connection.
I will record a screencapture with some extensive debug information.
Thank yor for the quick reply!
Ok, I found out that I filtered dt_push_post_args after I booted this logic on the plugins_loaded hook.
Then it gets run a lot.
Now I only use the dt_push_post_args filter when hooked triggered from the save_post.
add_action( 'save_post', function( ){
// Remove filters and slashes to the content
( new InternalConnections\PostContent( ) )->register_hooks();
// Migrate post_ids in Post located in (ACF) custom meta fields
( new InternalConnections\PostMeta() )->register_hooks();
// Migrate post_id's in Block located in the_content
( new InternalConnections\BlockMeta() )->register_hooks();
});
Now it only runs once.
If I don't do the Post ID check, it runs:
A. once for the time the Origin post gets saved and
B. once for then the Destination post is saved via wp_post_insert in the Connection class.
To be complete, for a test, I added do_action('jaime') to NetworkSiteConnection->push() method and hooked my logic to that hook. My code was triggerd 6 times...
add_action('jaime', function() {
add_filter( 'dt_push_post_args', [ $this, 'prepare_post_content' ], 4, 10 );
});
I'm using https://github.com/spatie/ray to log everything.
Just reduced it to running 1 time.
I had a old redundant call still that initialized my logic on init. Now that it's gone, everything is just called once.
So any dt_push_post_args I'm doing is run once by hooking it into save_post without any extra checks.
@jmslbam thanks again for the continued research and sharing results on this, it's extremely helpful!