Posts Tagged ‘Blogging’

Writing WordPress posts offline in Word with the help of VBA macros

Monday, February 15th, 2010

If you want to write your WordPress posts offline (i.e. in a separate editor to the WordPress editor), then you may find you have to spend a fair bit of time reformatting the blog post to add any required WordPress formatting before you can publish.

There are lots of reasons for wanting to write your WordPress blog posts offline. You may not have access to the internet at the time you are writing. You may find the WordPress editor to be a pain, or maybe you have another editor that you’d much rather write with.

I like writing using Word 2007 so I created some VBA macros which allow me to add bits of formatting to the post (titles, links, photos) faster than I could do manually.

wordpress word 2007 macros

These macros help you format posts which are meant to be pasted into the WordPress non-WYSIWYG post editor. I don’t know what would happen if you pasted posts formatted with these macros into the WordPress WYSIWYG editor.

Description of WordPress macros

Here’s a description of the macros from the source code at the end of this post. I’m only describing the main macros, not the other supporting functions in the code that these macros need.

BoldForWordPress – Adds ‘Strong’ tags around the highlighted text and also makes the text bold in Microsoft Word to make the titles easier to see when you are editing your blog posts.

BoldForWordPress

Will be turned into:

<strong>BoldForWordPress</strong>

PhotoLinkSite1 / PhotoLinkSite2

Changes the image name into an image link with just a few bits for you to fill in to complete the HTML. It will try to auto generate an ALT tag from the image name by turning any hyphens ‘-‘ into spaces. Highlight an image name such as ‘myimage.jpg’ and click the image button.

wordpress-blog.jpg

Will be changed into:

<img src="http://www.????.co.uk/data/2010/xxxx/wordpress-blog.jpg"
 width="" height="" alt="wordpress blog" />

If you have multiple sites then you can use the template code in PhotoLinkSite1 / PhotoLinkSite2 to allow you to create links which already contain each of your sites URLs. If you only have one site then just delete PhotoLinkSite2.

Listify

Listify will convert a number of lines of text into a HTML list.

Item 1
Item 2
Item 3

Will become:

<ul>
    <li>Item 1</li>
    <li>Item 2</li>
    <li>Item 3</li>
    <li></li>
</ul>

The code will give you an extra list element at the end in case you want to add more items to your list. If you don’t want it just delete it.

Link

Highlight some text or a URL and this will create your <A HREF… link. If you highlight text beginning with ‘http’ then it will put the text into the link section, otherwise it will put it into the description section.

This is some text

Will become:

<a href="">This is some text</a>

And:

http://www.reviewmylife.co.uk/blog/

Will become:

<a href="http://www.reviewmylife.co.uk/blog/"></a>

SpacingTable

This will insert a piece of fixed HTML which can be used to add extra spacing to images or Amazon iframes. See my post Adding spacing round an iframe in WordPress for more information. If you select the iframe HTML the spacing table will be put around it. If you have nothing selected then the spacing table will just be inserted straight where the cursor is. This is what will be inserted:

<table border="0" cellspacing="10" align="right">
 <tr><td></td></tr></table>

AdSense

This macro is useful if you use the Adsense Injection plugin. Press it once and it will insert a tag to disable AdSense in the current post. Press it again and you will get the tag to start the AdSense from a certain point in your post. Here are the two tags it will insert.

<!--noadsense-->
<!--adsensestart-->

Splitter

This inserts a line of hashes and asterixes into the text. This isn’t useful for the WordPress blog post, but I use it to split up sections in the Word document when I’m writing multiple posts. This is what this macro outputs:

*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#*#

How to create and configure the toolbar buttons

Here are some brief instructions for how to setup these macros. You’ll need the source code below.

First click on the ‘View’ tab and then the ‘Macros’ button on the right hand side of the ribbon.

word 2007 macros button

If you haven’t added any macros before you’ll need to create a dummy one so you can access the Visual Basic macro editor. Type in ‘Dummy’ as the macro name and press ‘Create’. You’ll be taken straight to the editor.

create dummy word 97 macro

Paste all the macro VBA source code below into the editor. Save the macros by going to the File menu and pressing ‘Save Normal’.

Now you need to create some buttons and link them to the macros. Click on the little down arrow (pictured below) to get the Customize Quick Access Toolbar menu. Press ‘More Commands’.

customize quick access toolbar

In the ‘Choose commands from’ pull down list select ‘Macros’.

choose commands from menu

Now click on each of the macros and then press ‘Add’.

adding macros to the quick access toolbar

To give each macro a unique icon, click on each on in turn, press ‘Modify’, and then choose your icon.

