問題描述

我想在 WordPress Loop 中的帖子 (如’Sponsors’) 中新增一個帖子 (來自特定類別) 。例:

P P P S P P S P P S P P

我該如何實現?我是一個初學者編碼,所以我不知道自己修改一個迴圈。任何迴圈編碼 Ninjas 在那裡可以提供一個解決方案?

請注意,以下是我當前的迴圈。它用於按價格或隨機順序排序帖子:

的 index.php

<?php while (have_posts() ) : the_post(); ?>
<h2><a href="<?php%20the_permalink()%20?>"><?php the_title(); ?></a></h2>
<?php  the_excerpt(); the_meta ();
endwhile;

previous_posts_link();
next_posts_link();
?>

的 functions.php

function my_custom_query($query){
 if ( $query->is_home() && $query->is_main_query() ) {

  $sort= $_GET['sort'];

  if($sort == "A"){
   $query->set( 'orderby', 'rand' );
   $query->set( 'posts_per_page', '2' );
  }

  if($sort == "B"){
   $query->set( 'meta_key', 'price' );
   $query->set( 'orderby', 'meta_value_num' );
   $query->set( 'order', 'DESC' );
   $query->set( 'posts_per_page', '2' );
  }
}
}

add_action( 'pre_get_posts', 'my_custom_query' );

編輯:更新

Birgire 的外掛工程!最初,我有問題讓外掛在我的主題工作。問題是我在 index.php 中的迴圈中使用的這段程式碼 (我用它來呼叫自定義欄位出現) 。

<?php
    global $wp_query;
    $postid = $wp_query->post->ID;
    echo get_post_meta($postid, 'price', true);
    wp_reset_query();
?>

最佳解決方案

自動贊助者帖子注射器:

這是一個基於 my answer 的一個想法:How to show Y number of custom posts after every X normal posts?

我希望使它更有用的 here on Github,但它可能會改進更多 (未來的工作) 。

SponsorPostsInjector 課程將幫助您使用過濾器 the_postloop_startloop_end 自動將贊助商帖子注入主題。

啟用外掛並將以下示例新增到 functions.php 檔案中以開始注入:

/**
 * Inject a sponsor post after the first post on the home page,
 * and then again for every third post within the main query.
 */

add_action( 'wp', 'my_sponsor_injections' );

function my_sponsor_injections()
{
    if( ! class_exists( 'SponsorPostsInjector' ) ) return;

    // We want the sponsor posts injections only on the home page:
    if( ! is_home()  ) return;

    // Setup the injection:
    $injector = new SponsorPostsInjector(
        array(
            'items_before_each_inject' => 3,
            'items_per_inject'         => 1,
            'template_part'            => 'content-sponsor',
        )
    );

    // Setup the injection query:
    $injector->query(
        array(
            'post_type'  => 'sponsor',
            'tax_query'  => array(
                array(
                   'taxonomy' => 'country',
                    'terms'   => 'sweden',
                    'field'   => 'slug',
                )
            )
        )
    );

    // Inject:
    $injector->inject();
}

我們在當前主題目錄中建立了 content-sponsor.php 模板檔案,以控制注入的贊助商帖子的佈局。

這個想法是,這也應該照顧分頁。

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

參考文獻

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