I am trying to get the ID (outside of loop) of a page which have a loop of another CPT within its content using a shortcode.
If I do a print_r
of get_queried_object()
, all I get the args used to register the CPT
If I echo
$post->ID
I get the ID of the last item in the secondary loop.
If I echo
get_queried_object_id()
, I get 0
all the time.
Here is the code I am currently using
function get_meta_values() {
global $post;
$queried_object = get_queried_object();
echo '<pre>';
print_r( $queried_object ); //Returns args used to register the CPT
echo '<br> $queried_object->ID: ' . $queried_object->ID; //Returns Nothing
echo '<br>get_queried_object_id(): '. get_queried_object_id(); // Returns 0 all the time
echo.'<br>PageID: ' . $post->ID; // Returns the ID of last item in the secondary loop
echo '</pre>';
}
add_action( 'wp_footer', 'get_meta_values' );
My goal is to get the ID of the page (where the shortcode is) to retrive some custom field values.
EDIT: I am using WooCommerce, but the shortcode that outputs the products is custom. I know I could bypass the issue by other means, but just curious why this is not working.
1 Answer
As others figured already out: If you have third party plugins with custom queries, you’ll have a bad day!
One solution might be caching your results.
Template (e.g.: page.php)
while (have_posts()): the_post();
global $my_cached_data;
$post_id = get_the_ID();
/*
* If you have single meta keys, this array_map function
* makes them easy to access; otherwise just use:
*
* $my_cached_data[$post_id] = get_post_meta( $post_id)
*/
$my_cached_data[$post_id] = array_map(
function( $a )
{
return $a[0];
},
get_post_meta( $post_id)
);
endwhile;
footer.php
global $my_cached_data;
echo "<pre>".print_r($my_cached_data, true)."</pre>";
Possible Result (with Page ID 2 and 15 having the same post meta data)
array(2) {
[2]=>
array(2) {
["meta_key"]=>
string(10) "meta_value"
["another_key"]=>
string(10) "meta_value"
}
[15]=>
array(2) {
["meta_key"]=>
string(10) "meta_value"
["another_key"]=>
string(10) "meta_value"
}
}