首页 > 解决方案 > 如果帖子数据不符合参数,如何排除某些帖子显示在 wp_query 中?

问题描述

我对 PHP 相当陌生,所以这可能是一个简单的修复。我正在编辑一个插件并尝试将其修改为基于一组输入的位置,我只想输出其元数据符合输入参数的某些帖子,而不显示数据不适合的帖子。如何排除数据不适合输出的帖子?

到目前为止,我已经完成了所有工作,但是如果输入的数据不适合发布的元数据,则无法显示。我猜我需要使用一个$_post == null函数并尝试了许多变体,但没有任何效果。

这是我坚持的代码行:

<?php if ( $creditscore >= esc_attr($min_credit_score) ) { echo "good";} else { $_Post == null; ;
} ?>

这是完整的代码:

<?php htmlspecialchars($_GET["crd"]);
?>


<?php 

    $args = array(   
    'post_type' => 'lenders',   
    'posts_per_page' => $number1,
    'lender_cat' => 'personal-loans',

);  
$wp_query = new WP_Query($args);
while($wp_query->have_posts()) : $wp_query->the_post();     
$advertised_title = get_post_meta(get_the_ID(),'_cmb_advertised_title', true);
$advertised_number = get_post_meta(get_the_ID(),'_cmb_advertised_number', true);
$comparison_title = get_post_meta(get_the_ID(),'_cmb_comparison_title', true);
$comparison_number = get_post_meta(get_the_ID(),'_cmb_comparison_number', true);
$min_credit_score = get_post_meta(get_the_ID(),'_cmb_min_credit_score', true);
$btn_text = get_post_meta(get_the_ID(),'_cmb_btn_text', true);
$btn_link = get_post_meta(get_the_ID(),'_cmb_btn_link', true);
$except = get_post_meta(get_the_ID(),'_cmb_except', true);
$creditscore = htmlspecialchars($_GET["crd"], true);

?>

     <?php if ( $creditscore >= esc_attr($min_credit_score) ) { echo "goodtest";} else { wp_query == null; ;
} ?>

标签: phpwordpressplugins

解决方案


您可以将$creditscore值添加到您的WP_Query. 检查自定义字段(post meta)参数的文档

IE

$creditscore = htmlspecialchars($_GET["crd"], true);

$args = [
    'post_type' => 'lenders',   
    'posts_per_page' => $number1,
    'category_name' => 'personal-loans',
    'meta_query' => [
        [
            'key'     => '_cmb_min_credit_score',
            'value'   => $creditscore,
            'compare' => '<=',
        ],
    ],
]; 

$wp_query = new WP_Query($args);

注释:既然您提到您是 PHP 新手,我将添加一些注释。

  1. 根据您使用的 PHP 版本,您可以将$var = []其用于数组。如果该语法引发错误,请继续使用$var = array()
  2. 我在查询中添加了与信用评分的比较,因此您不会检索不需要的结果。
  3. 我改变了lender_catfor category_name,因为那是使用WP_Query
  4. 有一些优雅的方法来调试你的代码,但是一个简单的检查是检查你的结果来检查你是否得到var_dump它们print_r

IE

<?php

while($wp_query->have_posts()) : $wp_query->the_post();
    print_r($post);
endwhile;

试一试,让我们知道!


推荐阅读