I'm currently working on a custom shortcode. I plan to make it enable to call related posts based on current category.

Here's the working code:

    function seniberpikir_bacajuga( $atts ) {
    global $post;
    // We should get the first category of the post
    $categories = get_the_category( $post->ID );
    $first_cat = $categories[0]->cat_ID;
    // Let's start the $output by displaying the title and opening the <ul>
    $output = '<h3>' . $title . '</h3>';
    // The arguments of the post list!
    $args = array(
        // It should be in the first category of our post:
        'category__in' => array( $first_cat ),
        // Our post should NOT be in the list:
        'post__not_in' => array( $post->ID ),
        // ...And it should fetch 5 posts - you can change this number if you like:
        'posts_per_page' => 4
    // The get_posts() function
    $posts = get_posts( $args );
    if( $posts ) {
        $output .= '<div class="bacajuga-konten"><h5 class="bacajuga-title">Baca <span style="color:#0c6;">Juga</span>:</h3><ul class="td-arrow-list">';
        // Let's start the loop!
        foreach( $posts as $post ) {
            setup_postdata( $post );
            $post_title = get_the_title();
            $permalink = get_permalink();
            $output .= '<li><a href="' . $permalink . '" title="' . esc_attr( $post_title ) . '" target="_blank">' . $post_title . '</a></li>';
        $output .= '</ul></div>';
    } else {
        // If there are no posts, we should return something, too!
        $output .= '<p>Sorry, this category has just one post and you just read it!</p>';
    echo $output;
add_shortcode('bacajuga', 'seniberpikir_bacajuga');

But the problem is, when I put the shortcode [bacajuga] in the middle of the content, for example, the related posts appear on top of the content instead.

Here are the screenshots:
#1 Shortcode Placement
Shortcode Placement

#2 Shortcode Output
Shortcode Output

Now, I want to place the related post wherever I put the shortcode around the content. So how can I fix it?

Any helps would be much appreciated. Here's the post link to look into: https://www.seniberpikir.com/alternatif-google-adsense-terbaik/

Thanking you in advance!

  • Don't echo your shortcode's output. you shoul return it. – Frank P. Walentynowicz May 12 '19 at 21:12
  • Nice, I forgot that part lol silly mistake but thanks so much :D – Walter P. May 21 '19 at 17:47

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.