add icons to macros

You should now have your macro buttons setup and it will look something like this.

wordpress word 2007 macros

Visual Basic (VBA) WordPress macro source code

Here is the VBA macro code – it’s not pretty but it works. It has been tested on Word 2007. You should be able to get it working on other versions of Word as well, but it might require minor modifications if it doesn’t work as expected.

You might want to customise the URLs in PhotoLinkSite1 / PhotoLinkSite2 to fit your own blog.

Sub BoldForWordpress()
    'Wordpress bold title
    Dim TitleStr
    TitleStr = Selection.Text
    Dim HasNewLine As Boolean
    If Right(TitleStr, 1) = Chr(13) Then
        HasNewLine = True
    End If
    TitleStr = TrimNewLine(TitleStr)
    With Selection
    .Delete
    .Font.Bold = wdToggle
    .TypeText ("<strong>")
    .TypeText (TitleStr)
    .TypeText ("</strong>")
    .Font.Bold = wdToggle
    End With
    If HasNewLine Then
        Selection.TypeText (Chr(13))
        Selection.MoveLeft
        Selection.Font.Bold = wdToggle
    End If
End Sub

Function TrimNewLine(Str) As String
    'Remove newline from string
    If Right(Str, 1) = Chr(13) Then
    TrimNewLine = Left(Str, Len(Str) - 1)
    Else
    TrimNewLine = Str
    End If
End Function

Function TrimPlus(TheString) As String
    'Trim space and newline
    TheString = Trim(TheString)
    TrimPlus = TrimNewLine(TheString)
End Function

Sub Replace(FromStr, ToStr)
'Replace text in the current selection
    With Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = FromStr
    .Replacement.Text = ToStr
    .Forward = False
    .Wrap = wdFindStop
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
    .Execute Replace:=wdReplaceAll
    End With
End Sub

Sub PhotoLinkSite1()
Call PhotoLink("http://www.????.co.uk/2010/xxxx/")
End Sub

Sub PhotoLinkSite2()
Call PhotoLink("http://www.????.co.uk/2010/xxxx/")
End Sub

Sub PhotoLink(LinkBase As String)
    'Turn the image name into a link
    Dim PicString, AltString
    PicString = Selection.Text
    ' Remember newline
    Dim HasNewLine As Boolean
    If Right(PicString, 1) = Chr(13) Then
        HasNewLine = True
    End If
    PicString = TrimPlus(PicString)
    'Create alt text
    Call Replace("-", " ")
    Call Replace(".jpg", vbNullString)
    Call Replace(".png", vbNullString)
    Call Replace(".gif", vbNullString)
    AltString = Selection.Text
    AltString = TrimPlus(AltString)
    'Write HTML
    With Selection
    .Delete
    .TypeText ("<img src=""")
    .TypeText (LinkBase + PicString)
    .TypeText (""" width="""" height="""" ")
    .TypeText ("alt=""" + AltString + """ />")
    End With
    ' Re-add new line
    If HasNewLine Then
        Selection.TypeText (Chr(13))
    End If
End Sub

Sub Listify()
    'Add list tags to a plain text list
    Dim ListString
    Call Replace(Chr(13), "</li>" + Chr(13) + "    <li>")
    ListString = Selection.Text
    Selection.Delete
    Selection.TypeText ("<ul>" + Chr(13) + "    <li>")
    Selection.TypeText (ListString)
    Selection.TypeText ("</li>" + Chr(13) + "</ul>")
End Sub

Sub SpacingTable()
    'Add a table which puts space around Amazon
    'product links
    Dim TableString
    TableString = Selection.Text
    TableString = TrimPlus(TableString)
    With Selection
    .Delete
    .TypeText ("<table border=""0"" cellspacing=""10""")
    .TypeText (" align=""right""><tr><td>")
    .TypeText (TableString)
    .TypeText ("</td></tr></table>")
    End With
End Sub

Sub Link()
    'You can either select some plain text or a
    'URL to be turned into a link
    Dim LinkString
    LinkString = Selection.Text

    Dim HasNewLine As Boolean
    If Right(LinkString, 1) = Chr(13) Then
        HasNewLine = True
    End If

    LinkString = TrimPlus(LinkString)
    Selection.Delete
    If Left(LinkString, 4) = "http" Then
        Selection.TypeText ("<a href=""")
        Selection.TypeText (LinkString)
        Selection.TypeText ("""></a>")
    Else
        Selection.TypeText ("<a href="""">")
        Selection.TypeText (LinkString)
        Selection.TypeText ("</a>")
    End If
    'Fix up the new line
    If HasNewLine Then
        Selection.TypeText (Chr(13))
    Else
        Selection.TypeText (" ")
    End If
    Selection.MoveLeft
    'Put the cursor in the correct place so you
    'can complete the link
    Selection.MoveLeft Unit:=wdCharacter, Count:=4
    If Not Left(LinkString, 4) = "http" Then
        MoveCount = 2 + Len(LinkString)
        Selection.MoveLeft Count:=MoveCount
    End If
