Getting Post Permalink By Post Id Doesn’t Work

In my WordPress blog I am trying to get post permalink of a post of custom post type for which I add this code to function.php

function get_randomp() { ?>
<?php 
$args=array('post_type'=>'photo', 'orderby'=>'rand', 'posts_per_page'=>'1'); 
$photo=new WP_Query($args); while ($photo->have_posts()) : $photo->the_post();
?>
<?php echo get_the_ID(); ?>
<?php
endwhile;
wp_reset_postdata();
?>
<?php } ?>

and this added this code in sidebar.php to output the permalink,

Read More
<?php 
$postidr = get_randomp();
echo get_permalink( $postidr ); 
?>

But it is showing permalink of the current post which is being viewed.
Please help me guys.

Related posts

Leave a Reply

2 comments

  1. the working code is here, put this into your theme functions.php

    function get_randomp() { 
    
    $args=array('post_type'=>'photo', 'orderby'=>'rand', 'posts_per_page'=>'1'); 
    $photo=new WP_Query($args); while ($photo->have_posts()) : $photo->the_post();
    
    
    echo '<a href="' . get_permalink( get_the_ID() ) . '">';
    echo 'Link';
    echo '</a>';
    
    endwhile;
    wp_reset_postdata();
     }
     add_action( 'init', 'get_randomp',1);
    

    and call it as get_randomp(); wherever you want

  2. Your function shouldn’t echo the result, rather it should return it. You also have very malformed code, try this instead:

    function get_randomp() { 
        $args = array('post_type'=>'photo', 'orderby'=>'rand', 'posts_per_page'=>'1'); 
        $photos = new WP_Query($args); // Posts set to variable
    
        $photo = current($photos); // Get first, and only, post
    
        wp_reset_postdata(); // Reset posts
    
        return $photo->ID; // Return ID from post object
    }