WordPress easily be able to add shortcode to insert PHP codes. When I added a shortcode which can make a list of specific posts. After that, comments form below shortcode can’t be removed. Why?

First, Added a hook of shortcode into the function.php. Then added a list.php file which will be listed a specific posts.

<div class="card border-primary">
<div class="card-header border-primary">Material</div>
<div class="card-body">
  <div class="row">
    <?php $posts = get_posts('numberposts=10&category=1'); global $post; ?>
    <?php if($posts): foreach($posts as $post): setup_postdata($post); ?>
    <div class="card mr-auto ml-auto mb-4" style="width: 22rem;">
      <div class="card-header"><?php the_title();?></div>
        <div class="card-body">
          <div align="center"><?php the_post_thumbnail(array(286, 180)); ?></div
>
          <h5 class="card-title"></h5>
          <p class="card-text"><?php the_excerpt();?></p>
          <a href="#" class="btn btn-primary">Download</a>
        </div>
    </div>
    <?php endforeach; endif; ?>
  </div>
</div>
</div>

list.php

Finally, added a shortcode, [myphp file=”list.php”] ,into page and reload. Comments form displayed. Why? I understand that to prohibit display a comment form, uncheck “Allow comments” of Discussion in the Edit page. Of course, it did.

Conclusion is $post context was override by specific posts. In short, comments_open() function doesn’t check right context.

<?php $save = $post;?>
<div class="card border-primary">
<div class="card-header border-primary">Material</div>
<div class="card-body">
  <div class="row">
    <?php $posts = get_posts('numberposts=10&category=1'); global $post; ?>
    <?php if($posts): foreach($posts as $post): setup_postdata($post); ?>
    <div class="card mr-auto ml-auto mb-4" style="width: 22rem;">
      <div class="card-header"><?php the_title();?></div>
        <div class="card-body">
          <div align="center"><?php the_post_thumbnail(array(286, 180)); ?></div>
          <h5 class="card-title"></h5>
          <p class="card-text"><?php the_excerpt();?></p>
          <a href="#" class="btn btn-primary">Download</a>
        </div>
    </div>
    <?php endforeach; endif; ?>
  </div>
</div>
</div>
<?php $post = $save;?>

To temporary fix this issue, before read specific posts, context has been saved, and end of process, it been restored.

Hope this will help you 😗