Search code examples
phparrayswordpresspluginscustom-post-type

Getting Trying to get property 'ID' of non-object and Undefined index: ID while accessing the array


I have below the code and I have to get the post id using the post title.

        $atts['speakersname']='abc,xyz,prq'; // post title 
        $getspeakertitle=explode( ',', $atts['speakersname']);
        $speakerpostid[]='';
        foreach ($getspeakertitle as $key => $value) {
         $speakerpostid[] = get_page_by_title( $value, OBJECT, 'speaker' );
        } 
       echo"<pre>";
       print_r($speakerpostid); 
       print_r($speakerpostid->ID);
       print_r($speakerpostid['ID']);
       print_r($speakerpostid[0]['ID']); 

I have tried this and I am getting an error

print_r($speakerpostid->ID);

Notice: Trying to get property 'ID' of non-object in

print_r($speakerpostid['ID']);

Notice: Undefined index: ID in

Tried below code also it's displaying first id value

  print_r($speakerpostid[0]['ID']);

I have to pass the ID to the below code

$s_post = get_posts(array(
          'showposts' => 10, 
          'post_type' => 'speaker',
          'post_status'  => 'publish',
          'post__in'  => array('34'), // I have to pass id here to get all the details
            )
           );

Any idea what i am doing wrong here


Solution

  • Try this:

    You are getting the whole post object in the $speakerpostid array. You need to store only the post id.

    $atts['speakersname'] = 'abc,xyz,prq'; // post title
    $getspeakertitle = explode(',', $atts['speakersname']);
    $speakerpostid = array();
    foreach ($getspeakertitle as $value) {
        $page_obj = get_page_by_title($value, OBJECT, 'speaker');
        $speakerpostid[] = $page_obj->ID;
    }
    echo "<pre>";
    print_r($speakerpostid);