Entity attribute objects are the part of the Entity API that represent each of the different fields of an entity object. For example, attributes of the post entity would be its content, title, publish date, etc.

In most cases, your attribute will be stored in the database and made available as a property of the entity object, like the content of a post is through the post_content field of the WP_Post object. So let’s start with the class for the post content entity attribute as an example:

As you can see, our class extends the WordPoints_Entity_Attr_Field class. In other circumstances, like if the attribute wasn’t made available as a field on the entity object, we might need to subclass WordPoints_Entity_Attr directly instead. However, in this case we can let WordPoints_Entity_Attr_Field do all of the heavy lifting for us, so we just need to define a few properties and a simple method.

  • $storage_type — This tells us how this entity attribute is stored. In this case, it stored in the database table with the other post data, so the value of this property is 'db'.
  • $data_type — This is the type of value that is stored in the entity attribute. The post’s content is a string of text, so we use the 'text' data type. In other cases, we’d need to use different data types, like 'integer' for an integer value. You might even need to register a custom data type with the Data Types API.
  • $field — The field on the entity object and in database table where the value of this attribute is stored. The post’s content is stored in the post_content column of the database table, and made available through that property on the WP_Post object.
  • get_title() — This method needs to return the title of this entity attribute. This is the content attribute of a post, so we return 'Content'. Note that you shouldn’t include the name of the entity here, that is, use 'Content', not 'Post Content'.

Once you’ve created your entity attribute class, you now need to register it with the Entity API:

As you can see, we hook into the initialization of the entities registry, just as we do when registering a new entity. So you can register all of your entities and entity children in a single function. We just get the entity children class registry, which is a sub-app of the entities app, and register our attribute with the entity slug and a child slug that is unique for that entity.