API调用不会回显项目

时间:2019-02-22 20:52:27

标签: php wordpress api

几年前,我已经从envato市场购买了脚本。
它进行API调用以显示特定项目的信息。
他们更改了API,因此我正在尝试使其与新API一起使用。
我终于用令牌承载从API调用中获得了200个代码。

但是以某种方式从theme.php调用它时不会回显它。
我认为问题出在json解码部分,但我不确定。
为了使它正常工作,我连续两天挠头。

第一个代码来自Theme.php,我将其包含在shortcode.php(第二个代码)

<div class="eip-shortcode-wrapper">

<?php /* Title */ if( in_array( 'title', $this->preferences['preferences_components'] ) ): ?>

    <span class="eip-title" style="color: <?php echo $this->preferences['preferences_text_color'] ?>"><?php echo $item->name; ?></span><!-- /title -->

<?php endif; ?>

我对代码的这一部分做了一些更改以进行API调用:

        // Get item info
    $item = $this->get_item( $id );

    if( $item === false ) 
        return $this->msg( '<p class="envatomsg">Oops something went wrong... The info for this item couldnt be retrieved.<br>It could have been removed by the Envato DEV or just refresh the page to try again.</p>' );

    ob_start();

    include 'theme.php';


    return ob_get_clean();
}

protected function get_item( $id ) 
{
    $cache_expiration = 3600; // the cache expires in 3 hour

    $transient_id = "eip_envato_item_" . $id;

    $cached_data = get_transient( $transient_id );

    if( !$cached_data || ( $cached_data->id != $id ) ) {

        // Fetch data
        $response = wp_remote_get('https://api.envato.com/v3/market/catalog/item?id='. $id .'.json', array('headers' => array(
        'Authorization' => "Bearer AH6qreWAIBjXXXXXMYTOKEN"
        )
            )
                );

        // Check for errors 
        if( is_wp_error( $response ) or ( wp_remote_retrieve_response_code( $response ) != 200 ) ){
           return false;
        }

        // Parse json to object
        $result = json_decode( wp_remote_retrieve_body( $response ) );

        // Check for incorrect data
        if( !is_object( $result ) or !isset( $result->item ) or empty( $result->item )){
            return false;
        }

        // Prepare data for caching
        $data = new stdClass();
        $data->id = $id;
        $data->item = $result->item;

        // Set the transient
        set_transient( $transient_id, $data, $cache_expiration );

        // Return item
        return $data->item;
    }

    return $cached_data->item;
    }

    return $cached_data->item;
}

1 个答案:

答案 0 :(得分:0)

老同学帮助解决了问题。
<?php echo $item->name; ?>应该是<?php echo $item['name']; ?>

因为它显然不是物体。