繁体   English   中英

如何显示自定义字段值数组中的Wordpress帖子

[英]How to display Wordpress posts from an array of custom field values

我们有一个网站,其中包含数百个自定义“奖励”帖子。 这些帖子每个都包含一个自定义字段,标题为“ Incentive ID”,它是一个数字。 然后,我们对“ Recommended Incentives”表进行PHP / MySQL查询,该表返回以逗号分隔的“ Incentive ID's”列表。 我们要显示基于奖励ID的逗号分隔列表的“奖励”帖子列表。 我已经创建了一个PHP短代码脚本,该脚本在这里查询逗号分隔的列表

<?php


global $wpdb;
$user_ID = get_current_user_id();
$sql = <<<SQL
SELECT FK_T_L_INCENTIVES_ID FROM lighting_incentives.WAYPOINT_USER_PICKED WHERE WP_RECOMMENDED = 1 AND FK_USER_ID = $user_ID
SQL;

if (!$sql) { // add this check.
    die('Invalid query: ' . mysql_error());
}

$resultset = array();
$rebates = $wpdb->get_results( $sql, ARRAY_A );
foreach($rebates as $data) {
     echo $data['FK_T_L_INCENTIVES_ID']. ",";
}

?>

我还创建了一个自定义页面模板,该模板使用wp_query填充Wordpress的“奖励”帖子。 当我具有“奖励ID”的静态值时,此页面模板非常有用。

$args = array(

    'meta_key' => 'Incentive ID',
    'meta_value' => array(20,21),
    'orderby' => 'meta_value_num',
   'order' => 'ASC',
    'post_type' => 'incentives'
);

// get results
$the_query = new WP_Query( $args );

// The Loop
?>
<?php if( $the_query->have_posts() ): ?>
    <ul style="list-style:decimal;">
    <?php while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
        <li>
            <a href="<?php the_permalink(); ?>"><?php the_title(); ?></a>
        </li>
    <?php endwhile; ?>
    </ul>
<?php endif; ?>

<?php wp_reset_query();  // Restore global post data stomped by the_post(). ?>

但是,尝试将以逗号分隔的“奖励ID”列表插入wp_query args“ meta_value ”字段时,我遇到很多麻烦。 我已经尝试了所有我能想到的东西,但没有任何尝试可行。 我已经试过了

$gg = print do_shortcode("[php snippet=35]");
$args = array(

    'meta_key' => 'Incentive ID',
    'meta_value' => array($gg),
    'orderby' => 'meta_value_num',
   'order' => 'ASC',
    'post_type' => 'incentives'
);

这个

$gg = print do_shortcode("[php snippet=35]");
$args = array(

    'meta_key' => 'Incentive ID',
    'meta_value' => $gg,
    'orderby' => 'meta_value_num',
   'order' => 'ASC',
    'post_type' => 'incentives'
);

这个

$args = array(

    'meta_key' => 'Incentive ID',
    'meta_value' => print do_shortcode("[php snippet=35]"),
    'orderby' => 'meta_value_num',
   'order' => 'ASC',
    'post_type' => 'incentives'
);

但是这些选择都没有起作用。 它们会导致致命错误或空白页。 我究竟做错了什么!?!?!?! 任何人都可以给我的帮助将不胜感激!!!

您需要提供Incentices ID数组而不是字符串。

具有多个值时,应使用meta_query获取带有自定义字段的帖子。

$meta_values = array(value1, value2, /* .. */); // not a string

$args = array(
    'post_type' => 'incentives',
    'meta_key' => 'Incentive ID',
    'meta_value' => array(),
    'orderby' => 'meta_value',
    'order' => 'ASC',
    'meta_query' => array(
        array(
            'key' => 'Incentive ID',
            'value' => $meta_values,
            'compare' => 'IN'
        )
    )
);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM