TransWikia.com

How to move a post from one category to another

WordPress Development Asked by sajeergraphix on October 30, 2021

I am new to PHP. Please help me to achieve the below scenario. I am trying to achieve this from the last 3 days.

I’ve two categories in my WordPress dashboard named "Available (id:3)" and "Booked (id:4)".
In the "available" category a few posts are there.

When I submit a "contact form 7" successfully, I would like to move that post to the "booked" category.

I tried something like below in my functions.php

add_action('wpcf7_mail_sent', function ($cf7) {
    function wp_set_post_categories( $post_ID = 0, $post_categories = array(), $append = true ) {
    $post_ID     = (int) $post_ID;
    $post_type   = get_post_type( $post_ID );
    $post_status = get_post_status( $post_ID );
    // If $post_categories isn't already an array, make it one:
    $post_categories = (array) $post_categories;
    if ( empty( $post_categories ) ) {
        if ( 'post' == $post_type && 'auto-draft' != $post_status ) {
            $post_categories = array( get_option( 'default_category' ) );
            $append          = false;
        } else {
            $post_categories = array(4);
        }
    } elseif ( 1 == count( $post_categories ) && '' == reset( $post_categories ) ) {
        return true;
    }
 
    return wp_set_post_terms( $post_ID, $post_categories, 'category', $append );
}
});

Whatever I am writing inside the action its not even executing

add_action('wpcf7_mail_sent', function ($cf7) {
    // not working anything, only print_r command working
});

All help will be appreciated. Thank you.

One Answer

add_action('wpcf7_mail_sent', function ($cf7) {
    $submission = WPCF7_Submission::get_instance();
    $data = $submission->get_posted_data();

    if( empty($data['_wpcf7_container_post']) )
        return;

    $post_id = (int) $data['_wpcf7_container_post'];

    wp_remove_object_terms( $post_id, 'available', 'category');
    wp_set_object_terms( $post_id, 'booked', 'category');
});

Answered by Az Rieil on October 30, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP