1

EDIT: Based on @TimHallman's answer I have a follow-up question, please see the bottom of this post.

I am trying to do something that is way over my head and the more I think of it, the more questions I end up with.

This is the scenario I have:

  • Custom posts of type golfcourse, each presenting a golf course.
  • Custom posts of type clubnews.
  • Clubnews has the term clubnewsowner related to them.
  • The clubnewsowner taxonomies are identical to the golfcourses.

What I do is that (using a self made shortcode) I check, on each golfcourse-post, if one or more posts of type clubnews with taxonomy related to the spesific golfcourse exists. If yes, show the clubnews-post(s) on the golfcourse-post.

This works as I want it to.

I do, however, use the WP-Rocket caching plugin on this website. And because the clubnews-posts are added (to the golfcourse-posts) using php only (no ajax), WP-Rocket has no clue the content has changed on the golfcourse-post whenever a clubnews post has been added, updated or deleted. This means that I need to do a manual cache-clearing of the related golfcourse-post whenever the mentioned scenario occurs.

Luckily, WP-Rocket has a function for this:

//clean post with ID 5
rocket_clean_post( 5 );

I have managed to create some kind of pseudo-code:

function clearPageCacheBasedOnTaxOfClubnews() {
    if ( ( clubnews is created ) || ( clubnews is updated )  || ( clubnews is deleted ) ) {

        $customPost = clubnewsPostID;

        // The result here is always only one taxonomy
        $taxonomyOfCustompPost = get_post_taxonomies( $customPost );

        switch ($taxonomyOfCustompPost) {
            case 'golfcourseOne': rocket_clean_post( 5 );
            break;
            case 'golfcourseTwo': rocket_clean_post( 8 );
            break;
        }
    }
}
add_action( 'when?', 'clearPageCacheBasedOnTaxOfClubnews', 10, ?);

I think the above code will work, but there is a lot of things I am not sure of here:

  1. How do I get the ID of the clubnews post being created/updated/deleted?
  2. How do I check if it is actually being created/updated/deleted?
  3. At this point my head starts spinning, and I am no longer sure what I am wondering...

ANY help is appreciated!


Follow-up question:

I do believe @Tim Hallman solves at least two thirds of this (I need another action for when a clubnews custom post gets deleted) with his answer below.

I, however cannot make this work. My code produces a white screen of death, whitout generating any php errors. What I think happens is that WP Rocket uses all of the resources on the server when clearing the cache on individual posts. I'm not sure though.

This is the code:

add_action( 'save_post', 'clearPageCacheBasedOnTaxOfClubnews');