End Sub

Sub Splitter()
'Easily visible line for dividing posts
Sp = "*#*#*#*#*#*#*#*#*#*#"
Selection.TypeText (Sp + Sp + Sp + "*#*#" + Chr(13))
End Sub

Sub Adsense()
'For use with Adsense Injection plugin
NoAdsense = "<!--noadsense-->"
If Selection.Text = NoAdsense Then
    Selection.TypeText ("<!--adsensestart-->")
Else
    Selection.TypeText (NoAdsense)
    With Selection
    .MoveLeft Unit:=wdCharacter, Count:=16, Extend:=wdExtend
    End With
End If
End Sub

Tips for upgrading to WordPress 2.9 on 1and1

Thursday, December 24th, 2009

A few days ago I upgraded this blog from WordPress 2.8.5 to 2.9. Here are some tips on what I did in case you run into any of the same issues that I did. My blog is hosted by 1and1 and some of the information may be specific to them.

This isn’t meant as a full upgrade guide – just a collection of tips that may help you.

First make sure you backup your data! There are some general wordpress backup tips on a post I did about a previous upgrade.

1. Export the SQL database

In the MySQL admin panel I selected these extra options: ‘Add DROP TABLE’ and ‘Complete inserts’, and then chose to save the file as a .gz (gzip) archive. If you need a free application to read .gz archives then I recommend 7-Zip.

Oneandone MySQL icon

2. Export the XML data

Export the XML post data from the WordPress admin panel (Tools->Export).

3. Zip and downloaded the blog files

Zip up the actual files on the server. On 1and1 the easiest way to do this is to logon to your admin panel, go to the Webspace Explorer, right-click on the directory and select ‘zip’.

You can then right-click on the zip file and choose download to copy it down to your computer.

4. Verify the data

I verified that the exported SQL data, XLM and .zip files were valid. The easiest way to verify the SQL and XLM data is to look at it in a text viewer such as NoteTab Light and make sure that the data at the end of the file is valid. Sometime a download can silently fail and you can end up with truncated data. If you try to restore the data from a truncated file then the restore will fail.

Verify the .gz file by making sure it will open in 7-Zip.

Click on the upgrade button

I finally was ready to click on the upgrade button. I clicked on it and a second or two later I got the message:

‘The update cannot be installed because WordPress 2.9 requires MySQL version 4.1.2 or higher. You are running version 4.0.27’

How I got around it

The partial answer is contained in the post here. However I’ll add a few bits of information on what I did differently.

I created a new MySQL 5.0 database from the MySQL admin panel. On the 1and1 business hosting package I think you can create two MySQL databases so you don’t need to delete the existing one first. Don’t delete it – you may need it if everything goes wrong with the upgrade!

I didn’t import the data by using the XML backup. I imported the data into the new MySQL 5.0 database from the gzipped SQL archive that I’d created in step 1 above.

You can import the SQL data from the MySQL admin panel by going to the tab to execute SQL commands, and then selecting the .gz file. Importing the SQL file through a .gz file gets around the 2MB size limit in the MySQL admin panel.

Importing from the .gz file rather than the .XML will import all your database data, and plugin settings, whereas if you do it from the .XML file you may have to manually re-enter various settings into your blog.

In your wp-config.php you will have to ensure that the DB_NAME, DB_USER, DB_PASSWORD and DB_HOST have been updated with the settings of your new MySQL 5.0 database.

Upload the wp-config.php file and if everything has gone right your blog should still be working and look exactly the same as before. Your blog will be using the old version of WordPress but will be accessing the data from the new MySQL 5.0 database.

You should now be able to click on the upgrade button and the blog should upgrade in less than 5 seconds.

This worked fine for me on 1and1. If you have loads of plugins or a heavily customised theme you may find more problems. If this is the case you can try deactivating plugins, or switch to the default theme.

If you really can’t get things to work you should be able to roll back to your pre-2.9 WordPress blog by restoring the files that you zipped in step 3 above. You MySQL 4.0 database should still be there (as long as you didn’t delete it).

Upgrading WordPress can often be a pain but at least having upgraded the SQL database from 4.0 to 5.0 should avoid more problems in the future. And now with WordPress 2.9 you can look forward to batch updating your plugins rather than doing them one at a time!

