1

I have this relationshop between some categories and posts where the name of the category is also the name of the post. When I add a new category, a post that has the same title as the category is created. Now when I edit one of those category titles, I want the corresponding post to update its title automatically as well. Here's what I have:

function update_group($post_id) {

    // get the category object
    $category = get_term_by( 'id', $post_id, 'category');

    // use the object to get your values
    $name = $category->name;

    $updates = array(
        'ID' => 996,
        'post_title' => $name
    );

    wp_update_post($updates);

}

add_filter('edit_category' , 'update_group' );

The problem with this simple code is that when I fetch the category name, the new name that I submitted has not been saved yet when edit_category runs, so the first time I edit a category, wp_update_post updates the post with the old name. That means the post will only get the new and correct name when I submit the category change again via the admin page. Is there a way around this? How do I get the sumbitted category name the first time edit_category is executed?

  • I've looked at a few other filters, you could try edited_terms and pre_category_name - WordPress Codex – Howdy_McGee Mar 13 '14 at 14:45
  • No luck with those two unfortunately. – Marc Mar 13 '14 at 15:42
1

The solution I arrived at is using the POST value of the submitted category title, so you always get what you entered and not what was saved before. Like so:

function update_group($post_id) {

    $updates = array(
        'ID' => 996,
        'post_title' => sanitize_text_field($_POST['name'])
    );

    wp_update_post($updates);

}

add_filter('edit_category' , 'update_group' );

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.