Support » Fixing WordPress » Custom shortcodes ruin post data

  • Resolved Ahmad Rulim

    (@falkia34)


    I have this custom shortcode to show random read more link inside a post, but when i use the shortcode, the post detail (like tag, category, next post, previous post) is ruined (inaccurate). Any idea how to fix this?

    
    // Add random read more shortcode
    function random_read_more_shortcode() {
        $args = array(
            'post_type'      => 'post',
            'orderby'        => 'rand',
            'posts_per_page' => 1,
        );
    
        $the_query = new WP_Query($args);
    
        if ($the_query->have_posts()) {
            while ($the_query->have_posts()) {
                $the_query->the_post();
    
                return '<a href="' . get_permalink() . '" target="_blank" class="read-more-link"><div class="read-more-box"><span class="prefix">Lihat juga: </span><span class="title">' . get_the_title() . '</span></div></a>';
            }
    
            wp_reset_postdata();
        }
    }
    add_shortcode('random_read_more', 'random_read_more_shortcode');
    
Viewing 1 replies (of 1 total)
  • Joy

    (@joyously)

    Inside the loop, you are returning the result. So it never reaches the call to wp_reset_postdata().

Viewing 1 replies (of 1 total)
  • The topic ‘Custom shortcodes ruin post data’ is closed to new replies.