Home > Enterprise >  How to display a button depending on the parameter in the shortcode?
How to display a button depending on the parameter in the shortcode?

Time:09-01

There are posts on the page that I display using a shortcode. I need to display a button if there are more than 3 posts. The button should be in a How can I add it there?

function posts() {
  $args = array(
    'posts_per_page' => 3,
    'offset' => 0,
    'orderby' => 'post_date',
    'order' => 'DESC',
    'post_type' => 'post',
    'post_status' => 'publish'
  );
  $query = new WP_Query($args);
  if ($query - > have_posts()):
    while ($query - > have_posts()): $query - > the_post(); ?>
    ...
   <? php
  endwhile;
  endif;
}

add_shortcode('display_posts', 'posts');
<div >
  <?php echo do_shortcode('[display_posts]'); ?>
</div>
<div >
 
</div>

CodePudding user response:

To count the number of posts you need to add the logic to the shortcode itself and the button needs to be within the outputted shortcode markup like so.

<?php
function get_posts()
{
    $args  = array(
        'posts_per_page' => 3,
        'offset'         => 0,
        'orderby'        => 'post_date',
        'order'          => 'DESC',
        'post_type'      => 'post',
        'post_status'    => 'publish'
    );
    $query = new WP_Query($args);
    if ($query->have_posts()):
        while ($query->have_posts()): $query->the_post();

        endwhile;
    endif;

    if ($query->post_count > 3) {
        echo '<button id="loadmore">Load More</button>';
    }

    echo '<div >';
    // More posts go here...
    echo '</div>';
}

add_shortcode('display_posts', 'get_posts');
?>

<div >
    <?php echo do_shortcode('[display_posts]'); ?>
</div>

You can then use AJAX to get load more posts when the 'Load more' button is clicked, assuming this is what you're trying to achieve?

  • Related