0

I'm having some trouble to add_post_meta using the code below with all the post tags inside a custom field.

The code works to echo all the tags, but not for saving them because it only saves the first tag of the post.

$all_post_tags = get_the_tags();
   
    $count=0; $comma_sep = ', ';

if ($all_post_tags) {
foreach($all_post_tags as $tag) {
$get_all_tags = $tag->name . $comma_sep;

add_post_meta($post->ID, 'all_tags', $get_all_tags, true);  

    }
}  

What's wrong with this code?

1 Answer 1

1

To start, why do you want to have your tag data in tags and also in a custom field? Seems to me like there is no reason for this, but maybe I'm missing something.

To answer your question about the code you have.. inside your foreach you overwrite the value each time in the loop. Instead of overwriting, you should add new tags to your predefined variable. Try this:

$all_post_tags = get_the_tags();
$count = 0;
$comma_sep = ', ';

if ( $all_post_tags && !empty($all_post_tags) ) {

    $get_all_tags = '';

    foreach ( $all_post_tags as $tag ) {
        $get_all_tags .= $tag->name . $comma_sep;
    }

    add_post_meta($post->ID, 'all_tags', $get_all_tags, true);

} 
2
  • It works, thanks! The reason why I need this on a custom field is because I need my tags to be searchable and I find it a lot more faster if I put it all on a custom field and use a plugin to search that custom field. Will this be advisable?
    – bpy
    Commented Apr 7, 2022 at 10:04
  • I'm glad the code is working for you! I can't advise about this as I don't know the possibilities of the search plugin you're using. You can make that decision for yourself. All I can say about this is.. in general I'm not a big fan of having duplicate data in my database.
    – DeltaG
    Commented Apr 7, 2022 at 10:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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