3

Context: In a social sharing plugin that I work on, I'm store social share counts in hidden post meta (custom fields) so that I can use that data for various functions around the plugin.

One useful use of this data is to create a Popular Posts widget that is based on the number of social shares that a post has. I use a query with the following arguments to accomplish this:

Example Code:

        $swp_args = array(
            'posts_per_page'    => $count,
            'post_type'         => 'post',
            'meta_key'          => '_' . $network,
            'orderby'           => 'meta_value_num',
            'order'             => 'DESC',
        );
        $swq = new WP_Query( $swp_args );

Where $count is a valid integer and $network is a valid name of one of the meta fields associated with the share count of a particular social network or the _totes field which reflects total shares across all networks.

The Problem: On 99% of sites, this query works spendidly and people think it's just the bees knees. However, on a small handful of sites, I've discovered some unusual behavior. In some instances, the widget never seems to update. For example, on the post itself, the post will reflect that it has 100 shares, but the widget will remain at 80 shares and continue to sort according to 80 shares. Both the post and the widget are using the exact same meta field for these functions.

The Question: What would cause the WP_query to continue returning outdated data? If it is some sort of caching, is there a way to force the query to not be cached but to always return fresh data from the database?

1 Answer 1

3

WP_Query has a Caching Parameters you can configure to return the desired data with/without caching.

$swp_args = array(
    // Show posts without adding post meta information to the cache.
    'update_post_meta_cache' => false,
    ...
);

In your specific case update_post_meta_cache allows you to turn on/off the caching for post meta.

1
  • I'm testing this solution right now and will be marking it as accepted shortly. A couple quick questions (and I don't expect a lengthy reply as that would be more worthy of a separate question). 1. What is the default link of those query caches in WordPress? 2. Is it possible for plugins to alter the length that that information is cached (like WP Rocket, WP Super Cache, W3 Total Cache, for examples)? Commented Jul 10, 2017 at 21:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.