custom fields for wordpress with new WP_Query

i want to add custom fields value in this code

<?php $catquery = new WP_Query( 'cat=20;&posts_per_page=5' ); ?>

i need to replace the number 20 with custom fields value

this code for display custom fields

<?php $references = get_post_meta($post->ID, "references",true); ?>
<?php echo $references ?>

is there any way to add

<?php echo $references ?>

to the code so cat=<?php echo $references ?> or some thing like that?

1 answer

  • answered 2018-01-13 21:04 cale_b

    To do what you want, you can do something like this:

    "Simplest Form", but liable to break if things aren't set / correct in your custom field:

    // load the category id
    $references = (int)get_post_meta( $post->ID, 'references', TRUE);
    // use the category id in the query
    $catquery = new WP_Query( 'cat=' . $references . ';&posts_per_page=5' );

    Somewhat better:

    // use an array for the parameters.  Set it up here
    $parameters = array(
        'posts_per_page' => 5,
    // load the category id
    $references = (int)get_post_meta( $post->ID, 'references', TRUE);
    // only if there is a reference ID, add it to the parameters
    if ( $references ) {
        $parameters['cat'] = $references;
    // pass the parameters into the WP_Query
    $catquery = new WP_Query( $parameters );