1 year ago

#382683

test-img

compliance

WordPress - the_title() & the_content() are wrongly getting Post details instead of Page, after using shortcode

In about.php page, I have this shortcode to retrieve posts of a category:

<?php echo do_shortcode('[categoryposts catname="about-section-1"]'); ?>

functions.php:

 function wpb_postsbycategory($atts='') {

    // Get parameters\attributes from shortcode
    $attributes = shortcode_atts(
        array(
            'catname' => '',//this is default value
        ),
        $atts,
        'featured'
    );

   // the query
   $the_query = new WP_Query( array( 
       'category_name' => $attributes['catname'], 
       'posts_per_page' => 5
   ) );
      
   // The Loop
   $string = "";
   if ( $the_query->have_posts() ) {
       $string .= '<ul class="postsbycategory widget_recent_entries">';
       while ( $the_query->have_posts() ) {
           $the_query->the_post();
               if ( has_post_thumbnail() ) {
                    $string .= '<li>';
                    $string .= '<a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'</a></li>';
               } else { 
                    // if no featured image is found
                    $string .= '<li><a href="' . get_the_permalink() .'" rel="bookmark">' . get_the_title() .'</a></li>';
               }
            }
    } else {
        // no posts found
        $string .= '<li>No Posts Found</li>';
   }
   $string .= '</ul>';
      
   return $string;
      
   /* Restore original Post Data */
   wp_reset_postdata();
 }
 // Add a shortcode
 add_shortcode('categoryposts', 'wpb_postsbycategory');

Though about.php is a PAGE (since I linked it using Template Name), if I use the_title() & the_content():

  • before the shortcode line, they properly get current Page title & content.
  • but after the shortcode line, they wrongly get some Post title & content.

Question: How can I retrieve Page title & content (instead of Post), after having used shortcode?

php

wordpress

wordpress-shortcode

0 Answers

Your Answer

Accepted video resources