Redirect Custom Post Type Post if toggle switch is off

Viewed 21

I'm trying to create a toggle switch for each post in a custom post type within wordpress.

Each "Author" has their account page and I want to show them a list of their posts with a toggle switch. In the off state, I want the whole post to redirect to the websites home page. If they toggle it on I want the redirect to disable and allow the post to show. These posts contain contact information and when they aren't needed I want the user to be able to turn off that particular post for privacy. The use case is for a service based website.

Here's the code i currently have that get's the authors current list of posts.

What i cant figure out is how do i link the toggle to each post dynamically and then update the state in postmeta using ajax to on or off and if off to redirect.

global $current_user;
    get_currentuserinfo();
    $authorID = $current_user->ID;
        $args = array(
                  'post_type' => 'petcontact',
                  'posts_per_page' => -1,
                  'author' => $authorID
                  );

        $wp_query = new WP_Query($args);

    if($current_user){
        
        $loop = new WP_Query( $args ); 
        

    while ( $loop->have_posts() ) : $loop->the_post(); 
        print the_title(); 
         
    endwhile;

    wp_reset_postdata(); 

    }
1 Answers

This should get you started, without Ajax. Not tested but the code speaks for itself.

<?php

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if ($_REQUEST['action'] == 'toggle_post') {
        $state = $_REQUEST['state'];
        $post_id = $_REQUEST['post_id'];

        update_post_meta($post_id, 'state', $state);
    }
}

global $current_user;
get_currentuserinfo();
$authorID = $current_user->ID;
$args = array(
    'post_type' => 'petcontact',
    'posts_per_page' => -1,
    'author' => $authorID,
);

$wp_query = new WP_Query($args);

if ($current_user) {

    $loop = new WP_Query($args);

    while ($loop->have_posts()): $loop->the_post();

        $state = get_post_meta(the_ID(), 'state', true);

        print the_title() . '
            <form method="post">
                <input type="hidden" name="post_id" value="' . the_ID() . '">
                <input type="hidden" name="action" value="toggle_post">
                <label>
                    <input type="checkbox" name="state" value="' . $state . '" onchange="this.closest(\'form\').submit()">
                    Toggle Post [state is: ' . $state . ']
                </label>

            </form>
            <hr>
        ';

    endwhile;

    wp_reset_postdata();

}
Related