7

Is that possible to get current post ID without passing in shortcode as parameter. Like [related-post] I want to get the post ID in which post this shortcode will use.

add_shortcode( 'related-article', 'related_article_title' );
function related_article_title( $atts ) {
    $post_id = get_the_ID();
    echo $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="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php endwhile; wp_reset_postdata(); ?>
    </div>
    <?php $myvariable = ob_get_clean();
    return $myvariable;
}
}
  • 1
    What does get_the_ID() returns? You can always find current post ID on global $post_id – Sisir Dec 2 '15 at 9:22
  • 2
    get_the_ID() return nothing here but global $post; $post_id = $post->ID; work for me. – Gorakh Shrestha Dec 2 '15 at 11:41
5
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="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        <?php endwhile; wp_reset_postdata(); ?>
    </div>
    <?php $myvariable = ob_get_clean();
    return $myvariable;
}
}
| improve this answer | |
4

Just as @gorakh-shrestha was trying, using global $post and then $post->ID, is a good way to proceed, even inside a shortcode

| improve this answer | |
  • Hi i am passing ajax callback to shortcode. And i want to get page id of current page on which shortcode is used. But i am not able to get the page id using global $post->ID; – Wordpress Learner Aug 30 '19 at 10:06
  • This is not a forum, it's just a place where you should comment the answer given. For that issue, don't be afraid to open up a new Question, after searching for already given answers, of course :-) – Erenor Paz Aug 30 '19 at 11:02
  • 1
    I have done with my issue.Thanks :) – Wordpress Learner Sep 3 '19 at 8:04

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.