I've written a function to display a custom sidebar, which is outputted as a sidebar. On some pages, I have a Custom Field called 'show_sidebar', which I can assign as 'false' on pages which I do not want to display the Sidebar.
On the pages, I have some more shortcodes set up to initiate a loop for specific post categories. I need to show the sidebar on each page (through page.php in theme files), with 4 posts printed, each of the same category of the main posts (they are all the same category).
Problem is, to get the Custom Field, I need to use the global $post;
method to get the Page ID and not the Post ID (none of the posts will have the Custom Field set as there is no point). This all works fine and I can get the value of Custom Field just fine. However, when I echo the shortcode, I need the ID of the posts on the page (generated through the loop shortcode I wrote).
Here is my code:
function showSidebar() {
global $post; // so I get the Page ID, not the Post IDs
$customField = get_post_meta($post->ID, 'show_sidebar', true);
if ($customField == 'true' || empty($customField)) {
$showSidebar = true;
} elseif ($customField = 'false') {
$showSidebar = false;
} // get value of Custom Field 'show_sidebar' and check if it was true or false
$postCat = get_the_category($post->ID); // here is where I need to use the Post ID, not the Page ID
if ($showSidebar) {
echo do_shortcode('[sidebar category="'. $postCat[0]->name .'" no_of_posts="4" title="Latest '. $postCat[0]->name .'"]');
} // shortcode is initiated
}
So my question is, how can I use the Page ID in one part of the function, and Post ID in another part?
Pages
andPosts
you can use the$post->post_type
- one will be a page, the other a post. Another method would be to use conditionals such asis_home()
oris_single()
. Again not 100% sure what you're looking for so hope that helps.