Using WordPress ‘oembed_request_post_id’ PHP filter

The oembed_request_post_id WordPress PHP filter allows you to modify the determined post ID used in an oEmbed request.

Usage

add_filter('oembed_request_post_id', 'your_custom_function', 10, 2);
function your_custom_function($post_id, $url) {
    // your custom code here
    return $post_id;
}

Parameters

  • $post_id (int) – The determined post ID.
  • $url (string) – The requested URL.

More information

See WordPress Developer Resources: oembed_request_post_id

Examples

Change post ID based on the requested URL

Modify the post ID if the requested URL contains a specific query string.

add_filter('oembed_request_post_id', 'change_post_id_based_on_url', 10, 2);
function change_post_id_based_on_url($post_id, $url) {
    if (strpos($url, 'custom_query=example') !== false) {
        $post_id = 123;
    }
    return $post_id;
}

Return a custom post ID for a specific URL pattern

Set a custom post ID for any URL that matches a specific pattern.

add_filter('oembed_request_post_id', 'custom_post_id_for_url_pattern', 10, 2);
function custom_post_id_for_url_pattern($post_id, $url) {
    if (preg_match('/example-domain\.com\/custom-path\/(\d+)/', $url, $matches)) {
        $post_id = (int)$matches[1];
    }
    return $post_id;
}

Disable oEmbed for specific post IDs

Prevent oEmbed requests for specific post IDs by returning false.

add_filter('oembed_request_post_id', 'disable_oembed_for_specific_ids', 10, 2);
function disable_oembed_for_specific_ids($post_id, $url) {
    $disabled_ids = array(12, 34, 56);
    if (in_array($post_id, $disabled_ids)) {
        return false;
    }
    return $post_id;
}

Modify post ID based on a custom meta value

Change the post ID for oEmbed requests based on a custom meta value.

add_filter('oembed_request_post_id', 'modify_post_id_based_on_meta', 10, 2);
function modify_post_id_based_on_meta($post_id, $url) {
    $custom_meta_value = get_post_meta($post_id, 'your_custom_meta_key', true);
    if ($custom_meta_value) {
        $post_id = (int)$custom_meta_value;
    }
    return $post_id;
}

Swap post ID with its parent ID

Replace the post ID with its parent post ID for oEmbed requests.

add_filter('oembed_request_post_id', 'swap_with_parent_post_id', 10, 2);
function swap_with_parent_post_id($post_id, $url) {
    $parent_id = wp_get_post_parent_id($post_id);
    if ($parent_id) {
        $post_id = $parent_id;
    }
    return $post_id;
}