dsf5989 2016-11-29 15:37
浏览 46
已采纳

WordPress返回数组,其帖子ID基于meta_value

I'm trying to figure out something that should be fairly easy I think. I have custom fields named 'include-in-nav'. I'm using wp_nav_menu() to create a menu:

wp_nav_menu( array(     'theme_location' => 'primary', 
                        'menu_id' => 'primary-menu',
                        'include' => $post_ids

                ) 
        ); 

I've tried to get an array with post id's based on wether 'include-in-nav' is true or not. I've tried get_posts() and WP_query() but whatever i'm trying, nothing seems to return an array with post ID's. Any suggestions?

-edit my attempt to get $post_ids:

$post_ids = get_posts(array(
        'post'
        'meta_value'    => 'include-in-main-nav'
));

and

$nav_posts = array(
        'meta_value'    => 'include-in-main-nav'
));

$wp_query = new WP_Query($nav_posts);

$post_ids = array();

while ( $wp_query->have_posts() ) : $wp_query->the_post();
   $post_ids[] = get_the_ID() ;
endwhile;
  • 写回答

1条回答 默认 最新

  • dongzhanlu0658 2016-11-29 15:46
    关注

    well other than a flat our sql query, nope.

    you can use the wp_query with a meta query nested in. this will return posts though. you will need to loop through the posts as you would normally

    example of a query like the one you need:

    $args = array(
    'post_type'  => 'page',
    'meta_key'   => 'include-in-main-nav',
    'meta_query' => array(
        array(
            'key'     => 'include-in-main-nav',
            'value'   => 1,
            'compare' => '=',
        ),
    ),
    );
     $query = new WP_Query( $args );
    
    
    if ( $query->have_posts() ) : ?>
        <?php while ( $query->have_posts() ) : $query->the_post(); ?>    
            <!-- MOO! time to display your menu items! -->
        <?php endwhile; ?>
    <?php endif; ?>
    

    note: from there you can also fill an array with your ids.. if you really really need an array with only your ids in it.

    Have fun! hope this helps you out m8!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?