Adding ‘Related Posts’ to WordPress articles and 404 error pages

Tuesday, July 22nd, 2008

Many blogs have a list of related articles after each of their posts. I wanted something similar for my WordPress blog but found it wasn’t as easy to do as I thought it would be.

At the same time I was interested in capturing any access attempts to non-existant pages (causing a 404 error), and showing a list of suggested links. This is something that is useful to do to turn people who get 404 errors into readers of your blog.

I first looked at the WASABI related post plugin. It did what I wanted with the related entries but it requires you to add a tag to each post where you want the related entries to appear. There is also a version of the plugin which can generate sensible links for any 404 errors. It does this by turning the incorrect URL into a list of terms which are then used to find related posts.

The next plugin that I read about was called ‘Aizattos Related Posts’. This plugin was originally based on WASABI but has evolved since. It inserts related links without needed to add any special tags to the posts. A lot of good feedback was given about this plugin but it seems that the author has removed it from the original download site. Fortunately someone has re-posted this plugin to this site.

I therefore have what I need in two separate plugins. I installed the Aizattos Related Posts plugins and then created a modified version of the WASABI 404 handling code. The 404 handler is in one function ‘related_posts_404′. Below is the modified version of the WASABI code which will work with the Aizattos Related Posts plugin. As well as showing the related links it also shows an extract from the post page. Just put this function in the Aizattos Related Posts plugin PHP file.

related_posts_404()
function related_posts_404($limit=5, $len=50,
	$before_title = '', $after_title = '',
	$before_post = '', $after_post = '',
	$show_pass_post = false, $show_excerpt = true) {

    global $wpdb, $post;

    $before_title   = '<span class="aizatto_related_posts_title" >';
    $after_title    = '</span>';
    $before_excerpt = '<div class="aizatto_related_posts_excerpt">';
    $after_excerpt  = '</div><p></p>';
    $before_related = '<li>';
    $after_related  = '</li>';

    $search_term = $_SERVER['REQUEST_URI'];
    $search = array ('@[\/]+@', '@(\..*)@', '@[\-]+@', '@[\_]+@', '@[\s]+@', '@archives@','@(\?.*)@','/\d/');
    $replace = array (' ', '', ' ', ' ', ' ', '', '','');
    $search_term = preg_replace($search, $replace, $search_term);
    $search_term = trim($search_term);
    $terms = $search_term;

    $time_difference = get_settings('gmt_offset');
    $now = gmdate("Y-m-d H:i:s",(time()+($time_difference*3600)));

    // Primary SQL query
    $sql = "SELECT ID, post_title, post_content,"
         . "MATCH (post_name, post_content) "
         . "AGAINST ('$terms') AS score "
         . "FROM $wpdb->posts WHERE "
         . "MATCH (post_name, post_content) "
         . "AGAINST ('$terms') "
		 . "AND post_date <= '$now' "
         . "AND (post_status IN ( 'publish',  'static' ) && ID != '$post->ID') ";
    if ($show_pass_post=='false') { $sql .= "AND post_password ='' "; }
    $sql .= "ORDER BY score DESC LIMIT $limit";
    $results = $wpdb->get_results($sql);
    $output = '';
    if ($results) {
        foreach ($results as $result) {
            $title = stripslashes(apply_filters('the_title', $result->post_title));
            $permalink = get_permalink($result->ID);
            $output .= $before_title
                .'<a href="'. $permalink .'" rel="bookmark" title="Permanent Link: '
		. $title . '">'
		. $title . '</a>'
		. $after_title;
            if ($show_excerpt=='true') {
                $post_content = strip_tags($result->post_content);
                $post_content = stripslashes($post_content);
                $words=split(" ",$post_content);
                $post_strip = join(" ", array_slice($words,0,$len));
                $output .= $before_excerpt . $post_strip . $after_excerpt;
                }
        }
        echo $output;
    } else {
        echo $before_title.'Fuzzy ...'.$after_title;
    }
}

Although no code modifications are needed for the related links in your normal posts, you will have to make a modification to your theme’s 404 page if you want related links for any ‘Not Found’ errors. In blue below is the modification I made to my 404.php for the default theme.

\blog\wp-content\themes\default\404.php
<?php get_header(); ?>

	<div id="content" class="narrowcolumn">

		<h2 class="center">Error 404 - Not Found</h2>

		<p>We're sorry but the page you are looking
		for isn't at this location. Were you perhaps
		looking for one of these articles?</p>

		<?php related_posts_404(); ?>

	</div>

<?php get_sidebar(); ?>

<?php get_footer(); ?>