• I’m currently using this to retrieve a list with posts that have a certain custom fields value:

    <?php
    	$querystr = "
    		SELECT $wpdb->posts.*
    		FROM $wpdb->posts, $wpdb->postmeta
    		WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
    		AND $wpdb->postmeta.meta_key = 'type'
    		AND $wpdb->postmeta.meta_value = VALUE
    		ORDER BY $wpdb->posts.post_date DESC
    	";
    	$pageposts = $wpdb->get_results($querystr, OBJECT);
    ?>

    How can I however list posts where the custom field is empty? I’ve already tried to put:

    AND $wpdb->postmeta.meta_value = ”
    AND $wpdb->postmeta.meta_value = null

    but those don’t work. Any help would be greatly appreciated!

Viewing 6 replies - 1 through 6 (of 6 total)
  • Hi there,
    If the meta_value is empty, then most likely there will not be a custom field item for that post.
    So, your:

    WHERE $wpdb->posts.ID = $wpdb->postmeta.post_id
    AND $wpdb->postmeta.meta_key = 'type'

    … is going to result in no posts.

    Let me know if this doesn’t make sense.
    Paul

    Moderator keesiemeijer

    (@keesiemeijer)

    Thread Starter ukutabs

    (@ukutabs)

    Hi,

    Thank you for the replies!

    Well the situation is this:

    – some posts have type = “tab”
    – other posts type = “mix” (= chords and tabs)

    When custom field “type” isn’t used for a specific, the type is chords (i.e. all posts with no custom field “type”).

    So now I was able (with the script from my first post) to use as value “TAB” and “MIX” to retrieve a list with all posts that are tabs, respectively mix types.

    And now I want to also retrieve a list with posts that are chords (so no type filled in).

    Hopefully I’ve explained it good enough, I’d appreciate any help!

    Moderator keesiemeijer

    (@keesiemeijer)

    Try it with this:

    $querystr = "
    	SELECT * FROM $wpdb->posts
    	WHERE $wpdb->posts.ID NOT IN  (
    		SELECT post_id FROM $wpdb->postmeta
    		WHERE ($wpdb->postmeta.post_id = $wpdb->posts.ID)
    		AND meta_key = 'type'
    		)
    	AND (post_status = 'publish' OR post_status = 'static')
    	AND post_type = 'post'
    	ORDER BY post_date DESC
    ";
    
    	$pageposts = $wpdb->get_results($querystr, OBJECT);
    Thread Starter ukutabs

    (@ukutabs)

    Thank you so much! That worked perfect.

    Bedankt! ??

    Moderator keesiemeijer

    (@keesiemeijer)

    No problem. I’m glad you got it resolved.

    From (probably) WordPress version 3.5 you could try something like this [untested]:

    $args = array(
    	'post_type' => 'post',
    	'meta_query' => array(
    		array(
    			'key' => 'type',
    			'compare' => 'NOT EXISTS'
    		)
    	)
     );
    $pageposts = get_posts( $args );

    But that’s for in the future.

Viewing 6 replies - 1 through 6 (of 6 total)
  • The topic ‘List of posts where custom field is empty?’ is closed to new replies.