An easy way to get the actual page ID in WordPress

Last modified April 15, 2020
.* :☆゚

get_the_ID() only gets you so far in WordPress because it only gives you the relevant page ID when you are on a page or post.

Say you wanted to set a feature image or reference a custom field from a page such as the shop, which is a post type archive.

You set a featured image on the shop page but calling get_the_ID() in the template gives you the ID of the first product instead.

This is because when you call get_the_ID() on archive pages, WordPress defaults to the first post of the post type rather than look for a page with the same name first.

To get around this, I often use my own custom function to get the actual page ID. It is esentially full of conditionals which I customise for my own needs according to the site I’m working on, and returns either the post ID or the term ID.

Since I often allow custom feature sliders and videos alongside the default feature images, I find this method very handy in managing the retrieval of content across the site no matter what context you are in. You can even set a featured image for the blog page using get_option('page_for_posts').

Simply paste the snippet below into your functions.php and edit as you need.

<?php

function get_page_ID() {
  //get the blog page ID
  if ( is_home() ) {
    $ID = get_option('page_for_posts');

  //get the shop page ID
  } elseif ( is_post_type_archive('product')) {
    $pageobj = get_page_by_path('shop');
    $ID = $pageobj->ID;

  // get the term id (useful if you set any custom fields on taxonomies)
  } elseif ( is_tax() ) {
    $query = get_queried_object();
    $ID = $query->term_id;

  //get the default post ID
  }else {
    $ID = get_the_ID();
  }
  return $ID;
}