0

I have some meta fields in WordPress created by theme and i want to update it by using php.

The metafield stores url and i want to add some string after current url in custom meta.

i tried these method Assign/update the custom field value for all posts

and made changes

'post_category' => array(14,16,19);

to select a particular category but it edited all posts of all categories.

and used this method to change meta field but it removed url and changet field.

$dealcode = "&deal_code=coupon";
    $urlvalue = get_post_meta( $post->ID, 'metakey', false);
    $urlvalue = $urlvalue . $dealcode;
    update_post_meta( $post->ID, 'metakey', $urlvalue );

please can anyone fix this. Thanks.

  • Is that meta assigned for posts or for categories? Could you show the rest of your code? It's pretty hard to guess, what exactly are you doing with that 'post_category' => array(14,16,19); – Krzysiek Dróżdż Jun 5 '18 at 6:47
0

OK, so a little bit of guessing is involved in that answer, since you've posted only parts of your code, but... I assume that your code looks like that:

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page'   => -1,
    'post_category' => array(14,16,19)
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
    $dealcode = "&deal_code=coupon";
    $urlvalue = get_post_meta( $post->ID, 'metakey', false);
    $urlvalue = $urlvalue . $dealcode;
    update_post_meta( $post->ID, 'metakey', $urlvalue );
}

If so, then the problem lies in this line:

'post_category' => array(14,16,19);

There is no post_category argument for WP_Query...

The correct argument is category__in, so your code should look like this:

$args = array(
    'post_type' => 'post',
    'post_status' => 'publish',
    'posts_per_page'   => -1,
    'category__in' => array(14,16,19)
);
$posts = get_posts($args);
foreach ( $posts as $post ) {
    $dealcode = "&deal_code=coupon";
    $urlvalue = get_post_meta( $post->ID, 'metakey', false);
    $urlvalue = $urlvalue . $dealcode;
    update_post_meta( $post->ID, 'metakey', $urlvalue );
}

PS. Since you only use IDs, there is no point in getting whole posts. It would be much more efficient if you used fields => 'ids' in your query.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.