Skip to main content
1 of 2
Alex
  • 127
  • 1
  • 8

How to call get_post()?

I have a sidebar on my site and there I want to show the current post's meta information, such as the last modified date, the author and more.

Thus I wrote the following function:

function showPostMetaInfo()
{   
    global $post;

    setup_postdata($post);

    $mypost = get_post();

            $string.= "<table id='meta-info'>"
                    . "<thead>"
                    . "<tr>"
                    . "<th> Meta Type </th>"
                    . "<th> Value"
                    . "</tr>"
                    . "</thead>"
                    . "<tbody>"
                    . "<tr>"
                    . "<td> Title </td>"
                    . "<td>".get_the_title()."</td>"
                    . "</tr>"
                    . "<tr>"
                    . "<td> Author </td>"
                    . "<td>".get_the_author()."</td>"
                    . "</tr>"
                    . "<tr>"
                    . "<td> Published </td>"
                    . "<td>".get_the_date()."</td>"
                    . "</tr>"
                    . "<tr>"
                    . "<td> Last Modified </td>"
                    . "<td>".get_the_modified_date()."</td>"
                    . "</tr>"
                    . "<tr>"
                    . "<td> Categories </td>"
                    . "<td>".listCategories()."</td>"
                    . "</tr>"
                    . "<tr>"
                    . "<td> Tags </td>"
                    . "<td>".listTags()."</td>"
                    . "</tr>"
                    . "</tbody>"
                    . "</table>";
    
    return $string;
}

However, var_dump($mypost) returns NULL.

From what I understand this is because I call get_post() before the information is ready.

My problem now is that I don't know WHERE and HOW and AFTER WHICH HOOK to call add_action(...) properly. The function responsible for the sidebar is createPageInfo( $type ) where $type can be single, page or null. How to pass that argument $type to add_action properly?

I might have a conceptual misunderstanding but here's roughly how i built my current site:

index.php:

...
get_header();
createMainPanel();
get_sidebar();
get_footer();
...

sidebar.php:

 ...
 if( is_single() || is_page() )
    {
        if( is_single() ){createPageInfo( "single" );}
        elseif ( is_page() ){createPageInfo( "page" );}
    }
    
    else
    {
        createPageInfo ( null );
    }
 ...
Alex
  • 127
  • 1
  • 8