函数来删除一个帖子,它是子代和孙子(已经进行了一半)

时间:2017-03-09 作者:joelybristol

我有一个函数可以删除帖子及其子项。我怎样才能修改它来删除它的孙子呢?

<?php
function delete_post($sectionid)
{
    global $post;
    $deletepostlink= add_query_arg( \'frontend\', \'true\', get_delete_post_link( $sectionid) );

    if (current_user_can(\'edit_post\', $sectionid)) {
    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\' => \'bucket\'
        );

        // 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);
        $referer = $_SERVER[\'HTTP_REFERER\'];
        wp_redirect( $referer );
        exit;
    }
}
我需要另一个foreach, 但到目前为止,我的PHP只是基本的。

1 个回复
SO网友:moraleida

以下是您可以做的:

获取直系子代的所有ID获取孙子代的所有ID合并垃圾

function trash_redirection_frontend($post_id )
{
if ( filter_input( INPUT_GET, \'frontend\', FILTER_VALIDATE_BOOLEAN ) ) {

    $args = array(
        \'posts_per_page\' => -1,
        \'post_parent\' => $post_id,
        \'post_type\' => \'bucket\',
        \'fields\' => \'ids\', // get only the ids, it\'s all we need
    );

    // get all children ids
    $children = get_posts( $args );
    $all_parents = array_merge( [ $post_id ], $children );

    // get all grand_children
    $args[\'post_parent__in\'] = $children;
    unset( $args[\'post_parent\'] ); // we\'re using the above array now

    $grand_children = get_posts( $args );

    // $all_posts now contains all affected ids
    $all_posts = array_merge( $all_parents, $grand_children );

    foreach($all_posts as $child){
        wp_trash_post( $child ); // use this unless you have good reason to query directly
    }

    $referer = $_SERVER[\'HTTP_REFERER\'];
    wp_redirect( $referer );
    exit;
}
}

相关推荐

无法在WordPress中通过PHP显示图像

我有一个奇怪的问题,当我尝试使用PHP输入图像标记的源代码时,它会在检查器中显示以下错误<img src=(unknown) alt=\"\"> 这个代码片段为我提供了正确的url,通过查看CPanel并粘贴和复制地址进行检查,但当我尝试通过php输入它时,不会显示图像$image = wp_get_attachment_image_src( $post_thumbnail_id); //echo($image[0]); ?> <img src=