简体   繁体   中英

Query custom post type, using custom field/meta key in the query

I have multiple Wordpress custom post types set up using Toolset Types, with the following names:

no-9

no-8

no-7

etc.

I would like make a Wordpress query to show the posts from one of these custom post types on another page. The page I would like to show the posts on, also contains a custom field with the name 'issue-no' that matches the name of the custom post type I would like to show.

What I have for my query so far is:

        <?php 
            query_posts(array( 
                'post_type' => 'no-9',
            ) );  
        ?>
        
        <?php while (have_posts()) : the_post(); ?>
                <h2><?php the_title(); ?</h2>
        <?php endwhile;?>

This works to show all posts from the post type 'no-9', however I would like the call to be dynamic so it can update based on the matching custom field 'issue-no'.

How can I call the custom field name/meta key in the query? Something like below in theory, however it doesn't put the custom field into the query.

        <?php 
            query_posts(array( 
                'post_type' => 'wpcf-issue-no',
            ) );  
        ?>
        
        <?php while (have_posts()) : the_post(); ?>
                <h2><?php the_title(); ?</h2>
        <?php endwhile;?>

It would be better to make a Variable like $cpt and asign your custom field to it. Not sure what plugin ur using for the custom field but i use ACF for it.

$cpt = get_field('Your_post_type_name');

After this place $cpt on the query_post like this:

query_posts(array( 
    'post_type' => $cpt,
) );

and it should work.

so it should look something like this:

    <?php 
    $cpt = get_field('your_selector');
        query_posts(array( 
            'post_type' => $cpt,
        ) );  
    ?>
    
    <?php while (have_posts()) : the_post(); ?>
            <h2><?php the_title(); ?</h2>
    <?php endwhile;?>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM