กลายเป็นแสดงโพสเดียว
สาเหตุที่แสดงแค่โพสต์เดียว เป็นเพราะค่าเริ่มต้นของ WordPress (ในเมนู Settings > Reading) มักจะตั้งไว้ให้ดึงมาแค่ 10 โพสต์ครับ พอเราเอามาแบ่งส่วนเป็น Slider(5) + Grid1(1) + Grid2(2) + Grid3(3) + Grid4(4) มันต้องใช้ทั้งหมด 15 โพสต์ ถึงจะแสดงผลครบทุกแถวครับ
เพื่อให้หน้าแรกดึงข้อมูลมาเพียงพอสำหรับ Layout นี้ เราต้องไปสั่ง “บังคับ” ให้หน้าแรกดึงโพสต์ออกมามากกว่าปกติครับ
วิธีแก้ไข 1: แก้ไขใน WordPress Admin (ง่ายที่สุด)
- ไปที่หลังบ้าน WordPress เมนู Settings (ตั้งค่า) > Reading (การอ่าน)
- ตรงช่อง Blog pages show at most (หน้าบล็อกแสดงสูงสุด) ให้เปลี่ยนจาก 10 เป็น 15 หรือ 20 ครับ
- กด Save Changes
วิธีแก้ไข 2: บังคับผ่าน Code (แนะนำ เพราะจะไม่กระทบหน้าอื่น)
นำโค้ดชุดนี้ไปวางต่อท้ายในไฟล์ functions.php ครับ โค้ดนี้จะสั่งให้เฉพาะหน้าแรกดึงบทความมา 15 บทความเพื่อให้พอดีกับ Layout ที่เราสร้างครับ
PHP
/**
* บังคับจำนวนโพสต์เฉพาะหน้าแรกให้พอดีกับ Layout Magazine
*/
function insurance_customize_query( $query ) {
if ( $query->is_home() && $query->is_main_query() && !is_admin() ) {
$query->set( 'posts_per_page', 15 ); // ดึงมา 15 โพสต์
}
}
add_action( 'pre_get_posts', 'insurance_customize_query' );
3. ปรับปรุงไฟล์ index.php (กันเหนียว)
ผมปรับโค้ดเพิ่มเงื่อนไขว่า “ถ้าโพสต์ไม่พอ ให้แสดงเท่าที่มี” เพื่อไม่ให้หน้าเว็บดูว่างเปล่าครับ โดยใช้คำสั่ง count() เช็คจำนวนจริงที่ดึงมาได้:
PHP
<?php get_header(); ?>
<main class="container" style="margin-top: 20px;">
<?php
$all_posts = array();
if (have_posts()) :
while (have_posts()) : the_post();
$all_posts[] = array(
'title' => get_the_title(),
'link' => get_permalink(),
'img' => get_insurance_image(get_the_ID()),
'date' => get_the_date(),
'views' => get_post_views(get_the_ID())
);
endwhile;
endif;
$total = count($all_posts);
$i = 0;
// แสดงส่วน Slider (สูงสุด 5 หรือเท่าที่มี)
if ($total > 0) : ?>
<section class="mag-slider" style="display: flex; overflow-x: auto; scroll-snap-type: x mandatory; gap: 10px; margin-bottom: 40px; border-radius: 15px;">
<?php
$slider_limit = min(5, $total);
for ($j = 0; $j < $slider_limit; $j++) : $p = $all_posts[$i++]; ?>
<div style="flex: 0 0 100%; scroll-snap-align: start; position: relative; height: 400px;">
<a href="<?php echo $p['link']; ?>">
<img src="<?php echo $p['img']; ?>" style="width:100%; height:100%; object-fit:cover;">
<div style="position:absolute; bottom:0; background:linear-gradient(transparent, rgba(0,0,0,0.8)); color:#fff; padding:30px; width:100%;">
<h2 style="margin:0; font-size:1.8rem;"><?php echo $p['title']; ?></h2>
</div>
</a>
</div>
<?php endfor; ?>
</section>
<?php endif; ?>
<?php
// ตัวอย่างการวาด Grid 1 (ถ้ายังมีโพสต์เหลือ)
if ($i < $total) :
$p = $all_posts[$i++]; ?>
<section style="margin-bottom: 40px;">
</section>
<?php endif; ?>
</main>
ลองใช้วิธีที่ 1 (แก้ใน Settings) ดูก่อนนะครับ เพราะง่ายที่สุด ถ้าโพสต์ในระบบมีมากกว่า 15 โพสต์ มันจะไหลลงมาครบทุก Grid ทันทีครับ!
ถ้าในฐานข้อมูลคุณมีโพสต์ไม่ถึง 15 โพสต์ อยากให้ผมปรับให้ Grid มัน “วนซ้ำ” บทความเดิมมาโชว์ให้เต็มไหมครับ?