Get current post id witout passing in shortcode

add_shortcode( 'related-article', 'related_article_title' );
function related_article_title( $atts ) {
    global $post;
    echo $post->ID; // currently viewing post id
    ob_start();
    $query = new WP_Query( array(
        'post_type' => 'post',
        'posts_per_page' => 1,
        'order' => 'DESC',
        )
    );
    if ( $query->have_posts() ) {   ?>
    <div class="menu-row">
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>
            Leggi anche: <a href="https://wordpress.stackexchange.com/questions/210518/<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php endwhile; wp_reset_postdata(); ?>
    </div>
    <?php $myvariable = ob_get_clean();
    return $myvariable;
}
}

Leave a Comment