[WordPress] วิธีเก็บ get_template_part ลงตัวแปร

ล่าสุดต้องทำ Endpoint (API) ใช้ใน WordPress ครับ แล้วจะหาวิธีเรนเดอร์ HTML ด้วย get_template_part จาก PHP เลย ซึ่งตอนแรกเขียนเป็น AJAX ใน wp-ajax เลย ซึ่งสามารถใช้ get_template_part ได้เลยโดยไม่ต้องส่ง JSON

ปัญหา: คือ wp-ajax ไม่สามารถแคชได้ ทำให้เว็บหน่วง เลยไปทำ API ด้วย Rewrite Rule แทน แต่แบบนี้ต้องส่ง responsive เป็น JSON ทำนั้น เลยต้องมาหาวิธีเอา get_template_part ลงตัวแปรอีก เพื่อจะส่ง JSON ได้

ปัญหา 2: get_template_part ไม่ return อะไรกลับมาเลย เค้าบอกว่ามัน echo เองอัตโนมัติ เลยใช้ $x = get_template_part อะไรแบบนี้ไม่ได้

คุณ Simon บอกว่าต้องใช้ Buffering

function load_template_part($template_name, $part_name=null) {
    ob_start();
    get_template_part($template_name, $part_name);
    $var = ob_get_contents();
    ob_end_clean();
    return $var;
}

ทำแบบนี้แล้วสามารถเก็บ get_template_part ลงตัวแปร เอาไปใช้ต่อได้เลย

ป.ล. เวลาทำ API ด้วย Rewrite Rule อย่าลืมอัพเดท Permalink หรือ flush_rewrite_rules() ทุกครั้งที่แก้โค้ด

Reference: http://stackoverflow.com/questions/5817726/wordpress-save-get-template-part-to-variable


Posted

in

,

by

Tags:

Comments

Leave a Reply

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