Append to Drupal Node Body From Specific Content Types

Imagine you have a situation where you want to append Body content to a number of Drupal pages, according to content type.

e.g., to all "Stories" content add "Please contact Mr. Blah on 0400 123 123" at the end of the Body.

You don't want this as block either - it's the sort of thing that (for example) must be printed. It has to be appended in the 'Body' section of the node.

If this is a couple of pages perhaps you could just copy and paste. But for larger numbers this is not recommended. Imagine if you had to modify twenty nodes, or two thousand.

One fairly easy way to do this is via MySQL commands (with a little bit of sed). There is no doubt it is possible to combine the two SQL commands into one and skip the sed step - but this worked nonetheless.

Firstly, logon to MySQL, or use PhPMyAdmin and select your database.

From the node table generate a list of node identities according to content type e.g.,

SELECT nid FROM node WHERE TYPE LIKE "stories" OR TYPE LIKE "news" OR TYPE LIKE "press_releases" OR TYPE LIKE "policy";

As an excersise in intellectual laziness, this list of node IDs was simple stuck in a text file (append.txt) and a couple of sed commands parsed over them.


sed -i 's/^/"/' append.txt
sed -i "s/^/UPDATE node_revisions SET body = CONCAT(body,' Please contact Mr. Blah on 0400 123 123') WHERE nid = /" sqltest.txt
sed -i 's/$/";/' append.txt

The first sed command adds a " at the beginning of the node ID. The second sed command adds the MySQL statement which appends, through CONCAT, to body. The third adds a closing " to the node ID and adds a MySQL delimiter at the end of the line. The result will look something like this;


UPDATE node_revisions SET body = CONCAT(body,' Please contact Mr. Blah on 0400 123 123') WHERE nid = "1193";
UPDATE node_revisions SET body = CONCAT(body,' Please contact Mr. Blah on 0400 123 123') WHERE nid = "1195";
UPDATE node_revisions SET body = CONCAT(body,' Please contact Mr. Blah on 0400 123 123') WHERE nid = "1196";
UPDATE node_revisions SET body = CONCAT(body,' Please contact Mr. Blah on 0400 123 123') WHERE nid = "1197";
UPDATE node_revisions SET body = CONCAT(body,' Please contact Mr. Blah on 0400 123 123') WHERE nid = "1201";

Simply run the file of MySQL commands and you're done. Note that this will make a change to all previous revisions as well.

Brett Pemberton has suggested the following:

Feeling confident? Do it in one query:

UPDATE node_revisions,node SET node_revisions.body = CONCAT(node_revisions.body,' Please contact Mr. Blah on 0400 123 123') WHERE node.nid = node_revisions.nid and (node.type = "stories" or node.type = "news" or node.type = "press_releases" or node.type = "policy")';