greencode
Member
Posted 1 year ago #
I'm using the following query:
<?php query_posts( 'orderby=title&order=ASC&meta_key=featured' ); ?>
<?php while (have_posts()) : the_post(); ?>
to show only posts where the custom field of "featured" is true.
Except it doesn't work. Is there any way I can do this?
Thanks in advance for any help
meta_key is deprecated as of Version 3.1 in favor of 'meta_query'.
try it with this:
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array('key' => 'featured')
);
?>
<?php query_posts( $args ); ?>
greencode
Member
Posted 1 year ago #
Thanks for this. How would I go about only showing posts where the value of that custom field was "true"? I've tried the following:
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array('key' => 'featured', 'value'=>'true')
);
?>
<?php query_posts( '$args' ); ?>
But that doesn't show anything.
I've a feeling that you need to do it like this -
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array = (
'key' => 'featured',
'value'=>'true'
)
)
);
query_posts( '$args' );
?>
This allows you to query multiple meta values with only one query.
greencode
Member
Posted 1 year ago #
Umm, I got an error: Parse error: syntax error, unexpected '=', expecting ')'
greencode
Member
Posted 1 year ago #
Figured out where the error was:
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array (
'key' => 'featured',
'value'=>'true'
)
)
);
query_posts( '$args' );
?>
But that just seems to be bringing in any post where the "featured" custom field has content. Whereas I would like it where only posts with the text value of "true" are added.
greencode
Member
Posted 1 year ago #
I've used this code and it seems to be working okay but you say that meta_key is depreciated:
<?php query_posts( 'orderby=title&order=ASC&meta_key=featured&meta_value=true' ); ?>
This then only shows posts where the custom field of "featured" has the content "true" entered in the field.
I would be grateful for any suggestions though.
Yes, apologies, I added an extra '=' by mistake. I've also just spotted quotes that should not be there for query_posts.
Try this, as the code above (once corrected) should have worked as the default for 'compare' is LIKE, but you never know...
<?php
$args = array(
'orderby' => 'title',
'order' => 'ASC',
'meta_query' => array(
array(
'key' => 'featured',
'value' => 'true'
'compare' => 'LIKE'
)
)
);
query_posts($args);
?>
greencode
Member
Posted 1 year ago #
Spot on. Thanks so much for all of your help - really appreciated. There was just a missing comma after 'true' but all's working well now.
You are welcome, glad I could be of help.