• berry metal

    (@erikalleman)


    I have a grid in my post template, that uses a dynamic query to fetch new post types within the post, as they are posted.

    The problem with this directory post system (lists) is that when I post a new post type, and it’s getting fetched in a post by the grid, the post has been updated, but the “last updated” date will not change for the post, because the post has not been actually edited, only a new post type post got fetched within the grid.

    How do I auto-update the “last updated” date for the “post” posts?

Viewing 11 replies - 46 through 56 (of 56 total)
  • Thread Starter berry metal

    (@erikalleman)

    Hi,

    it does not work if I add the post via the dashboard, either.
    Could you give an example code?

    I felt I don’t have enough information to be able too google for this code, I mean to find tutorials for exactly this purpose.
    I need an example code.

    Thank you!

    Moderator bcworkz

    (@bcworkz)

    Yeah, there’s some sort of redirect or something that prevents us from getting the term ID out of $_POST. It’s weird. The data is certainly sent, but I don’t see how to reliably get it server side. Once in a rare while, the data really does come through, but it’s hardly reliable.

    However, my alternative idea of hooking the set object terms action looks viable. This code works on my site:

    add_action( 'set_object_terms', 'bcw_set_date', 10, 6 );
    function bcw_set_date( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
    	$item = get_post( $object_id );
    	if ('items' == $item->post_type && 'relations' == $taxonomy && 0 < count( $tt_ids)){
            // Form an array of data to be updated
            $latest_cpt = get_posts([
                'posts_per_page'=> 1,
                'post_type'=>'post',
                'tax_query'=>[[
                   'taxonomy'=>'relations',
                   'field'=>'term_taxonomy_id',
                   'terms'=> $tt_ids[0],
                ],],
            ]);
            // Get the current time
            $time = current_time('mysql');
            // Form an array of data to be updated
            $post_data = array(
                'ID'           => $latest_cpt[0]->ID, 
                'post_modified'   => $time,
                'post_modified_gmt' =>  get_gmt_from_date( $time )
            );
            // Update the latest post with the same term
            wp_update_post( $post_data );
    	}
    }

    Well, not exactly this, some of this code was altered from mine to fit your data.

    The one drawback here is there is not an $update argument ($append is unrelated), so the related post’s modified date is altered any time the relations term and items post is updated or newly published. I suppose you could check the $item->post_date value against the current date/time. If the difference is more than a few seconds, it’s probably not a newly published item.

    Thread Starter berry metal

    (@erikalleman)

    It works, perfect. Thank you!
    I see plenty of modification in the code that I couldn’t have come up with.
    To answer your question, no the items should not be posted via wp-cli, the only reason I used wp-cli was because at the moment i clicked on the add button, the error screen came in and I couldn’t actually attempt to post because of that (because the save_post already fires when clicking the add new (post) button) )

    But it turned out that the error came up also in wp-cli, because I enabled the –debug flag.

    I can see that

    $old_tt_ids

    and

    $append

    is declared but not used anywhere in the code.
    Are those not necessary for my setup and can I remove them and change the number to 4?

    So far I studied StackOverflow on the issue (regarding the previous code) I noticed that there were several posts mentioning a taxonomy permissions issue relating to save_post when assigning a taxonomy, so I tought you could bust that, but with wp-cli I managed to post while assigning the term, and the error still persisted, so perhaps is not a permissions issue.

    And I am super admin, so how could it be a permissions issue?

    What do you check for with this statement:
    0 < count( $tt_ids)

    Can you achieve almost anything in WordPress with such snippets using only database commands, variables, functions and actions?

    Out of PHP, I can only see variables in this code (with the dollar sign), hence I am asking this.

    This is great code as an example code for use for future similar modifications… thanks!

    Why do you take the time from the database instead from the server?

    Why is that

    $post_data

    needs to be an array but

    $latest_cpt

    not?

    Why do you use double [[ bracket at the tax query?

    And could you tell me what is this definition? terms'=> $tt_ids[0]
    And a few more questions if its okay:
    Why do you need to define an additional $object_id and why couldn’t you write just like this: $item = get_post( $item_id ); instead of $item = get_post( $object_id );
    And why $item doesn’t need to be added in the parenthesis with the other $ variables?

    And one more: what does this

    $latest_cpt[0]

    exactly mean?
    At least I could learn something from this.

    Thanks!

    • This reply was modified 3 years, 12 months ago by berry metal.
    • This reply was modified 3 years, 12 months ago by berry metal.
    Moderator bcworkz

    (@bcworkz)

    Are those not necessary for my setup and can I remove them and change the number to 4?

    Yes you can. However, in the future they might be useful. Of course you can always add them back. The way I work, I always collect everything, used or not, so in the future I’m reminded of what’s available without having to find the docs page. The performance hit from passing the extra data is negligible.

    Come to think of it, the old tax term IDs could be a way to detect the difference between updates and newly published. If an item has old terms, it cannot be newly published. Or if no old terms, it means the item is either newly published, or previously published without any terms and an update has newly assigned one.

    how could it be a permissions issue?

    Custom taxonomies inherit the permissions of the related post. Custom post types can require special capabilities not given to a super admin by default. If you can get to the post edit screen, you have permission.

    What do you check for with this statement:
    0 < count( $tt_ids)

    I’m ensuring there is at least one term to work on to avoid illegal offset warnings. In this context it may be unnecessary, but better safe than sorry ??

    Can you achieve almost anything in WordPress?

    Yes! “almost” being key. There are a few things that would be impractical. If there is not a useful hook available it can greatly complicate things. It helps to approach challenges with creative thinking.

    Why do you take the time from the database instead from the server?

    I don’t think there is any other way to get the data we need. You’re right, DB queries should be minimized. Sometimes there’s no choice.

    Why is that $post_data needs to be an array but $latest_cpt not?

    They are both arrays, as required by the syntax of related WP code. Even though we only get one post, get_posts() always returns an array, even if an array with only one element. Arrays are convenient containers to pass a large chunks of data as a single variable. Similar for objects. Objects are more formal and structured. Arrays can be used ad hoc.

    Why do you use double [[ bracket at the tax query?

    It’s required by tax_query syntax. It allows us to construct complex criteria by adding other inner arrays within the outer array.
    https://developer.www.ads-software.com/reference/classes/wp_query/#taxonomy-parameters

    [] is a shortcut for array() in later PHP versions. Some advise to not use shortcuts as it compromises readability. I used to code in LISP (lots (of (nested)) parenthesis) so I’m fine with brackets ??

    And could you tell me what is this definition? ‘terms’=> $tt_ids[0]

    Any ‘terms’ criteria limits what posts are candidates for return. $tt_ids[0] is the first tax term ID being set in the function we’ve hooked into. Probably the only term, but if more than one, we still get posts that have at least that one term.

    Why do you need to define an additional $object_id

    It’s not really additional, it is passed from the action hook. We could have collected it as $item_id instead. As we discussed earlier, we can name local variables anything we like. If you think $item_id is more readable, feel free to change all instances of $object_id to $item_id.

    And why $item doesn’t need to be added in the parenthesis

    Because the hook doesn’t pass any post object, only its ID. We can only collect what is passed to us.

    what does this $latest_cpt[0] exactly mean?

    As mentioned earlier, get_posts() always returns an array of post objects. The [0] part gives us the first (and only in this case) object in the array $latest_cpt

    From the sort of questions you ask, I’d say you’re learning a lot! If you keep finding things that can be made easier by code and try to do so, your coding skills will keep improving. Even if it’d be faster to do something manually, code it anyway as an exercise. I have a private page on my site which is based on a custom template. It serves as a blank canvas on which I can try out different coding concepts. You can learn a lot by simply trying things out.

    Thread Starter berry metal

    (@erikalleman)

    I am a blogger and designer, but I am not comfortable hiring people to do tasks for me so that I will not understand in the end how my own site works, hence I struggle with the technical part of it, so I could master the whole thing, even if I don’t intend to be a coder, but a blogger and designer.

    As programmers have historically proven, they do not have a flair for design and writing at all, so it’s 2 different type of personalities, and it’s hard to fit them in 1 person…

    Thank you, master!

    • This reply was modified 3 years, 12 months ago by berry metal.
    • This reply was modified 3 years, 12 months ago by berry metal.
    Moderator bcworkz

    (@bcworkz)

    I’m not a coder by profession either. I’ve dabbled in it long it enough that I’ve become pretty decent at it. I started coding long ago out of a fascination with techy computer things. I do it because I enjoy being able to do things for myself. My needs aren’t important enough to justify hiring someone else to do these things. Plus I can get the exact results I need. Getting that from someone else always seems to be elusive. Regardless of your true calling, having some coding ability is a useful skill.

    At some point I discovered I enjoy helping others (especially those keen to learn for themselves) solve their coding challenges, so I started hanging out here. Happy coding!

    Thread Starter berry metal

    (@erikalleman)

    Thanks. Happy coding!

    Thread Starter berry metal

    (@erikalleman)

    Nice to know your story.

    Thread Starter berry metal

    (@erikalleman)

    Hi there,

    thanks a lot for the code, but I realized that it’s removing HTML from my posts:

    add_action( 'set_object_terms', 'bcw_set_date', 10, 6 );
    
    function bcw_set_date( $object_id, $terms, $tt_ids, $taxonomy, $append, $old_tt_ids ) {
    
        $item = get_post( $object_id );
    
        if ('items' == $item->post_type && 'relations' == $taxonomy && 0 < count( $tt_ids)){
    
            // Form an array of data to be updated
            $latest_cpt = get_posts([
                'posts_per_page'=> 1,
                'post_type'=>'post',
                'tax_query'=>[[
                   'taxonomy'=>'relations',
                   'field'=>'term_taxonomy_id',
                   'terms'=> $tt_ids[0],
                ],],
            ]);
    
            // Get the current time
            $time = current_time('mysql');
    
            // Form an array of data to be updated
            $post_data = array(
                'ID'           => $latest_cpt[0]->ID, 
                'post_modified'   => $time,
                'post_modified_gmt' =>  get_gmt_from_date( $time )
            );
    
            // Update the latest post with the same term
            wp_update_post( $post_data );
        }
    }

    What the code is supposed to do (and it does) is that every time I post an “item” post, it’s updating the “last updated” date of a “post” post, that has the same term in the “relations” taxonomy, as the newly posted “item”.

    Thats’ all.

    The problem is that it removed HTML.
    I found this thread:
    https://stackoverflow.com/questions/47746325/why-wordpress-wp-update-post-function-removes-html-form-tags/47750009

    It seems that it’s some security feature.
    Could you tell an opinion, do you think this thread is relevant for this code and should I use the suggestion in the answer?

    I didn’t notice it earlier that this code even though it does what it’s supposed to do, it removes HTML form my posts, and even if I delete the newly posted “item”, the HTML will be missing. It also alters CSS and that is also permanent.

    I am not posting via Gutenberg, but via the classig editor, but the “item” post type is exposed to the REST API in the post type settings.
    I don’t know if the “post” post type is exposed, because I don’t know how to check it since that is not a custom post type.

    Could you by any chance tell something how could I troubleshoot this?

    Thanks!
    I hope you and your business are doing well.

    Best regards.

    • This reply was modified 3 years, 5 months ago by berry metal.
    Thread Starter berry metal

    (@erikalleman)

    Ah it’s solved!

    I needed to add:

    // prevent issues with metabox save function.
    $_POST[‘themeprefix_metabox_nonce’] = array();

    before saving the post because it saved the metaboxes of the “item” into the “post”, and that caused the issue!

    Thanks for the code again!
    I wish you all the best.

    Thread Starter berry metal

    (@erikalleman)

    This might cause issues if I add custom metaboxes to the “item”s right?

Viewing 11 replies - 46 through 56 (of 56 total)
  • The topic ‘How do I auto-update post date when new post type is fetched within the post?’ is closed to new replies.