首頁  >  問答  >  主體

刪除自訂貼文類型並重定向到主頁

<p>我正在使用 <code>get_delete_post_link</code> 從前端刪除自訂帖子,但刪除後我得到 404 頁面。自訂貼文刪除後如何重定向到首頁? </p> <p>我在functions.php中插入了這段程式碼:</p> <pre class="brush:php;toolbar:false;">function wp_delete_post_link($link = 'Delete Post', $before = '', $after = '') { global $post; $link = "<a href='" . wp_nonce_url( get_bloginfo('url') . "/wp-admin/post.php?action=delete&amp;post=" . $post->ID, 'delete-post_' . $post->ID) . "'>".$link."</a>"; echo $before . $link . $after; }</pre> <p>之後我創建了短代碼來產生刪除按鈕:</p> <pre class="brush:php;toolbar:false;">function wpc_elementor_shortcode( $atts ) { wp_delete_post_link(); } add_shortcode( 'my_shortcode', 'wpc_elementor_shortcode');</pre> <p>有沒有辦法改進這段程式碼,實現刪除後重定向? </p>
P粉590428357P粉590428357381 天前432

全部回覆(2)我來回復

  • P粉020556231

    P粉0205562312023-09-05 00:57:37

    試試這個:

    /**
     * template_redirect Action Hook.
     * Redirect users to home page
     * after deleting a custom post type post.
     */
    function redirect_on_delete() {
        // Custom post type plural name or rewrite slug name.
        $custom_post_type = 'CUSTOM_POST_TYPE';
    
        $regex = "/" . $custom_post_type . ".*" . preg_quote(  "/?deleted=", "/" ) . "\d+" . "/i";
    
        if ( preg_match( $regex, $_SERVER["REQUEST_URI"] ) ) {
            \nocache_headers();
            if ( \wp_safe_redirect( esc_url( get_home_url() ) ) ) {
                exit;
            };
        }
    }
    add_action( 'template_redirect', 'redirect_on_delete', 10, 1 );

    回覆
    0
  • P粉609866533

    P粉6098665332023-09-05 00:40:08

    我嘗試了許多程式碼片段來在刪除自訂貼文後進行重定向,但沒有一個起作用。所以我嘗試了另一種方法:將 404 頁面重新導向到我為編輯器角色使用者建立的自訂前端編輯器儀表板。程式碼如下:

    function editor_redirect_404() {
        global $wp_query;
        if ( $wp_query->is_404 ) {
          wp_redirect( home_url( '/dashboard/' ) );
          exit;
        }
    }
    add_action('template_redirect', 'editor_redirect_404', 1);

    我不希望網站的訪客遇到這種情況(他們有常規的 404 頁面),因此僅當使用者登入並具有編輯者角色時才會套用此重定向。這是透過使用 WPCodeBox 插件中的條件產生器來實現的。

    回覆
    0
  • 取消回覆