WordPress.org

Ready to get started?Download WordPress

Forums

wp_postmeta: querying multiple meta_values from a random post_id (3 posts)

  1. Han
    Member
    Posted 1 year ago #

    I am trying to pull a random post content along with its meta data from a custom post type called "BRAND" (try saying that again ^_^).

    I can pull one meta data, but I cannot pull multiple meta data for that post. My code is as follows:

    SELECT p.ID, p.post_content, m.meta_key, m.meta_value
    FROM wp_posts p
    	INNER JOIN wp_postmeta m
    		ON p.ID = m.post_id
    WHERE p.post_type = 'BRAND'
    	AND p.post_status = 'publish'
    	AND m.meta_key LIKE 'brand-%'
    ORDER BY RAND()
    LIMIT 1

    Note, that the meta_key can be something like "brand-a", "brand-b", "brand-c", etc.

    How do I pull all those meta_keys? Thanks!

  2. keesiemeijer
    moderator
    Posted 1 year ago #

    Try it with group_concat:

    <?php
    global $wpdb;
    $query = "SELECT p.ID, p.post_content, GROUP_CONCAT(meta_key) AS metakey, GROUP_CONCAT(meta_value) AS metavalue
    FROM $wpdb->posts p
    INNER JOIN $wpdb->postmeta m ON p.ID = m.post_id
    WHERE p.post_type = 'BRAND'
    	AND p.post_status = 'publish'
    	AND m.meta_key LIKE 'brand-%'
    	GROUP BY p.ID
    ORDER BY RAND()
    LIMIT 1";
    
    $results = $wpdb->get_results( $query );
    ?>
  3. Han
    Member
    Posted 1 year ago #

    You are a lifesaver! Very clever way to put multiple data into one column. Thanks!

Topic Closed

This topic has been closed to new replies.

About this Topic

Tags

No tags yet.