function clearPageCacheBasedOnTaxOfClubnews($post_id) {

    /* Is has_term() used correctly here? In the codex it says that the
     * taxonomy parameter is optional, other places on the Internet claims
     * the opposite...
     */
    if ( has_term('clubnewsowner', '', $post_id ) {

        // The result here is always only one taxonomy
        $taxonomyOfCustompPost = get_post_taxonomies( $post_id );

        /* The codex says get_post_taxonomies() returns an array. The code
         * on the line below produces a php fatal error though.
         */
        $taxonomyOfCustompPost = $taxonomyOfCustompPost[0];

        /* This is where the connection between the taxonomy of the
         * Clubnews custom posts and the golf course pages happens
         */
        switch ($taxonomyOfCustompPost){
            case 'Course One': $courseID = 123; break;
            case 'Course Two': $courseID = 234; break;
            case 'Course Three': $courseID = 345; break;
            ...
        }

        //This cleans the cache of the selected post
        rocket_clean_post( $courseID );
    }
}

I have tried this in different variants, and either I get a fatal error because of the $taxonomyOfCustompPost = taxonomyOfCustompPost[0]; or I get a white screen of death whitout any php errors at all.

Any suggestions on where to go on from here?

  • you probably want the save_post hook – Tim Hallman Mar 8 '18 at 8:17
  • Thank you @TimHallman. But that doesnt cover all three scenarios, does it? (New, updated or deleted.) Maybe I will have to add three actions... – erolha Mar 8 '18 at 8:29
  • Check out the CODEX: "save_post is an action triggered whenever a post or page is created or updated" codex.wordpress.org/Plugin_API/Action_Reference/save_post – Tim Hallman Mar 8 '18 at 8:30
  • please don't ask additional question, if you have a different question, even if related, just ask it as a new question. – Mark Kaplun Mar 9 '18 at 6:11
  • 1
    and always develop with WP_DEBUG set to true and use the query monitor plugin – Mark Kaplun Mar 9 '18 at 6:47
0

I suppose a quick and dirty way to achieve what you want is to clear the entire site cache, something like this:

function clear_rocket_cache_on_post_save() {
     rocket_clean_domain();
}
add_action( 'save_post', 'clear_rocket_cache_on_post_save' );

Otherwise you'll need to do a query to get the matching post, something like this should work:

  function clear_rocket_cache_on_post_save( $post_id ) {

       // $result_id = tax query by $post_id
       rocket_clean_post( $result_id );

  }
  add_action( 'save_post', 'clear_rocket_cache_on_post_save' );

You can find more information on Wordpress's "out of the box" caching features here: https://codex.wordpress.org/Transients_API

and here: https://codex.wordpress.org/Class_Reference/WP_Object_Cache

Many themes do not utilize this core functionality, but it's there.

UPDATE:

If you're not getting debugging output on your screen, the best way to figure out why you're getting errors is to use the debug.log.

First, put this snippet at the bottom of your functions.php file.

if (!function_exists('write_log')) {
    function write_log ( $log )  {
        if ( true === WP_DEBUG ) {
            if ( is_array( $log ) || is_object( $log ) ) {
                error_log( print_r( $log, true ) );
            } else {
                error_log( $log );
            }
        }
    }
}

Then edit your wp-config.php file to include these:

define( 'WP_DEBUG', true);
define( 'WP_DEBUG_DISPLAY', false );
define( 'WP_DEBUG_LOG', true );

Then in your wp-content folder create a new file called debug.log. Now you are ready to debug.

Now whatever you want to output you use the function write_log($some_variable) and it'll output your debugging errors to debug.log. Do that and I bet you'll see why you're getting a WSOD. /happy coding

  • 1
    Ah, could it be that simple? And include a "check if $post_id has the term clubnews connected. If yes, do the switch." I'll give it a shot and get back here with the results. Thanks! – erolha Mar 8 '18 at 8:37
  • @erolha please accept this answer if this worked for you. Disregard the other guy. Wordpress does have page caching "out of the box", it's built into the core of Wordpress and the WP devs spent a lot of time doing that. Have a look at transients – Tim Hallman Mar 8 '18 at 17:23
  • Also see here. WP has tons of caching features built into the core "out of the box". Just because some themes don't leverage it doesn't mean it's not there. codex.wordpress.org/Class_Reference/WP_Object_Cache – Tim Hallman Mar 8 '18 at 17:29
  • your answer is probably the correct one, and as soon as I stop getting white screen of death because of my erroneous code I will take actions here. I have been struggling with figuring out if my questions now belong in a new thread or if I should continue here. I'll update my question now with the code not working... – erolha Mar 9 '18 at 5:21
0

Ok, so I got this working. The solution is based on @TimHallman' answer below/above here.

One of the reasons I didn't get it to work was I was confused with what is a term and what is a taxonomy. I thought a term contained taxonomies when it is the opposite....

Despite good advices of not hardcoding stuff like this, not caching dynamic sites and so on there are scenarios when code like this is needed. And here is the working code:

// Run the function when a post is created or updated
add_action( 'save_post', 'clearPageCacheBasedOnTaxOfClubnews');
function clearPageCacheBasedOnTaxOfClubnews($post_id) {

    $taxonomyOfCustompPost = get_post_taxonomies( $post_id );
    // In this special case, there is always only one taxonomy!
    $taxCustompPost = $taxonomyOfCustompPost[0];

    if ( $taxCustompPost != 'clubnewsowner' ) {
        return;
    }

    if ( $taxCustompPost == 'clubnewsowner' ) {
        $terms = wp_get_post_terms( $post_id, 'clubnewsowner', array("fields" => "names"));
        $term = $terms[0];;

        switch ($term){
            case 'Course One': $courseID = 123; break;
            case 'Course Two': $courseID = 456; break;
            case 'Course Three': $courseID = 789; break;
            ...
        }

        rocket_clean_post( $courseID );


    }
}

//Run the function when the post is deleted
add_action('trash_post','clearPageCacheWhenCPDeleted',1,1);
function clearPageCacheWhenCPDeleted($post_id){

    if(!did_action('trash_post')){

        $taxonomyOfCustompPost = get_post_taxonomies( $post_id );
        // In this special case, there is always only one taxonomy!
        $taxCustompPost = $taxonomyOfCustompPost[0];

        if ( $taxCustompPost != 'clubnewsowner' ) {
            return;
        }

        if ( $taxCustompPost == 'clubnewsowner' ) {

            $terms = wp_get_post_terms( $post_id, 'clubnewsowner', array("fields" => "names"));
            $term = $terms[0];;

            switch ($term){
                case 'Course One': $courseID = 123; break;
                case 'Course Two': $courseID = 456; break;
                case 'Course Three': $courseID = 789; break;
            }

            rocket_clean_post( $courseID );

        }
    }
}
  • The "When deleted" hook is also based on this answer: wordpress.stackexchange.com/a/44460 – erolha Mar 10 '18 at 9:26
  • yeh hardcoding is very bad here. someone changes the name of the course and things stop working – Mark Kaplun Mar 10 '18 at 9:59
  • @markkaplun In general, you are of course right. In this case though, you are wrong. – erolha Mar 10 '18 at 10:02
-1

Basically, once you start using page caching you can not do dynamic things. This is part of why wordpress do not have page caching out of the box.

Cleaning up a page cache, especially when it is not on the server wordpress runs on, can be a long process which will make your server busier (and the whole point of having a page cache is to reduce the load).

From your description, the problem you are facing is not a real problem, as no one will die from having some stale gulf course information, but if you just have to have it, the easier way is to reduce the time until the cache expires. This will be easier to do and you will not need to write code which is likely to have bugs and will need constant maintenance.

  • Wordpress does have caching out of the box. Look at transients. – Tim Hallman Mar 8 '18 at 8:45
  • Well, one reason to do this is that it is not I who post the clubnews. Imagine a scenario where you have a couple of hundred authors publishing without seeing their posts being published instantly. Sorry for describing the issue in such a way that it appears not to be a problem... – erolha Mar 8 '18 at 8:45
  • @TimHallman, I advice to read again what I wrote. And wordpress has zero caching out of the box – Mark Kaplun Mar 8 '18 at 8:46
  • I'm not going to get into a flinging match, you said "This is part of why wordpress do not have page caching out of the box." That is not true. Furthermore, to suggest his problem is not real is also incorrect. – Tim Hallman Mar 8 '18 at 8:48
  • @erolha, logged in users should not be served content from cache. In addition, the more content you have the longer it will take to clear the associated content as there will be more of it, and you will have to do it more times as with more authors there is likely to be more frequent updates. – Mark Kaplun Mar 8 '18 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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