我创建了一个插件来从 API 获取一些数据。我创建了一个自定义帖子类型,并将从 API 检索到的数据包含到帖子中。我的插件代码如下
<?php
/**
* Plugin Name: Experts
* Plugin URI: https://****.**
* Description: Wordpress plugin for experts.
* Version: 1.0
* Author: My name
* Author URI: https://****.**
*/
if (!defined('ABSPATH'))
{
die;
}
class ExpertsPlugin
{
function __construct()
{
add_action('init',array($this, 'custom_post_type'));
}
function expert_activate()
{
$this->custom_post_type();
flush_rewrite_rules();
$this-> get_experts_from_api();
}
function expert_deactivate()
{
flush_rewrite_rules();
}
function expert_uninstall()
{
}
function custom_post_type()
{
register_post_type('expert',['public' => true, 'label' => 'Experts', 'capability_type' => 'post']);
}
function get_experts_from_api()
{
$experts = [];
$results = wp_remote_retrieve_body(wp_remote_get('https://api.****.**/v1/users/profiles?get=10'));
$results = json_decode($results);
$experts[] = $results;
foreach($experts[0] as $expert)
{
foreach($expert as $profile)
{
$expert_slug = sanitize_title($profile->userId);
$inserted_expert = wp_insert_post([
'post_name' => $expert_slug,
'post_title' => $expert_slug,
'post_type' => 'expert',
'post_status' => 'publish'
]);
if(is_wp_error($inserted_expert))
{
continue;
}
}
}
}
}
if(class_exists('ExpertsPlugin '))
{
$expertsPlugin = new ExpertsPlugin ();
}
//activation
register_activation_hook(__FILE__,array($expertsPlugin , 'expert_activate'));
//deactivation
register_deactivation_hook(__FILE__,array($expertsPlugin , 'expert_deactivate'));
//uninstall
register_uninstall_hook(__FILE__,array($expertsPlugin , 'expert_uninstall'));
这个插件可以正常工作。我的问题是因为我只get_experts_from_api()
在激活插件时调用,如果更新 API 中的数据,我将无法获取新值。我该如何解决这个问题。
我尝试过的一件事是像这样在构造函数中调用函数
function __construct()
{
add_action('init',array($this, 'custom_post_type'));
add_action('init',array($this, 'get_experts_from_api'));
}
但是使用这种方法,每次我刷新管理页面时都会调用该函数,并且还会复制数据。
如何防止数据重复,最好的方法是什么?