Hi there,
I'm writing a plugin in which I relate some posts and data.
I'm having the following problem:
- I have a function ie: prefix_get_post_by_meta()
, and it contains something like:
function prefix_get_post_by_meta( $meta_value ){
$args = array(
'numberposts' => 1,
'post_type' => 'my_post_type',
'meta_key' => 'my_key',
'meta_value' => $meta_value
);
// get results
$the_query = new WP_Query( $args );
// The Loop
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ):
$the_query->the_post();
return get_the_ID();
endwhile;
endif;
wp_reset_postdata();
return false;
}
Everything goes great with that function.
The problem is that at certain point when I use this function in another function for a shortcode or in the front end it doesn't return anything.
Imagine I have another function my_shortcode_function()
function my_shortcode_function(){
$my_id = prefix_get_id_from_api(); // this gives a unique ID that match with the custom field value
$the_post_id = prefix_get_post_by_meta( $my_id );
$output = '';
if ( $match_id ){
$output .= '<h1>' . get_the_title( $the_post_id ) . '</h1>';
$output .= '<h1><a href="'. get_permalink( $the_post_id ) .'">' . get_the_title( $the_post_id ). '</a></h1>';
}else{
$output .= 'Nothing for the ID ' . $my_id;
}
return $output;
}
add_shortcode( 'my_shortcode_function', 'my_shortcode_function' );
----
If I invoque the function directly from the shortcode, I get nothing as a response, when the post actually exists.
If I modify the function to echo the $output, and add that as an action for the init:
add_action( 'init', 'my_shortcode_function' );
I get the accurate result on the backend. On the front end, I get the wrong result.
----
If I stay with the echo instead of returning the $output, and I call the function directly on my plugin, like
my_shortcode()
;
Then I get this:
Fatal error: Call to undefined function is_user_logged_in() in /Applications/MAMP/..../wp-includes/query.php on line 2778
It's obvious that is a runtime thing. Is there something that I'm missing?
Every query function end up using WP_Query(), that's why I assumed that this wasn't the problem, am I right? (I tried with get_posts just in case and the same happened).
any help is super appreciated :)
Juanfra.