Site icon Hip-Hop Website Design and Development

how to add tags to post in the Loop?

I have the following code below, which loops through all posts in a db of books. I would like to tag book entries which do not have the tag $tag="book_".$booknum."_".$chapnum;

My output in the debug, shows that the query correctly identifies what I want.

BUT the line: $result= wp_add_post_tags((int) $id, $tag ); does not seem to be adding the tag to the post with the $id. I tried adding
//wp_update_post( $post );
// wp_reset_postdata();
but both failed also.

while ($q->have_posts()) {
            $post= $q->the_post();
             $link = get_permalink();
             $title=get_the_title();
             $id=get_the_ID();
             $content=get_the_content();
             $booknum=$this->GetKeyValFromText($content, "book_num");
             $chapnum=$this->GetKeyValFromText($content, "chap_num");
             $tag="book_".$booknum."_".$chapnum;
             $hasTag=has_tag($tag);
             $ln=$this->MakeLink($title, $link);
             if (!$hasTag) {
                 $this->debug("adding  post tag to $ln ;    $tag   hasTAG=$hasTag , id=$id");
                // wp_insert_term( 'post_tag', $tag );
                $result= wp_add_post_tags((int) $id, $tag );
                var_dump($result);
                 //wp_update_post( $post );
                // wp_reset_postdata();
                 return;
             }
         }