Quantcast
Channel: Question and Answer » wpdb
Viewing all articles
Browse latest Browse all 44

Inserting Post Meta From SQL

$
0
0

I’m trying to get post meta to be updated/replaced with $wpdb and running into issues. I have working SQL, but cannot get it work when coding it up for my WP plugin.

Extra note:

The post meta being saved is for example is Twitter follower count that I need the number to be saved to the database so I can export the result in a table

Here is my working SQL. When I put this in PHPmyAdmin it updates all post meta:

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT wp_posts.ID, 'agency_details_seo_grade', 'test'
FROM wp_posts
WHERE wp_posts.post_status = 'publish' and wp_posts.post_type = 'agencies'";

Here is my failed attempt putting it in WP. Nothing happened as a result (no meta changed and no error message):

// Failed attempt to put into functions.php
function add_grading_post_meta() {
    global $wpdb;
    $wpdb->prepare("SELECT ID,'','test2'", $wpdb->query("INSERT INTO wp_postmeta ($post_id,meta_key,meta_value)"));
}

I’m trying to get this working so I can use it with wp_cron before the next step of using it with WP scheduling functions. Any help would be appreciated for this first step, cracking a lot of hours on this project learning PHP.

Edit:

Here’s 1 more version I tried with no success. I changed it due to @czerspalace comment, coding provided by old Stack Exchange post.

function add_grading_post_meta() {
    global $wpdb;

    $twitter_followers = 'agency_details_twitter_followers';
    $twitter_count = 'test3';

    $sql = "INSERT INTO $wpdb->wp_postmeta (post_id,meta_key,meta_value) VALUES   (%d,'%s',%s) ON DUPLICATE KEY UPDATE meta_value = %s";
    $sql = $wpdb->prepare($sql,$post_id,$twitter_followers,$twitter_count);
    $wpdb->query($sql);
}

Viewing all articles
Browse latest Browse all 44

Trending Articles