How to add listing and vendor blocks by ID with PHP

I have made my own custom query with PHP that returns an array of listing or vendor IDs, but now I want to show them using your existing blocks. I don’t want to have to recreate them. Is there a function I can use to add a block by ID? Can’t seem to find anything in your Github Gists or documentation. Thanks in advance.

Spoke too soon. Figured it out on my own. For others who are curious, I have set up relationships between vendors so that one is a retailer and another is a supplier. The retailer can connect with the supplier and include their listings on their vendor profile. This is where I’m at, making a shortcode to display the supplier’s listings that are stored by ID on the retailer’s vendor post meta.

// Get the vendor's suppliers
$suppliers = $SL_VENDORS->has_supplier_listings( $vendor_post_id );

// Since we have some
if ( !empty( $suppliers ) ) {

    // Extract all supplier IDs
    $listing_ids = [];
    foreach ( $suppliers as $supplier ) {
        foreach ( $supplier as $listing_id ) {
            $listing_ids[] = $listing_id;
        }
    }

    // The query
    $query = HivePress\Models\Listing::query();

    // Filter
    $query->filter(
        [
            'id__in' => $listing_ids,
        ]
    );

    // Random
    $query->order( 'random' );

    // Fetch them
    $listings = $query->get(); 

    // Start the container
    $results = '<div class="supplier-listings hp-listings hp-block hp-grid">
        <div class="hp-row">';

            // Iter the listings
            foreach ( $listings as $listing ) {

                // Listing container
                $results .= '<div class="hp-grid__item hp-col-sm-4 hp-col-xs-12">';

                    // Render the block
                    $results .= ( new HivePress\Blocks\Template(
                        [
                            'template' => 'listing_view_block',
                            'context'  => [
                                'listing' => $listing,
                            ],
                        ]
                    ) )->render();

                // End container
                $results .= '</div>';
            }

        // End the container
        $results .= '</div>
    </div>';
    return $results;
}

For vendors, I would Render the block using 'template' => 'vendor_view_block' and 'context' => [ 'vendor' => $vendor_object ]. Hope it helps someone. :+1:

1 Like

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