artlung.

Adding tags to blog posts retroactively. 2019 Mar 02

I’ve been reflecting my instagram posts back to this blog for a while now. One of the conventions there is mentioning people with the @mention and hashtagging posts with #hashtags.

It has bothered me for a while that I didn’t ingest those tags and mentions in some manner. I left this lay for a long time but I’ve had a tickle in my brain to address this. So– I added tags using the wp command line tool. By the way that command line tool is incredibly useful and powerful. You can do stuff like upgrade and install plugins and themes. I have found it useful for searching over the 5882 blog posts and organizing them.

Here’s a simple search:

# https://developer.wordpress.org/cli/commands/post/
wp post list  --post__in=$(wp db query 'SELECT ID FROM artlungblog_posts WHERE \
post_title LIKE "%#%" AND post_status="publish" AND post_type="post"' \
--skip-column-names |  paste -s -d ',' - ) --format=csv --fields=ID,post_title > out.csv

And my code to parse that outfile.

function find_tags($str) {
    $tags = [];
    $words = explode(" ", $str);
    foreach ($words as $word) {
        if (substr($word, 0, 1) === "#") {
            $value = strtolower(str_replace([".",":","#","!","\"", "@", "(", ")"],"",$word));
            if (strlen($value) > 2) {
                $tags[] = $value;
            }
        }
    }
    return implode(" ", $tags);
}

function find_atsigns($str) {
    $tags = [];
    $words = explode(" ", $str);
    foreach ($words as $word) {
        if (substr($word, 0, 1) === "@") {
            $value = strtolower(str_replace([".", ":", "#", "!", "\"", "@", "(", ")"],"",$word));
            if (strlen($value) > 2) {
                $tags[] = $value;
            }
        }
    }
    return implode(" ", $tags);
}


$lines = file("out.csv");

foreach ($lines as $line) {
    $parts = explode(",", $line);
    $id = array_shift($parts);
    $title = implode($parts, ",");
    $tags = find_atsigns($title) . " " . find_tags($title);
    
    if ($tags) {
        echo <<<WHAT
wp post term add {$id} post_tag $tags
WHAT;

        echo "<br>";
    }

}

On my TODO list is to do this in an automated manner. For now, it’s custom.

But it’s really nice to see the aggregate of lots of posts. It’s the basis for my robots and drawings tag pages. And now my sdcc – for San Diego Comic Con is a lot better too.

I like writing ad hoc code like this.

Joe Crawford blogged this at 7:31pm in 2019 in March. The 2nd was a Saturday. You are reading this 5 months later. Comment. There are no comments Tweet. Send email. It has hashtags→ .

Leave a Reply

Comments Open; Trackbacks Open.