3 回答

TA貢獻(xiàn)1863條經(jīng)驗(yàn) 獲得超2個(gè)贊
剛剛在我的本地環(huán)境中嘗試了這段代碼,唯一的變化是數(shù)組post_type
中的值$args
,它似乎工作正常。
我建議做什么,如下所示:
仔細(xì)檢查該值是否
post_type
與帖子類型的 slug 相匹配。這可能只是一個(gè)拼寫錯(cuò)誤的情況,多年來,這件事讓我絆倒的次數(shù)比我愿意承認(rèn)的還要多。
您可以通過查找functions.php
函數(shù)register_post_type
調(diào)用來找到它。檢查該帖子類型下是否確實(shí)有已發(fā)布的帖子。再說一遍,我也曾多次遇到過這種情況。
此外,您可能需要考慮稍微整理一下代碼,以防止可能丟失某些內(nèi)容并使其在將來更易于管理。
循環(huán)訪問可用的帖子類型數(shù)組,然后WP_Query
為每個(gè)可用的帖子類型構(gòu)造一個(gè)數(shù)組,這是我首選執(zhí)行您所描述的任務(wù),它看起來像這樣:
<?php
? ? $post_types? ? ? ?= array( 'yourposttype', 'yourotherposttype' );
? ? $common_arguments = array(
? ? ? ? 'post_status'? ? => 'publish',
? ? ? ? 'order'? ? ? ? ? => 'ASC',
? ? ? ? 'posts_per_page' => -1,
? ? );
?>
<?php foreach ( $post_types as $post_type ): ?>
? ? <?php
? ? ? ? $post_type_argument = array( 'post_type' => $post_type );
? ? ? ? $arguments? ? ? ? ? = array_merge( $common_arguments, $post_type_argument );
? ? ? ? $query? ? ? ? ? ? ? = new WP_Query( $arguments );
? ? ?>
? ? <?php if ( $query->have_posts() ): ?>
? ? ? ? <?php while ( $query->have_posts() ) : $query->the_post(); ?>
? ? ? ? ? ? <?php // Example output ?>
? ? ? ? ? ? <?php the_title(); ?>
? ? ? ? <?php endwhile; ?>
? ? ? ? <?php wp_reset_postdata(); ?>
? ? <?php endif; ?>
? ??
<?php endforeach; ?>
這樣,如果您需要顯示另一種帖子類型,您可以將其添加到$post_types
數(shù)組中,而無需復(fù)制代碼塊。
最后,當(dāng)您使用時(shí),您是正確的wp_reset_postdata()
,這是在循環(huán)自定義之后運(yùn)行的推薦函數(shù)WP_Query
,wp_reset_query()
在這種情況下有點(diǎn)多余。

TA貢獻(xiàn)1830條經(jīng)驗(yàn) 獲得超9個(gè)贊
使用<?php wp_reset_postdata(); ?>
while 循環(huán)后解決了這個(gè)問題。

TA貢獻(xiàn)1966條經(jīng)驗(yàn) 獲得超4個(gè)贊
我找到了解決辦法!事實(shí)上,并不是 WP_Query() 循環(huán)導(dǎo)致了問題,而是保存正在顯示的帖子的輪播。每個(gè)循環(huán)都會(huì)將自定義帖子放入輪播中,并且我為頁面上的每個(gè)輪播重復(fù)使用相同的 id。這對(duì) JavaScript 來說效果不佳。
為了糾正這個(gè)問題,我在主 js 文件中復(fù)制了 JavaScript 函數(shù),但將 #original-name 更改為 #other-name。我還將 carousel id 更改為 other-name。
現(xiàn)在一切都按預(yù)期進(jìn)行。
- 3 回答
- 0 關(guān)注
- 197 瀏覽
添加回答
舉報(bào)