• Hello,

    I was trying to make my website load the whole comment section only after a button is clicked, but was not able to find anything certain. Many people also say that this is insecure.

    Can you help me and create a simple code that would maybe load a comments.php template or a comments section in some way that is completely safe and secure after a button was pressed?

    Thank you so much!

Viewing 3 replies - 1 through 3 (of 3 total)
  • Moderator bcworkz

    (@bcworkz)

    I’m not sure what the perceived insecurity is. Almost anything is insecure if not done correctly. The corollary being almost anything can be secure if done correctly.

    First identify the part of the single post template which loads the comments. Replace that with a button whose click invokes JavaScript which makes an Ajax query to fetch the comments. Also output an empty div container in which script can insert the comments once they come back from the Ajax request.

    The Ajax handler does need to assume anything requesting it could be suspect and it should properly validate and sanitize any data passed with the request. You may only need the post ID for the comments as passed data. Type casting it as (int) will be adequate sanitation. Confirming it’s not negative and withing a certain range could be additional validation. The handler can include your theme’s comment.php template in order to generate the output to be used to insert into the empty div container. It’s best to use output buffering so template output can be collected into a single variable and returned all at once to the calling script.

    Some general information on using Ajax in WP:
    https://developer.www.ads-software.com/plugins/javascript/ajax/

    Thread Starter H-var

    (@hvar)

    Thank you so much for showing interest in my topic!

    It is difficult to make it into an actual working example. Could you please write a simple functions.php and a javascript code and an html part to show how it will work on a wordpress website? Thank you

    • This reply was modified 4 years, 7 months ago by H-var.
    Moderator bcworkz

    (@bcworkz)

    There’s nothing simple about Ajax ?? The examples in the docs pages I linked to don’t even quite work as a whole. They were meant as illustrative examples, actual functioning was not the primary concern. I made my own working version some time ago. It doesn’t do anything like what you want, but at least it’s working Ajax code that you can start with. I hope it helps some.
    https://pastebin.com/3VxAWpqZ

    You’ll want to make use of output buffering to manage template output.
    https://www.php.net/manual/en/book.outcontrol.php

Viewing 3 replies - 1 through 3 (of 3 total)
  • The topic ‘Click a button to load comment section’ is closed to new replies.