問題描述

有沒有一些 wordpress 魔術/外掛,將使媒體庫只顯示上傳到特定的自定義帖子型別的影像?我有一個名為”artists” 的自定義帖子型別,我想要,當管理員單擊上傳/附加影像時,媒體庫彈出視窗只顯示已上傳到藝術家自定義型別的影像,而不是整個網站。

我使用 ACF 外掛來處理自定義欄位,以及定製的 post 型別 ui 。這可能嗎?

最佳解決方案

我不是 100%肯定如果我得到你的問題正確,但… 也許這將幫助你…

媒體上傳器使用簡單的 WP_Query 獲取附件,因此您可以使用許多過濾器來修改其內容。

唯一的問題是,您不能使用 WP_Query 引數查詢具有特定 CPT 的帖子作為父級,所以我們必須使用 posts_whereposts_join 篩選器。

可以肯定的是,我們只會更改媒體上傳者的查詢,我們將使用 ajax_query_attachments_args

這是它的外觀,組合時:

function my_posts_where($where) {
    global $wpdb;

    $post_id = false;
    if ( isset($_POST['post_id']) ) {
        $post_id = $_POST['post_id'];

        $post = get_post($post_id);
        if ( $post ) {
            $where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type);
        }
    }

    return $where;
}

function my_posts_join($join) {
    global $wpdb;

    $join .= " LEFT JOIN {$wpdb->posts} as my_post_parent ON ({$wpdb->posts}.post_parent = my_post_parent.ID) ";

    return $join;
}


function my_bind_media_uploader_special_filters($query) {
    add_filter('posts_where', 'my_posts_where');
    add_filter('posts_join', 'my_posts_join');

    return $query;
}
add_filter('ajax_query_attachments_args', 'my_bind_media_uploader_special_filters');

當您編輯帖子 (帖子/頁面/CPT) 時開啟媒體上傳器對話方塊時,您只會看到附加到此特定帖子型別的影像。

如果你希望它只適用於一個特定的帖子型別 (就是說頁面),你必須改變 my_posts_where 函式的條件,就像這樣:

function my_posts_where($where) {
    global $wpdb;

    $post_id = false;
    if ( isset($_POST['post_id']) ) {
        $post_id = $_POST['post_id'];

        $post = get_post($post_id);
        if ( $post && 'page' == $post->post_type ) {  // you can change 'page' to any other post type
            $where .= $wpdb->prepare(" AND my_post_parent.post_type = %s ", $post->post_type);
        }
    }

    return $where;
}

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。