我目前正试图从ACF布尔字段中检索一篇帖子(将其放在我创建的搜索过滤器的搜索结果中的所有其他帖子之前)(我是初学者),因此我编写了此脚本,但没有得到预期的结果:
在我的功能中。php:
// Set Meta Query Relation
$metaQueryRelation = array( \'relation\' => \'AND\' );
// Build Meta Query Params
$metaQueryParams = array(
\'relation\' => \'OR\',
\'display_not_first\' => array(
\'key\' => \'order_by_first_post\',
\'compare\' => \'NOT EXISTS\'
),
\'display_first\' => array(
\'key\' => \'order_by_first_post\',
\'compare\' => \'EXISTS\'
),
);
在结果文件中
// Get WP_Query custom args.
$argsRecipesGrid = buildArgs($params);
$display_first = $metaQueryParams[\'display_first\'][\'compare\'];
$result[$key] = arrayCopy( $val );
$queryRecipesGrid = new WP_Query( $argsRecipesGrid );
/** partie de code Richardson **/
$queryRecipesGrid = array();
// The sorting loop
foreach ($queryRecipesGrid as $post ){
if ($display_first[\'compare\'] == \'EXISTS\'){
array_unshift($display_first, $post);
}
if($post->have_posts()):
?>
<div class="recipes-row<?php echo $params[\'mines\'] ? \' row-count-3\' : \'\'; ?>">
<?php
while( $queryRecipesGrid->have_posts() ): $queryRecipesGrid->the_post();
?>
<div class="recipe-col">
<a class="list--item-link" <?php if(get_post_status() == \'publish\'){?>href="<?php echo get_permalink(); ?>"<?php }; ?>>
<?php get_template_part(\'tpl/recipes/card\'); ?>
</a>
</div>
<?php
endwhile;
echo \'</div>\';
else :
echo \'<div class="grid-row">\';
echo \'<div class="grid-col-12">\';
echo \'<p>\' . __(\'Aucun résultat\', \'galbani\') . \'</p>\';
echo \'</div>\';
echo \'</div>\';
endif;
?>
<?php
echo get_pagination($queryRecipesGrid, $params);
?>
最合适的回答,由SO网友:Antti Koskinen 整理而成
看起来您正在通过将posts var设置为空数组来清除查询的post。
$queryRecipesGrid = new WP_Query( $argsRecipesGrid ); // first you get the posts here
/** partie de code Richardson **/
$queryRecipesGrid = array(); // then you wipe them out by setting the same var to empty array.
关于排序,请参考我之前提供的示例,
How to always display a specific post from the search result first$my_acf_value = 1; // it might make sense to have this as post ID (as integer)
// Do your query
$queryRecipesGrid = new WP_Query( $argsRecipesGrid );
// Sort posts
$sorted_posts = array();
if ($queryRecipesGrid->posts) {
foreach ( $queryRecipesGrid->posts as $post ) {
if ( $post->ID == $my_acf_value ) { // change this to match your needs
array_unshift($sorted_posts, $post);
} else {
$sorted_posts[] = $post;
}
}
}
// Render the posts
if ($sorted_posts) {
foreach($sorted_posts as $sorted_post) {
// html stuff
}
}
NB: 为了简单起见,我在本例中使用post-ID进行排序。请修改代码以匹配您的实际用例和数据。