Error shown for Trying to get property ‘roles’ of non-object in WordPress After Content for User Roles

Question

I have been struggling to code a function, which echoes a code, when the user role is ‘administrator’ or is um_verified’

Honestly i don’t know much of what it means, but still I want to solve this problem. This function picks up the user id for the given wordpress post, then gets the author data, using the Author Data it finds out the user role, and if the user role matched the if clause, it echoes it, the whole functions runs after content.

My implementation of the code which is given below gives the correct result, basically works, but it shows a error of “Trying to get property ‘roles’ of non-object” basically which means that the property should be an object.

How can i solve the error, basically I know something is wrong, because it piles up about 5mb of errors in just matter of few hours. Please help me correct the code, and also, please explain what does an object mean in PHP.

function Milyin_After_Content($content) { 
        if( is_single() ):
        ob_start();

     $user_meta=get_userdata(get_the_author_meta('ID'));
 $user_role=$user_meta->roles;
if (in_array("administrator", $user_role) | in_array("um_verified", $user_role)){
    echo '<svg height="12pt" viewBox="0 0 512 512" width="12pt" xmlns="http://www.w3.org/2000/svg"><path d="m256 0c-141.164062 0-256 114.835938-256 256s114.835938 256 256 256 256-114.835938 256-256-114.835938-256-256-256zm0 0" fill="#1f1fff"/><path d="m385.75 201.75-138.667969 138.664062c-4.160156 4.160157-9.621093 6.253907-15.082031 6.253907s-10.921875-2.09375-15.082031-6.253907l-69.332031-69.332031c-8.34375-8.339843-8.34375-21.824219 0-30.164062 8.339843-8.34375 21.820312-8.34375 30.164062 0l54.25 54.25 123.585938-123.582031c8.339843-8.34375 21.820312-8.34375 30.164062 0 8.339844 8.339843 8.339844 21.820312 0 30.164062zm0 0" fill="#fff"/></svg>  
    ';}
        $code_content_2 = ob_get_clean();
        $content .= $code_content_2;
        endif;
        return $content;
    }

add_filter('the_content', 'Milyin_After_Content_2', 10);

This is the code, and the code that i echo is just the normal html, basically the SVG tag, so there should not be a problem with it. If there exists a better approach or a built in WordPress function to check for an array of user roles, then that would be even better, but as this was the only method i found, please help me debug it, and improve it…

0
, , , , Aditya Agarwal 3 years 2019-10-30T08:15:51-05:00 0 Answers 82 views 0

Leave an answer

Browse
Browse