I have the following error Attempt to read property "ID" on null
in this code snippet
global $wp_query;
$categories = get_the_terms($wp_query->post->ID, 'live_stream_categories');
$cat_slug = '';
$live_stream_true = False;
if(!empty($categories)){
foreach ($categories as $cat) {
if($cat->slug != 'live-stream')
{
$cat_slug = $cat->slug;
}
if($cat->slug == 'live-stream')
{
$live_stream_true = True;
}
}
}
However I'm not sure what the workaround would be. Any advice? I've took over this site from a previous developer
I have the following error Attempt to read property "ID" on null
in this code snippet
global $wp_query;
$categories = get_the_terms($wp_query->post->ID, 'live_stream_categories');
$cat_slug = '';
$live_stream_true = False;
if(!empty($categories)){
foreach ($categories as $cat) {
if($cat->slug != 'live-stream')
{
$cat_slug = $cat->slug;
}
if($cat->slug == 'live-stream')
{
$live_stream_true = True;
}
}
}
However I'm not sure what the workaround would be. Any advice? I've took over this site from a previous developer
Where did you put that function ? that's better call that it inside the action, the error probably coming from missing variable.
add_action('init','newFunction');
function newFunction(){
global $wp_query;
// Do your code here
}
To fix that error (on php8 & over) try this:
global $wp_query;
$post_id = get_queried_object_id();
$categories = get_the_terms($wp_query->$post_id, 'live_stream_categories');
$cat_slug = '';
$live_stream_true = False;
if(!empty($categories)){
foreach ($categories as $cat) {
if($cat->slug != 'live-stream')
{
$cat_slug = $cat->slug;
}
if($cat->slug == 'live-stream')
{
$live_stream_true = True;
}
}
}
Issue coming if code is executed outside of the main WordPress loop or if there are no posts found by the query.
you can first check if $wp_query->post
is not null before attempting to access its properties. Additionally, it's good practice to check if $wp_query
itself is not null to avoid potential errors
global $wp_query;
if ($wp_query && $wp_query->post) {
$categories = get_the_terms($wp_query->post->ID, 'live_stream_categories');
$cat_slug = '';
$live_stream_true = false;
if (!empty($categories)) {
foreach ($categories as $cat) {
if ($cat->slug != 'live-stream') {
$cat_slug = $cat->slug;
}
if ($cat->slug == 'live-stream') {
$live_stream_true = true;
}
}
}
} else {
// Handle the case where there is no post available
// For example, you might set default values or display an error message
$cat_slug = '';
$live_stream_true = false;
}