Co_123 Co_123 - 11 days ago 5
PHP Question

Permalink of specific post ID

Below the code I have on my page tot display the permalink of q specific post in Wordpress. It works, but I have the feeling it can be easier. Can somebody explain how?

<?php
$post_id = 26; // post id
$queried_post = get_post($post_id);
$title = $queried_post->post_title;
$content = $queried_post->post_content;
$perma = get_permalink($post_id);

if ( has_post_thumbnail() )
{
$image_src = wp_get_attachment_image_src( get_post_thumbnail_id(),’thumbnail’ );
}

echo '<a href="' . $perma . '" title="' . $title . '">';
echo $title;
echo '</a>';
echo '<img width="100%" src="' . $image_src[0] . '">';
echo $content;

?>

Answer

Well your code seems ok. However there are some improvements that can be made. For example, when you have the $queried_post object, you don't need to create additional variables for content and title. You can use this object properties to get the values.

Also you can use wordpress get_the_post_thumbnail to show featured image. Some formatting and it's almost perfect.

$post_id      = 26;  // post id
$queried_post = get_post($post_id); 

echo '<a href="' . get_permalink( $post_id ) . '" title="' . $queried_post->post_title . '">';
    echo $queried_post->post_title;
echo '</a>';

if ( has_post_thumbnail( $post_id ) ) {
    echo get_the_post_thumbnail( $post_id, 'full', array('width' => '100%') );
}

echo $queried_post->post_content;
Comments