首页 > 解决方案 > 从自定义表中检索数据并更新 post_meta

问题描述


长话短说:我需要从 WordPress 创建的自定义表中检索数据并将元数据添加/更新到相关帖子(post_type=product)。我可以通过帖子元数据(_sku)匹配帖子(产品)和自定义表字段,这是我查询的关键。

为了给您更多的上下文,请按照我的查询:
SELECT * FROM wpfx_custom_table a 
left join wpfx_postmeta b 
on a.custom_key_id=b.meta_value
WHERE b.meta_key = '_sku'
ORDER BY a.custom_date DESC
LIMIT 1

我已经尝试过了,但它不起作用:

function update_custom_post_meta_data() {
    global $wpdb;
    global $post;
    
    $args = array(
    'posts_per_page' => -1,
    'post_type' => 'products',
    'suppress_filters' => true,
    'meta_key' => '_sku'
     );

    $posts_array = get_posts( $args );

    foreach($posts_array as $post_array) {
        $post_array->the_post();
        $post_id = $post_array->ID;
        $post_sku = get_post_meta($post_id,'_sku',true);
        
        $CustomTable = $wpdb->prefix.'custom_table';

        $results = $wpdb->get_results ( "SELECT * FROM CustomTable  WHERE `custom_key_id` = $meme_sku ORDER BY `custom_date` DESC LIMIT 1");

        foreach($results as $result){
            $custom_meta_value = $result->custom_column1;
            add_post_meta($post_id, 'custom_meta_key', $custom_meta_value);
        }

    update_post_meta($post_id, 'custom_meta_key', $custom_meta_value);
}
}

先感谢您

标签: phpmysqlwordpress

解决方案


推荐阅读