0

I have a posts query that queries posts by ID but want to select those posts by enetering a custom field. Here is the query and where I want to put the custom field:

$query_args = array('post_type'=>'post', 'post_status'=>'publish', 'include' => '483,454, CUSTOM FIELD HERE', 'orderby' => 'date', 'order' => 'ASC');

More info: Custom field is listids and passed in include. But doesn't work.

<?php
&listids = get_post_meta($post->ID, 'list_array', true);
$query_args = array('post_type'=>'post', 'post_status'=>'publish', 'include' => 'echo $listids;', 'orderby' => 'date', 'order' => 'ASC');
$query_posts = get_posts($query_args);
$last_query = end($query_posts);
foreach ($query_posts as $post) : setup_postdata($post); ?> 
4
  • 1
    Did you try and search in Google, WordPress handles custom fields in for a query already, codex.wordpress.org/Class_Reference/…
    – Wyck
    Commented Oct 12, 2012 at 19:18
  • That's why meta_query is for. Please search on the site.
    – kaiser
    Commented Oct 12, 2012 at 19:18
  • No, there is n instructions anywhere for passing the custom field value into an array.
    – Mark R
    Commented Oct 12, 2012 at 19:23
  • Right in the link it says meta_query (array) and value (string|array)
    – Wyck
    Commented Oct 13, 2012 at 1:19

1 Answer 1

1

I will assume that you(or users) will enter post ids into a posts custom field, comma separated, eg: 11,13,34,54 OR 11, 13, 34, 54.

Then all you need to do is get the custom field value for the loaded post, explode the custom field value by comma(,): and, then you'll have a nice array to pass into the include parameter. Here is an example showing the important pieces:

<?php
    $postIds = get_post_meta($post->ID, 'postIds', true); // get custom field value
    $arrayIds = explode(',', $postIds); // explode value into an array of ids
    if(count($arrayIds) <= 1) // if array contains one element or less, there's spaces after comma's, or you only entered one id
    {
        if( strpos($arrayIds[0], ',') !== false )// if the first array value has commas, there were spaces after ids entered
        {
            $arrayIds = array(); // reset array
            $arrayIds = explode(', ', $postIds); // explode ids with space after comma's
        }

    }

    $args = array(
        'include' => $arrayIds // pass array of ids into `include` parameter
    );
    ...
?>
1
  • I thank you very much as this has worked perfectly. You're awesome.
    – Mark R
    Commented Oct 12, 2012 at 21:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.