artlung.

Adding tags to blog posts retroactively.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.