从定制表中获取数据,并根据meta_key更新相关的post_meta

时间:2021-07-03 作者:Giacomo Gaglione

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

为了给您提供更多的上下文,下面是我的查询:

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);
}
}
提前谢谢你

1 个回复
最合适的回答,由SO网友:shanebp 整理而成

您的功能中有几个问题。不要在sql中使用反勾号。不要在字段名称周围加引号。您使用get_results 具有LIMIT 1 当您只需要单行中单个列的值时。而您使用$meme_sku 而不是$post_sku ?只是猜测一下这个例子,它可能会起作用。。。

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

    $posts_array = get_posts( $args );
    $customTable = $wpdb->prefix.\'custom_table\';

    foreach($posts_array as $post) {
       
        $post_id = $post->ID;
        $post_sku = get_post_meta($post_id,\'_sku\',true);
            
        $result = $wpdb->get_var( "SELECT custom_column1 FROM $customTable  WHERE custom_key_id = $post_sku");
        
        if ( $result != NULL ) {
              update_post_meta($post_id, \'custom_meta_key\', $result);
        }

    }
}

相关推荐

Set MySQL variables in WPDB

我有一个SQL查询,它可以很好地作为原始SQL查询工作,但是当我将其放入WPDB时,它会抛出一个错误:global $wpdb; $sql = "SET @product_group = (SELECT product_group FROM insert_temporary LIMIT 1); SELECT * FROM insert_temporary WHERE product_group in (SELECT product_group