Python LogoAny internet marketer or SEO guru will tell you that content is a major key to success when running a website. The better the content is, the better your website will be. However, as many website owners will tell you, it is sometimes difficult to come up with good quality content for your website, especially for blogs. For those days that, for whatever reason, you just can’t seem to come up with some good content for your blog, I have found that those days are especially good for revisiting previous content. Not only do I think it’s a good idea to revisit past content, but I also think it’s a great opportunity to (re-)inform your visitors about past content just in case they might have missed something. To do that in a nice clean way, I like to use something called the “periodic roundup”. Roundups are nothing more than an article / post that contains links to previous posts. You can create roundups for weekly, monthly, yearly, or any other time frame you want. It’s extremely simple to do and doesn’t take more than just a couple of minutes to create. Since roundups are so simple to do, they are ideal for automating as well.

In this article I will show you how to automate roundup creation for WordPress powered websites using Python and cron. I will provide you with code that will check your blog for any articles posted within the previous month and will generate a new post with links to each of those articles. I have made sure to add checks in the code to prevent from linking to previous weekly or monthly roundups as readers would see this and know right away that you probably either automated the roundups or that you were just lazy or incompetent. The code can be easily modified to support other time frames as well such as weekly and yearly. If you are hosting your website on Windows, you can use the built-in Task Scheduler to schedule when your Python script will run instead of using cron as explained in this article. Basically, you just need a way to run the Python script on auto-pilot on the first day of every month (week or year depending on the time frame you choose). You can also run the app manually if you don’t have a way to automate when it runs on the server. Let’s get started.

┬áThe first thing you are going to need for this Python app is the “python-wordpress-xmlrpc” package. In order for this code to work, you will need to get an install version 2.2 which you can download from https://pypi.python.org/pypi/python-wordpress-xmlrpc. You can download it on your server using the following command:

wget https://pypi.python.org/packages/source/p/python-wordpress-xmlrpc/python-wordpress-xmlrpc-2.2.tar.gz

Next, you will need to extract it with the following:

tar xvf python-wordpress-xmlrpc-2.2.tar.gz

After you have extracted the package, move into the directory where you extracted it using this:

cd python-wordpress-xmlrpc-2.2

Install the package using this:

/usr/bin/python setup.py install

Note: You might have to change the path to your Python interpreter above.

That is the only dependency that this code requires. Now that you have it installed, you can create a new file somewhere on your system that will include the following code. For example purposes, I’ll use the path “/var/cronjobs/” where I will create a file called “monthly_roundup.py”. Remember the full path and file name for your Python script as we will be needing it later for cron. Next, copy the following code and paste it into your Python file.

from wordpress_xmlrpc import Client, WordPressPost
from wordpress_xmlrpc.methods.posts import GetPosts, NewPost
from wordpress_xmlrpc.compat import xmlrpc_client
from wordpress_xmlrpc.methods import posts

import datetime

wp_host = 'http://[YOUR_WEBSITE_URL]'
wp_user = ''
wp_pass = ''
wp_publish = True

class WordPress():
    def __init__(self):
        self.wp = Client(wp_host + '/xmlrpc.php', wp_user, wp_pass)
    
    def get_posts(self, count):
        posts = self.wp.call(GetPosts({'number': count}, None))
        return posts

    def post_article(self, title, content, tags = [], categories = []):
        newpost = WordPressPost()
        newpost.title = title
        newpost.content = content
        newpost.terms_names = {
            'post_tag': tags, #Example: ['Programming', 'Software Development'],
            'category': categories #Example: ['Programming', 'Software Development', 'Java']
        }
        if wp_publish == True:
            newpost.post_status = 'publish'
        newpostid = self.wp.call(NewPost(newpost))
        return newpostid

def subtract_date(date, year = 0, month = 0):
    year, month = divmod(year * 12 + month, 12)
    if date.month <= month:
        year = date.year - year - 1
        month = date.month - month + 12
    else:
        year = date.year - year
        month = date.month - month
    return date.replace(year = year, month = month)

if __name__ == '__main__':
    wp = WordPress()
    posts = wp.get_posts(50)
    date = datetime.date.today()

    last_month = subtract_date(date, month = 1)
    last_month = last_month.replace(day = 1)
    
    content = ''
    for post in posts:
        if post.post_status == 'publish' and post.date.date() >= last_month and post.title != 'Weekly Roundup' and post.title != 'Monthly Roundup':
            categories = []
            for category in post.terms:
                categories.append(category.name)
            categories = list(set(categories))
            categories = ','.join(categories)
            line = '<li>%s: <a href="%s" title="%s" alt="%s" target="_blank">%s</a></li>' % (post.date.strftime('%B %d, %Y'), post.link, categories, categories, post.title)
            content = line + '\n' + content
            
    if content != '':
        content = 'Here are this month\'s articles:\n\n<ul>' + content + '</ul>'
        wp.post_article('Monthly Roundup', content, None, None)

Before you can run the code, you will need to set the values for “wp_host”, “wp_user”, and “wp_publish” to match your website. If you want to test this without actually publishing anything for visitors to see yet, you can also set the “wp_publish” variable to “False”. When you run the app with this set to false, it will generate your roundup, but will create it as a draft. That will allow you to view the roundup and make any necessary changes before actually publishing it for others to see. Feel free to modify the message (“content” variable) at the very bottom of the code to match whatever you want to show up on your roundups. If desired, you can also change the title of your roundup article and include any tags or categories you want to include in the roundups by adding them to the very last line of code.

Before using this code, you’ll also need to make sure that XML-RPC has been enabled in WordPress as explained here. Even though WordPress now comes with XML-RPC enabled, it’s still a good idea to install the plugin from that article in case you ever need to disable XML-RPC for any reason. Without XML-RPC enabled, the code in this article will not work as that is the mechanism the code uses for communicating with your WordPress site even if you run the code on a different computer than the one your website is running on.

Once you have your roundups looking the way want, you are now ready to schedule them to run. Since we are creating a “monthly roundup” in this example, we will want to schedule our Python app to run on the first of every month. The code above will then take the current date and subtract one month from it and create links in the roundup for all articles that were published during that time. Don’t worry, the app will not post anything that has not been published yet. So, you won’t have to worry about it publishing links to articles that are still in the draft phase.

To schedule your roundups to run on the first of every month, run the following command. This will launch the cron editor.

crontab -e

Press the “i” key to enter insert mode and add the following line. Make sure you use the same path and filename you used earlier.

3 0 1 * * /usr/bin/python /var/cronjobs/monthly_roundup.py

This will tell cron to launch your Python app on the first day of every month at 12:03am (3 minutes after midnight). I chose to use 3 minutes after midnight for various reasons, but you can use whatever you want. Just do a Google search to get information about the cron syntax.

After you have added your cron job, press the escape key and type “:wq!” (without the quotes) and press enter. This will tell the editor to write your changes to the file and exit back to the command prompt. Once you’re back at the command prompt, it’s a good idea to restart the cron daemon so that it recognizes your changes. To do that, run the following command:

service crond restart

That’s it! You now have an automated Python app that will generate a new monthly roundup article for you on the first of every month.

Thank you for your interest in my site. If you find the information provided on this site useful, please consider making a donation to help continue development!

PayPal will open in a new tab.
$2.00
$5.00
Other

Related Posts

Tagged with:  

Leave a Reply