从Wordpress数组中的对象获取值

问题描述 投票:0回答:2

我正在尝试向 Wordpress 网站添加投票功能,可用的插件不能满足我的要求。

我有这个数组,其中包含另一个带有 wp_post 对象的数组(这些是投票的用户),我需要做的是将 current_user_ID 与数组对象中的所有 post_author ids 进行比较。我需要这样做,以便我可以向已经投票的用户显示不同的内容。只要知道如何从数组中的对象获取 post_author 值并将其与 current_user_id 进行比较就会有很大帮助。希望大家能帮助我,先谢谢了。

这就是我获取数组的方式:

<?php $my_post_meta = get_post_meta($post->ID, 'supporters', false);
            echo print_r($my_post_meta); ?>

这是显示的数组:

 Array ([0] => Array
        (
        [0] => WP_Post Object
            (
                [ID] => 750
                [post_author] => 46
            )

        [1] => WP_Post Object
            (
                [ID] => 749
                [post_author] => 47

            )

        [2] => WP_Post Object
            (
                [ID] => 748
                [post_author] => 1

            )
          ))1            
php arrays wordpress object
2个回答
0
投票

为什么不使用

wp_list_pluck()
将 ID 提取到数组中作为键,然后简单地检查当前用户 ID
isset()
是否在结果中,

$my_post_meta = get_post_meta($post->ID, 'supporters', false);
$voters = wp_list_pluck($my_post_meta, 'ID', 'post_author');
if( !isset( $voters[$current_user_ID] ) ){
  // this user hasn't voted as yet.
}

-1
投票

试试这个:

 <?php 

    $my_post_meta = get_post_meta($post->ID, 'supporters', false);
    $current_user_ID = get_current_user_id();
    foreach( $my_post_meta[0] as $post_object ) {
        if( $post_object->ID == $current_user_ID ) {
            // The current user has voted
        }
    }

   ?>
© www.soinside.com 2019 - 2024. All rights reserved.