問題描述

我想選擇一個精選的帖子只是通過在編輯屏幕中選中一個複選框,並能夠從特定類別檢索這些精選文章?

總之我正在尋找:

  • 設置特色帖子

  • 循環播放特定類別的帖子 (不是所有的帖子)

任何幫助?並提前感謝:)

最佳解決方案

您可以按照以下步驟執行此操作:

  1. 在您的帖子中添加自定義元框

  2. 創建使用 save_post 操作保存元數據的函數

  3. 將’meta_key’ 查詢參數添加到您正在使用的任何查詢。

將它放在你的 functions.php 文件中:

function register_post_assets(){
    add_meta_box('featured-post', __('Featured Post'), 'add_featured_meta_box', 'post', 'advanced', 'high');
}
add_action('admin_init', 'register_post_assets', 1);

function add_featured_meta_box($post){
    $featured = get_post_meta($post->ID, '_featured-post', true);
    echo "<label for='_featured-post'>".__('Feature this post?', 'foobar')."</label>";
    echo "<input type='checkbox' name='_featured-post' id='featured-post' value='1' ".checked(1, $featured)." />";
}

function save_featured_meta($post_id){
    // Do validation here for post_type, nonces, autosave, etc...
    if (isset($_REQUEST['featured-post']))
        update_post_meta(esc_attr($post_id, '_featured-post', esc_attr($_REQUEST['featured-post']))); 
        // I like using _ before my custom fields, so they are only editable within my form rather than the normal custom fields UI
}
add_action('save_post', 'save_featured_meta');

然後在您的模板文件中,使用以下主循環:

    $args = array(
        'meta_key' => '_featured-post', // include underscore prefix in key name
        'meta_value' => 1
    );
    // The number of posts displayed would be determined under Settings->Reading
    query_posts($args);

    if(have_posts()): while(have_posts()): the_post();
        // Do your bidding here

    endwhile; else:

    endif;

僅用於示例目的:對於自定義循環 (如果在一個頁面上運行多個循環),則可以使用:

    $args = array(
        'posts_per_page' => 5,
        'meta_key' => '_featured-post',
        'meta_value' => 1
    );

    $featured = new WP_Query($args);

    if ($featured->have_posts()): while($featured->have_posts()): $featured->the_post();
        the_title();
        the_content();
    endwhile; else:

    endif;

參考文獻

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