gabearnold
gabearnold

Reputation: 592

What is the proper way to query a Wordpress custom field

I have this working query that successfully gets the custom field data in my page template file:

<?php $featuredpost_cat = get_field('featured_category_id'); ?>

If I echo that out into the page I get "23" the value of the custom field, so I know that is working, what I want to do is grab that value and use it as a query parameter.

Farther down my page I have this:

<?php query_posts( $featuredpost_cat . '&posts_per_page=1'); if (have_posts()) : while (have_posts()) : the_post(); ?>

All that this does is ignore my variable and return the latest post on the site.

I hope this is clear enough.

== Edit ===

In case I am not being clear, I want to get a custom field which is a category ID from the page, then use it in a query on the page template.

So I set the field as category ID: 23 and then call it in my query_posts function so that I only return posts from that category.

Maybe the full page of code will help: template code

Upvotes: 1

Views: 113

Answers (2)

ZZ-bb
ZZ-bb

Reputation: 2167

Sorry, I don't understand your second code example. Are you trying to use ternary operator to accomplish this?

query_posts('cat='.$featuredpost_cat . '&posts_per_page=1');

if (have_posts()){
  while (have_posts()){
    the_post();
  }
}

What does query_posts() and the_post()do? If query_post() fetches the posts, have_post() checks the existance of posts and the_post() echoes them on the page, the code above should work. If this is not the case, please tell what the functions do.


Edit. Removed the question mark.

Upvotes: 0

Selvaraj M A
Selvaraj M A

Reputation: 3136

How about

<?php query_posts( 'cat='.$featuredpost_cat . '&posts_per_page=1'); if (have_posts()) : while (have_posts()) : the_post(); ?>

I assume that $featuredpost_cat is a category id

Upvotes: 1

Related Questions