I have a custom post type archive archive-projects.php that I am using as a page template because I have some custom fields that I want to display. I am trying to get the post id of this page but either get null or the id of the first post in the archive depending on what I try. I have tried putting my code above the loop on my page but without any luck.
Apologies if this is a duplicate but I have tried searching many tutorials on this and still don't have an answer with my specific scenario of using a page template with a custom post type archive.
I have tried this code and it works but I am still stumped as to why none of the other methods seem to work. I'm reluctant to keep this as a solution because if the user changes the page slug this won't work anymore:
$my_page_id = get_id_by_slug('projects'); function get_id_by_slug($page_slug) { $page = get_page_by_path($page_slug); if ($page) { return $page->ID; } else { return null; } } I have tried the following without success (above my custom loop in my template):
get_queried_object_id(); // returns nothing $page_id = $wp_query->get_queried_object_id(); // returns 0 global $post; // I've tried including this and removing with same effect $post = $wp_query->post; $post_id = $post->ID; // returns the id of the first post in my archive Any ideas on what I am doing wrong or the right way to get the actual id of my projects page?
UPDATE My custom post type had has_archive set to true. I tried creating a custom template but due to WordPress hierarchy it was looking for an archive page. I solved my issue by setting has_archive to false and creating a custom template called page-template-projects.php. I was then able to setup a page called Projects and use my custom template, while being able to correctly get an ID for the page.