問題描述

當我在 WordPress 中創建一個新頁面時,我可以選擇從主題 (從接口的 right-hand 側的下拉列表) 中指定使用哪個模板。

我需要找到哪些可用的模板是未使用的,以便我可以刪除它們。

請問這怎麼辦?

WP 版本是 4.2.2

最佳解決方案

您需要做的是比較元字段_wp_page_template 的值,其中包含為單個頁面選擇的頁面模板與可用的頁面模板。

為此,您需要構造一個已使用模板的數組,因為您需要所有頁面使用的模板,如下所示:

使用 array_unique 獲取唯一的值。

然後,您需要獲取可用的頁面模板,如下所示:

最後但並非最不重要的是,您可以使用 array_diff 比較已使用和可用模板的數組,隨後將為您提供未使用的模板。

次佳解決方案

更新:

WordPress 4.4+中的頁面模板使用信息

在 WordPress 4.4 中,array_intersect_assoc()已從 WP_Theme::get_page_templates()方法中刪除。

參見 #13265#34995 的更改。

因此,我們可以使用 theme_page_templates 過濾器直接在模板下拉列表中添加頁面模板使用信息,而不使用 JavaScript 或一些聰明的對象緩存技巧來解釋 here by @MikeSchinkelhere by @gmazzap

這是一個演示 (PHP 5.4+):

add_filter( 'theme_page_templates', function( $page_templates, $obj, $post )
{
    // Restrict to the post.php loading
    if( ! did_action( 'load-post.php' ) )
        return $page_templates;

    foreach( (array) $page_templates as $key => $template )
    {
        $posts = get_posts(
            [
                'post_type'      => 'any',
                'post_status'    => 'any',
                'posts_per_page' => 10,
                'fields'         => 'ids',
                'meta_query'     => [
                    [
                        'key'       => '_wp_page_template',
                        'value'     => $key,
                        'compare'   => '=',
                    ]
                ]
            ]
        );

        $count = count( $posts );

        // Add the count to the template name in the dropdown. Use 10+ for >= 10
        $page_templates[$key] = sprintf(
            '%s (%s)',
            $template,
             $count >= 10 ? '10+' : $count
        );
    }
    return $page_templates;
}, 10, 3 );

例:

在這裏我們可以看到它的外觀如何,將使用計數信息添加到模板名稱中:

希望可以根據您的需要調整

參考文獻

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