• I am having an issue that when I call wp_insert_post() the cache for my CPT is not cleared. So when I call get_posts() the newly inserted post is missing.

    After some help from Facebook, I found the cache_results and update_post_meta_cache settings in the query arguments and that fixes my problem, but it’s not particularly efficient since I only do about 12 to 15 inserts a day.

    What I am wondering is if calling wp_cache_flush() after each insert would be more efficient… or if there is a way to specifically target the one CPT to flush its cache after each insert.

Viewing 5 replies - 1 through 5 (of 5 total)
  • Dion

    (@diondesigns)

    You can hook on transition_post_status. If the new status is “publish”, and the post type is your custom post type, your handler can call wp_cache_flush().

    Thread Starter Dave Navarro, Jr.

    (@dnavarrojr)

    How is that any different than just alling wp_cache_flush() after wp_insert_post()? Seems more complicated.

    Dion

    (@diondesigns)

    Hooking on transition_post_status will flush the cache correctly even if the post was scheduled to be published at a later date/time, or if you edit the post in the future. Since I have no idea how you are calling wp_insert_post(), or whether the post will be edited in the future, I provided the foolproof solution.

    Moderator bcworkz

    (@bcworkz)

    Another advantage of transition_post_status action is the post object is passed to your callback, so you can choose to do nothing unless the post type you are concerned about is passed.

    If you only need to target a specific status of a specific post type, you can use the dynamic action "{$new_status}_{$post->post_type}". If you are only concerned with the publish status of the “product” post type for example, the action hook would be publish_product.

    These can be a little more complicated to setup, but in the end they are a lot more efficient. Blindly flushing after every insertion can add up to a lot of additional queries that caches were supposed to prevent.

    Thread Starter Dave Navarro, Jr.

    (@dnavarrojr)

    In this case, it’s a CPT created by a form and is always published. Literally the only time I’d need to clear the cache is when it’s created. No other cases…

    But thanks! Much appreciate your advice and time.

Viewing 5 replies - 1 through 5 (of 5 total)
  • The topic ‘Issue with WordPress database caching’ is closed to new replies.