Add new methods to the listing model

I’m trying to get the URL of a custom image that I added using an “add_meta_box” in my child theme with “get_post_meta”. I created a new template in my child theme under /listing/view/block to retrieve the URL and display an image, but I couldn’t get the listing ID. I managed to implement a get_logo_url() method inside the includes/models/class-listing.php file of the HivePress plugin that works, but this is obviously a bad practice. I’d like to know how I can “inject” this method from my child theme. I’ve tried several implementations by creating a class and inheriting from \HivePress\Models\Listing, but it seems that the get_logo_url method is not being called or added correctly.

final public function get_logo_url() {
	if ( ! isset( $this->values['logo_url'] ) ) {
		// Get the logo URL from the post metadata
		$logo_url = get_post_meta( $this->id, 'restaurant_logo', true );

		// If there is no logo, set a default image
		if ( empty( $logo_url ) ) {
			$logo_url = '';
		}

		// Set the value of the field
		$this->values['logo_url'] = $logo_url;
	}

	return $this->values['logo_url'];
}

Sorry for the late reply.

You can do this by adding new fields to the listing model, then adding custom post meta, taking care of validation, adding fields in HTML, etc. is not needed at all Models | Developer Docs

For example, if you add a new attribute via the hivepress/v1/models/listing hook, then $listing->get_attributenamehere() method will also become available. It may be easier to add a custom Attachment attribute in Listings/Attributes in the WordPress dashboard, then in the code you can use this method depending on which attribute field name you set:

$listing->get_attributenamehere()

If it’s attachment, you can get it’s URL this way:

$listing->get_attributenamehere__url()

Hope this helps

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.