Blog / WordPress / WordPress

WordPress Get Post ID - Complete Guide with Methods

Mahesh Mahesh Waghmare
4 min read

Getting the post ID is fundamental in WordPress development. Whether you’re building themes, plugins, or custom functionality, knowing how to retrieve the current post ID is essential.

This guide covers all methods to get post IDs in WordPress, from simple functions to advanced techniques.

Introduction

Why Get Post ID?

  • Retrieve post meta data
  • Build custom queries
  • Create post relationships
  • Generate custom URLs
  • Implement post-specific functionality

Common Scenarios:

  • Single post pages
  • Archive pages
  • Custom post types
  • AJAX requests
  • Admin areas

get_the_ID() Function

Basic Usage

Most common method:

$post_id = get_the_ID();
echo $post_id;

In the Loop:

if (have_posts()) {
    while (have_posts()) {
        the_post();
        $post_id = get_the_ID();
        echo "Post ID: " . $post_id;
    }
}

Outside the Loop

On single post page:

// Works on single post pages
$post_id = get_the_ID();

On archive pages:

// Gets ID of current post in loop
$post_id = get_the_ID();

Return vs Echo

get_the_ID() returns the ID (use this):

$id = get_the_ID();

the_ID() echoes the ID directly:

the_ID(); // Outputs ID directly
Advertisement

Using $post Global

Access Global $post

global $post;
$post_id = $post->ID;

Check if Post Exists

global $post;
if (isset($post->ID)) {
    $post_id = $post->ID;
}

Safety Check

global $post;
$post_id = isset($post) && isset($post->ID) ? $post->ID : null;

In Functions

function get_current_post_id() {
    global $post;
    return isset($post->ID) ? $post->ID : 0;
}

$id = get_current_post_id();

get_queried_object()

Get Current Queried Object

$queried_object = get_queried_object();
$post_id = $queried_object->ID;

With Type Check

$queried_object = get_queried_object();

if ($queried_object && isset($queried_object->ID)) {
    $post_id = $queried_object->ID;
}

For Custom Post Types

$queried_object = get_queried_object();

if (is_singular() && $queried_object) {
    $post_id = $queried_object->ID;
}

From URL Parameters

Get from Query String

// From URL: ?p=123
$post_id = isset($_GET['p']) ? intval($_GET['p']) : 0;
// Extract ID from URL
$url = 'https://example.com/2024/01/24/post-name/';
$post_id = url_to_postid($url);

Get Current URL Post ID

global $wp;
$current_url = home_url($wp->request);
$post_id = url_to_postid($current_url);

From REST API

// In REST API endpoint
$post_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

Database Queries

Direct Database Query

global $wpdb;

// Get post ID by slug
$post_id = $wpdb->get_var($wpdb->prepare(
    "SELECT ID FROM {$wpdb->posts} WHERE post_name = %s AND post_type = 'post'",
    'post-slug'
));

Get ID by Title

global $wpdb;

$post_id = $wpdb->get_var($wpdb->prepare(
    "SELECT ID FROM {$wpdb->posts} WHERE post_title = %s AND post_status = 'publish'",
    'Post Title'
));

Get ID by Meta Value

global $wpdb;

$post_id = $wpdb->get_var($wpdb->prepare(
    "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key = %s AND meta_value = %s",
    'custom_key',
    'custom_value'
));
Advertisement

Using Hooks and Filters

In Action Hooks

add_action('wp_head', function() {
    $post_id = get_the_ID();
    // Use post ID
});

In Filter Hooks

add_filter('the_title', function($title, $post_id) {
    // $post_id is passed automatically
    return $title;
}, 10, 2);

Get ID in save_post Hook

add_action('save_post', function($post_id, $post) {
    // $post_id is passed as parameter
    // Use post ID
}, 10, 2);

Best Practices

Always Validate

$post_id = get_the_ID();

if ($post_id) {
    // Use post ID
} else {
    // Handle case when ID not available
}

Sanitize Input

// When getting from URL
$post_id = isset($_GET['p']) ? absint($_GET['p']) : 0;

// absint() ensures positive integer

Check Post Exists

$post_id = get_the_ID();

if ($post_id && get_post($post_id)) {
    // Post exists, use ID
} else {
    // Post doesn't exist
}

Use Helper Function

function get_safe_post_id() {
    $post_id = get_the_ID();
    
    if (!$post_id) {
        global $post;
        $post_id = isset($post->ID) ? $post->ID : 0;
    }
    
    return absint($post_id);
}

$id = get_safe_post_id();

Quick Reference

In Loop: get_the_ID() Global: $post->ID Queried Object: get_queried_object()->ID From URL: url_to_postid($url) Database: Direct $wpdb query

Conclusion

Getting post ID in WordPress:

  1. Use get_the_ID() in the loop (most common)
  2. Use $post->ID when global is available
  3. Use get_queried_object() for queried objects
  4. Validate and sanitize all input
  5. Check post exists before using ID

Key Points:

  • get_the_ID() is the standard method
  • Always validate post ID exists
  • Sanitize when getting from user input
  • Use appropriate method for context

Mastering post ID retrieval is essential for WordPress development.

Advertisement
Mahesh Waghmare

Written by Mahesh Waghmare

I bridge the gap between WordPress architecture and modern React frontends. Currently building tools for the AI era.

Follow on Twitter

Read Next