วิธีทำลิงค์ Previous / Next Post ใช้เองใน WordPress

เนื่องจากมีธีมที่ต้องทำแล้วต้องมีการทำลิงค์ Previous / Next Post ใช้เอง เนื่องจาก Output จากฟังก์ชั่นของ WordPress แก้ไขค่อนข้างยาก และลองแก้ดูแล้วไม่สำเร็จ T__T

Previous / Next Post ก็คือลิงค์ที่อยู่ใต้หน้าเนื้อหาบทความ เพื่อลิงค์ไปบทความก่อนหน้าอันที่อ่านอยู่ และหลังอันที่อ่านอยู่

ไปหาวิธีทำลิงค์ Previous / Next Post ใช้เอง ได้โค้ดจากเว็บฝรั่งมา วิธีนี้เราแก้ได้ทุกแท็กที่ Output ออกมา

<?php
$previous_post = get_adjacent_post(false, '', true);
$next_post = get_adjacent_post(false, '', false);
?>
<ul>
<?php if ($previous_post): // if there are older articles ?>
    <li class="prev">Previous post: <a href="<?php echo make_href_root_relative(get_permalink($previous_post)); ?>"><?php echo get_the_title($previous_post); ?></a></li>
<?php endif; ?>
<?php if ($next_post): // if there are newer articles ?>
    <li class="next">Next post: <a href="<?php echo make_href_root_relative(get_permalink($next_post)); ?>"><?php echo get_the_title($next_post); ?></a></li>
<?php endif; ?>
</ul>

เครดิต: 465bereaststreet

การจะใช้ฟังก์ชั่นข้างบน ต้องมี custom function เพิ่มชื่อ make_href_root_relative ด้วย

function make_href_root_relative($input) {
    return preg_replace('!http(s)?://' . $_SERVER['SERVER_NAME'] . '/!', '/', $input);
}

ฟังก์ชั่นนี้จะเปลี่ยนลิงค์ให้แทนที่จะเป็นแบบ www.example.com/post-name จะเหลือแค่ /post-name สั้น ๆ น่ารักฝุด ๆ


Posted

in

, , ,

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *