Add metadata to an ElggObject

I have an ElggObject that works pretty much like The Wire. How can I add metadata to this?  Basically, I'm looking to add two extra fields to each post. The point is to later try query/filter based on the value of this extra item.

  • @RvR thanks for the brilliant reply. I have a doubt tough, the method requests a user entity, I should then attach it to the user?, my code goes like this:

    $post = new ElggObject();
    
    $post->subtype = 'match';
    
    $post->owner_guid = $userid;
    
    $post->access_id = $access_id;
    
    // this is what I'm looking ot add to the object.
    
    $post->somedata = $somedata1;
    
    $post->moredata = $somedata2;

    Then if I understood correctly, in order to add `somedata`and `moredata` to that object, I should then attach the metadata to ...the user?

    create_metadata($userid, 'somedata', $somedata1, 'text', $userid, 2);

    If so, I'm a bit confused. How would I get this metadata to display?  By getting the userId from getObjectEntity() then trying to get the user?   would this be the right way to do it?

  • Edited

    If you want to add metadata to 'object' ($post) then you should create metadata for it:

    create_metadata($post->guid, 'metadata_name', 'metadata_value', 'text', $userid, ACCESS_PUBLIC);

    For getting metadata from $post just use:

    $somedata1 = $post->somedata;
    
    $somedata2 = $post->moredata;

    If you know the post's GUID only then use elgg_get_metadata_from_id function.

    If you want to display posts by metadata then use elgg_get_entities_from_metadata function:

    echo elgg_get_entities_from_metadata(array(
    
       'type' => 'object',
    
       'subtype' => 'match',
    
       'metadata_name' => 'somedata',
    
       'metadata_value' => $value,
    
       'limit' => 0
    
    ));

    etc

    Some examples for creating metadata: 1, 2

    More metadata tests also.

    And more...

  • @RvR Brilliant! Thank you!

Beginning Developers

Beginning Developers

This space is for newcomers, who wish to build a new plugin or to customize an existing one to their liking