0

I have the following function in functions.php in a child theme:

<?php
add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 1 ); // Grabs the inserted post data so you can modify it.
function modify_post_title( $data ){
    if($data['post_type'] == 'post' || $data['post_type'] == 'remark' || $data['post_type'] == 'share' && !get_page_by_title($data['post_title'],OBJECT, 'post')){
        $id = get_the_ID();
        $new_title = get_the_time( 'Y-m(M)-d(D)—HiT', $id );
        $new_slug = get_the_time( 'Y-m-d-HiT', $id );

        $data['post_title'] =  $new_title;
        $data['post_name'] = strtolower($new_slug); // Updates the post slug to the new title.
    }
    return $data;
}

What this should do is grab the (publish) date and time and set that to the title and slug for the listed post types. This worked precisely as expected until recently. For some reason, this function no longer works in WordPress 6.x (as of writing this, WordPress 6.0.3).

Nothing relevant seems to appear in any logs. What change or changes caused this to break? and what needs to be updated to get it working again?

5
  • 1
    Calling get_the_ID in this context isn't correct, it's for use inside query loops. If the ID isn't stored inside $data, increase your filter accepted args to two and check the $postarr (second incoming array of data) for the appropriate ID.
    – t31os
    Oct 27, 2022 at 10:54
  • As mentioned, this worked (in this case, for years) until recently. Did something change with WordPress that caused the function the break?
    – Zyniker
    Oct 27, 2022 at 20:28
  • 1
    Possibly a lucky coincidence that there was a post object populated for the call to work originally. Do you need help making adjustments?
    – t31os
    Oct 27, 2022 at 21:26
  • That would be appreciated, yes.
    – Zyniker
    Oct 28, 2022 at 13:20
  • 1
    Added as answer, see if that does the trick.
    – t31os
    Oct 28, 2022 at 14:30

1 Answer 1

2

The call to get_the_ID() possibly worked by happy coincidence of there being an available post object to pull the ID from. However, realistically you should have been looking at data available to the filter for this ID instead, here's how.

First update you add_filter declaration to bring in the second variable from wp_insert_post_data.

add_filter( 'wp_insert_post_data' , 'modify_post_title' , '99', 2 );

Then update your callback(function) to receive that additional data.

function modify_post_title( $data, $postarr ){

And update your ID variable with the value from $postarr.

$id = $postarr['ID'];

Hope that helps.

1
  • That did, indeed, resolve the issue. Thank you.
    – Zyniker
    Oct 28, 2022 at 17:36

Your Answer

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

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