問題描述
我想在 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_post,loop_start 和 loop_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 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇。