admin管理员组

文章数量:1310160

I have a post in my WordPress website, which has lot of custom fields. I have an Excel sheet with "post link" - "custom field data" combination. That custom field (video URL) is already set for each post, but now I need to change and update those links based on the Excel sheet. I don't have a "post_id - post meta data" combination, just link and appropriate meta data value.

Is there a way to update this data with some code?

I have a post in my WordPress website, which has lot of custom fields. I have an Excel sheet with "post link" - "custom field data" combination. That custom field (video URL) is already set for each post, but now I need to change and update those links based on the Excel sheet. I don't have a "post_id - post meta data" combination, just link and appropriate meta data value.

Is there a way to update this data with some code?

Share Improve this question edited Jun 27, 2017 at 2:35 Dave Romsey 17.9k11 gold badges56 silver badges70 bronze badges asked Jun 4, 2015 at 17:57 Anna GabrielyanAnna Gabrielyan 13311 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 1

I have not tested this, but the idea is to find the post ID based on the post URL, and then update the meta field for that post.

I would save that excel as csv format. Import it to a new table in your database. That way you can easily have access to that information, instead of having to read a excel file (which could require you to include some extra php classes).

Once you have the excel data in the database you can pull that data and run it in a loop.

For example:

global $wpdb;
    //You can use $wpdb to query non-wordpress tables
    //Here I query I table I created video_urls
    //It has two columns. One with the post url, and one with the video url

    $results = $wpdb->get_results('SELECT * FROM video_urls', OBJECT);

    //Loop through each result

    foreach($results as $result){

        //use the wordpress function url_to_postid() to get the post id

        $post_id = url_to_postid($result->post_url);

        //update the post_meta with the wordpress function below
        //you will need to know the name of the custom field.

        update_post_meta($post_id, "NAME_OF_CUSTOM_FIELD", $result->video_url);

    }

This should work, but please do not just copy and paste and expect it to work. Also, make a backup of your database before running any scripts that attempts to mass update wordpress posts.

This code could be pasted in one of your page templates, and then you can just load that page to run the code once, and comment it out the code later so that it won't run again.

本文标签: mysqlUpdate post meta data (custom field) by post link