How to not load comments form on post preview?

I need a way not to load the comments form when previewing a post, is there a way to achieve this? How?

If you need a reason to help: I use disqus and it generates a url for the "discussion" the first time the comment form loads, if this is the preview then it will look something like site.com/?post_type=foodp=41009 And this is a problem because afterwards when the post is published under a real url disqus will not recognize the comments count. The only way is to manually change the discussion url. I've already contacted disqus and they say, "not a bug" if you do not want disqus to pick the preview url, don't load disqus on the preview page, the only way i know is to completely remove the comments form, so how would i go about this? Is there some sort of conditional for the preview page?

Topic disqus comments Wordpress

Category Web


I took a quick peek at the disqus plugin. This works in disabling the option before the plugin decides to print out the form.

add_filter( 'pre_option_disqus_active', 'wpse_conditional_disqus_load' );
function wpse_conditional_disqus_load( $disqus_active ) {
  if( is_preview() ){
    return '0';
  }

  return $disqus_active;

}

You could also try something like this (not tested)

add_filter( 'the_content', 'wpse_load_disqus');
function wpse_load_disqus( $content ){
  if( is_preview() ){
    return $content;
  }

  if( is_singular() ) { // displays on all single post types. use is_single for posts only, is_page for pages only

    $content .= ?>
      // You disqus script here
    <?php ;
  }

  return $content;

}

Here's one suggestion: Close the comments when previewing:

add_filter( 'template_redirect', function()
{
    if( is_preview() )
        add_filter( 'comments_open', '__return_false' );
} );

This should stop the comments_template() from loading if it's e.g. wrapped with

if( comments_open() ) 
    comments_template();

in your theme. There's also a comments_open() check within comment_form() to prevent the form from displaying if the comments are closed.

We could also do it manually in our child theme:

if( ! is_preview() ) 
    comments_template();

But I'm not sure though how it works with plugins like Disqus.

Here are some very interesting suggestions on how to interfere with the loading of comments_template().

PS: I noticed the the disqus_active option check in the dsq_can_replace() function:

if (get_option('disqus_active') === '0'){ return false; }

so we might try something like:

add_filter( 'template_redirect', function()
{
    is_preview() && add_filter( 'pre_option_disqus_active', 
         function( $value ) { return '0'; }
    );
} );

but note that this is untested!

About

Geeks Mental is a community that publishes articles and tutorials about Web, Android, Data Science, new techniques and Linux security.