1

I have this function which I am using to enable front end page deleting which is working fine

function delete_post(){
global $post;
$deletepostlink= add_query_arg( 'frontend', 'true',   get_delete_post_link( get_the_ID() ) );
if (current_user_can('edit_post', $post->ID)) {
    echo       '<span><a class="post-delete-link" onclick="return  confirm(\'Are you sure to delete?\')" href="'.$deletepostlink.'">Delete this </a></span>';
}
}

//Redirect after delete post in frontend
add_action('trashed_post','trash_redirection_frontend');
function trash_redirection_frontend($post_id) {
if ( filter_input( INPUT_GET, 'frontend', FILTER_VALIDATE_BOOLEAN ) ) {
    wp_redirect( get_option('siteurl').'/' );
    exit;
}
}

And then I use this is my template file for the button

<?php echo delete_post(); ?>

What I am looking to achieve is when a user deletes a page from the front end that it will also delete (or move to trash) all that parent pages children?

Thanks

1

Well, interesting question. As far I've researched the hooks are called on deleting post passes the deleted post ID as parameter. At the time of deleting a parent page it works well but when you hooked a function on trashed_post to delete the child page it won't work cause every time it will get the trashed post id and here it'll be the ID of recently deleted child page. So it will not work as expected.

Now come to the solution. Here I've rewritten your functions with a SQL command to change the post status of the child pages to trash-

function delete_post(){
    global $post;
    $deletepostlink= add_query_arg( 'frontend', 'true',   get_delete_post_link( get_the_ID() ) );
    if (current_user_can('edit_post', $post->ID)) {
        echo '<span><a class="post-delete-link" onclick="return  confirm(\'Are you sure to delete?\')" href="' . $deletepostlink . '">Delete this </a></span>';
    }
}

//Redirect after delete post in frontend
add_action('trashed_post','trash_redirection_frontend');
function trash_redirection_frontend($post_id) {
    if ( filter_input( INPUT_GET, 'frontend', FILTER_VALIDATE_BOOLEAN ) ) {
        $args = array(
            'posts_per_page' => -1,
            'order'=> 'ASC',
            'post_parent' => $post_id,
            'post_type' => 'page'
        );
        // Filter through all pages and find Portfolio's children
        $children = get_children( $args );
        global $wpdb;
        foreach($children as $child){
            $childs[$child->ID] = $child->ID;
        }
        $sql = "UPDATE {$wpdb->posts} SET post_status = 'trash' WHERE ID IN (" . implode( ', ', $childs ) . ")";
        $wpdb->query($sql);
        wp_redirect( get_option('siteurl').'/' );
        exit;
    }
}

Hope it'll help you.

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.