rwmb_meta not working in wp_get_recent_posts

Support General rwmb_meta not working in wp_get_recent_posts

Viewing 2 posts - 1 through 2 (of 2 total)
  • Author
    Posts
  • #3111
    jonwatson87jonwatson87
    Participant

    Hey guys!

    So, ran into a recent issue and just wanted to share it with you. I did find a solution, but it meant bypassing rwmb_meta and going back to get_post_meta.

    Essentially, I was building a shortcode for recent posts, to display 5 upcoming events and wanted to show the event date (not the post date), and ran into a problem loading custom meta.

    rwmb_meta just didn't work:

    function radix_events_shortcode() {
    
    	ob_start();
    
    		$currentdatetime = current_time( 'timestamp' );
    
    		$args = array(
    		    'numberposts' => '5',
    		    'post_type' => 'events',
    			'order'          => 'ASC',
    			'orderby'        => 'meta_value',
    			'meta_query'     => array(
    				array(
    					'key'     => 'radix_eventstart',
    					'value'   => $currentdatetime,
    					'compare' => '>',
    				)
    			)
    		);
    
    	    $recent_posts = wp_get_recent_posts( $args );
    
    	    foreach( $recent_posts as $recent ) {
    
    			echo '<li><a href="' . get_permalink($recent["ID"]) . '">' .   $recent["post_title"].'</a> </li>' . date( 'jS F Y', rwmb_meta($recent["ID"], "radix_eventstart" ,true) );
    	
    		}
    
    	return ob_get_clean();
    
    }
    
    add_shortcode( 'show_latest_events', 'radix_events_shortcode' );

    I had to change the date field to:

    date( 'jS F Y', get_post_meta($recent["ID"], "radix_eventstart" ,true) )

    That seemed to fix the problem, but I would've expected rwmb_meta to work in this situation. My impression was that get_post_meta and rwmb_meta were indistinguishable, but that you guys recommend using rwmb_meta in most circumstances?

    Might be worth looking into! 🙂

    #3115
    Anh TranAnh Tran
    Keymaster

    I think it's not a bug. The helper function rwmb_meta works with current post object, e.g. the global $post;. In your loop, you don't use setup_postdata( $post ); to make the current post in the loop the global, so it won't work.

    To resolve this, simply add the 3rd parameter to rwmb_meta like this:

    rwmb_meta( 'radix_eventstart', '', $recent['ID'] );

Viewing 2 posts - 1 through 2 (of 2 total)
  • The topic ‘rwmb_meta not working in wp_get_recent_posts’ is closed to new replies.