WordPress.org

Ready to get started?Download WordPress

Forums

Use value of a custom field inside query_posts (4 posts)

  1. adam533
    Member
    Posted 4 years ago #

    Hi. I am not sure if this can be done but am hopeful :)

    I need to use multiple query_post on a new site I am working on. They will all be very similar besides one specific value in each. Instead of having to create 50 separate page templates, I was wondering if the following would be possible. Use a custom field on each page titled age. Then pull the value of that custom field and add it into the query_post. That way I can use just one template and change each query_post based on the custom field.

    So that way on the page that uses the custom field age of 12, the query post will return only posts with the category 12. I will be using more than just that one category in the query_post but they will all be staying the same across all pages, the only change will be the age.

    Hope it makes sense. Would hate to create all those different template files just to change one value on each.

  2. vtxyzzy
    Member
    Posted 4 years ago #

    It certainly is possible. I use almost the identical technique on my BlueGrassMiataClub.com site. You get the custom field before the main loop like this:

    $this_cat=get_post_meta($post->ID,'age',TRUE);

    Then you can use $this_cat in the query_posts. Of course, the 'age' custom field could contain a comma separated list of category id's.

    I will warn you, though, that WP does not stay in category when you click on a post title in your template. Single.php does not stay in category by default. The situation can be very complicated if a post belongs to more than 1 category, or if part of your site is a blog.

  3. robertjakobson
    Member
    Posted 3 years ago #

    vtxyzzy, can You give the context of the code?

  4. vtxyzzy
    Member
    Posted 3 years ago #

    Since I don't know what arguments you are using for your query_posts, this is only a general suggestion:

    $args = array(
       'paged' => $paged,
    );
    $this_cat = get_post_meta($post->ID,'age',TRUE);
    if ($this_cat) $args['category__in'] = array($this_cat);
    query_posts($args);

    I did not know what you wanted to do if there is no custom field for this query. You probably want to put in a default.

    One other thing, I usually don't check for replies to very old posts. I don't know if others do that or not.

Topic Closed

This topic has been closed to new replies.

About this Topic