Export Wordpress to Tumblr
Well I finally made the switch. After ignoring my old (Wordpress) blog for 2 years I decided to make the move to Tumblr.
I didn’t want to lose all of my previous content but for some reason it was rather difficult to find a solid way to import my old Wordpress content into Tumblr.
The best I found was
How to Make Simple Cross-Domain Ajax Requests With Responses
For Read It Later for the iPhone, I built a ‘Tap to Save’ bookmarklet for Mobile Safari. When using Tap to Save, instead of opening a link when clicked, the link is saved to a user’s reading list. This makes it easy to save a few links from a web page without having to open each one individually. The problem I came across however was I could not do an ajax request to send the link to the Read It Later server because cross-domain browser restrictions. I could use an iframe to send the request, but again because of cross-domain issues, I would not be able to retrieve a response from inside of it. After the request was sent, there were 3 possible outcomes: Success, the user needs to login, or there was a problem saving. The method that eventually dawned on me is rather hackish, but it works none-the-less. It provides a way to send a request to any domain and get a basic response. The solution: Images are not subject to cross domain restrictions. So load an ‘image’ with a get string that hits a script on the server and then returns an different sized image per possible outcome. If that makes absolutely no sense, let me try to illustrate with an example that provides a response with two options: success/failure.Starting the Request: (Javascript: Client Side)
Handling the Request (Server Side):
The image is now loading this script:
<?php
/* ... do your request processing here ... */
// Based on the result of the script, we either return a
// 1px wide image (in the case of success) or
// 2px wide image (in the case of failure)
// you'll need to create these images yourself
if ($success) {
$file = file_get_contents( '1x1.gif' );
} else {
$file = file_get_contents( '2x1.gif' );
}
// output the image
$length = strlen($file);
header('Last-Modified: '.date('r'));
header('Accept-Ranges: bytes');
header('Content-Length: '.$length);
header('Content-Type: image/gif');
print($file);
?>
Handling the Response: (Javascript: Client Side)
Back on the javascript side of things, we have our ajaxTimer checking to see if the image is loaded. Once the image loads, we’ll check the width.
function isImageLoaded() {
if (ajaxImg.complete) {
var w = ajaxImg.width;
if (w == 1) {
alert('Success!');
} else if (w == 2) {
alert('Failed!');
}
// Hide the image (even though you probably won't see it
ajaxImg.style.display = 'none';
// Stop the timer
clearInterval(ajaxTimer);
}
}
Simple Works Best
As you can see, this works well if you only have a few possible outcomes of the transaction or if you do not need to return a literal response like generated markup.IE Woes
Surprisingly, this DOES work in IE6 and IE7, however there is a little bit of extra work. The url of the request you load into the src of the image has to have .gif in it. For example: ‘script.php’ won’t work, but ‘script.gif’ will. So to make this work you’ll need to add an Htaccess rewrite rule to redirect the script.gif to your script.php file.How to Block Email From a Specific Address on a Cpanel/WHM or Other Web Server Using Exim
While working on a client project that had a mass member email function, I needed a way to test the system exactly as it would run in production. This meant, when it ran, it would send emails to all of the members in the directory instead of a test email address. The only problem was I didn’t want to send test emails out to the thousands of members in the directory. So I wanted a way have PHP still send the email out as it normally would but have the mail server (EXIM) kill it before it left the server. Luckily this is very easy to do. With EXIM, you can setup filters that can perform a large number of tasks, like blocking message, or blind copying messages to other email addresses. In this case, I’m going to create a filter to cause an email coming from a specific sender to fail (the email address I use to send the email in PHP). What you’ll want to do is find your System Filter File for EXIM. In WHM, you can find this file listed in your EXIM Configuration Editor about half way down the page. Once you’ve located the file, log into SSH and edit the file.
if first_delivery
and ( ("$h_from:" contains "emailtoblock@mydomain.com")
)
then fail
endif
if first_delivery
and ( ("$h_from:" contains "emailtoblock@mydomain.com")
)
then
unseen deliver "youremail@yourdomain.com"
fail
endif
When Dynamically Generating CSV, Don’t Forget the Quotes
I was generating CSV files with PHP so that a client could easily export their mailing list from the database when I hit a snag with loading the generated files on a Mac.
I received the error message:
“SYLK: file format is not valid.” when opening the file in Excel on OS X.
To solve the problem, simply make sure all data is enclosed with quotes.
Ex: ‘ID’,’First Name’, ‘Last Name’
Found this on Microsoft’s website: http://support.microsoft.com/kb/323626
Cleaner Print Command in PHP
Stumbled upon this by accident and I haven’t been able to find anything in the PHP documentation because you can’t search for non-alpha characters, but this find has cleaned up my code a ton.
<?php print ‘Hello World’; ?>
Works the same as:<?= ‘Hello World’ ?>
I’m using PHP 5, so I don’t know if this works in previous versions.Least Common Mulitple and Greatest Common Factor (LCM,GCF) in PHP and Javascript
I would imagine this is a good time to tell my Math teacher that maybe he was right and I would need this in the real world. While working on Idea 27, I needed a script to calculate the least common multiple from a set of numbers. To my surprise I had some difficulty finding a script to do that. So I brushed up on my 6th grade math and made one. I’ve added a set for both PHP and Javascript below, I’m sure you could easily read them for any language.
Usage
To calculate the Greatest Common Factor of two numbers, use the ‘gcf’ function. Ex: gcf(6, 10) To calculate the Least Common Multiple of two numbers, use the ‘lcm’ function. Ex. lcm(6, 10) To calculate the Least Common Multiple of more than two numbers, enter an array into the lcm_nums function. Ex: lcm_nums( array(6, 10, 4, 9, 54) )
PHP Code
function gcf($a, $b) {
return ( $b == 0 ) ? ($a):( gcf($b, $a % $b) );
}
function lcm($a, $b) {
return ( $a / gcf($a,$b) ) * $b;
}
function lcm_nums($ar) {
if (count($ar) > 1) {
$ar[] = lcm( array_shift($ar) , array_shift($ar) );
return lcm_nums( $ar );
} else {
return $ar[0];
}
}
Javascript Code
function gcf(a, b) {
return ( b == 0 ) ? (a):( gcf(b, a % b) );
}
function lcm(a, b) {
return ( a / gcf(a,b) ) * b;
}
function lcm_nums(ar) {
if (ar.length > 1) {
ar.push( lcm( ar.shift() , ar.shift() ) );
return lcm_nums( ar );
} else {
return ar[0];
}
}
Wordpress Plugin: Extra Comment Fields
Overview
This Wordpress plugin allows you to add additional fields for users to complete when submitting a comment. The extra data will be saved in the wp database and can be retrieved when showing a post’s list of comments. The extra comment variables will show up in the list of comments in your Wordpress admin and are editable through the standard admin comment edit page. This plugin requires a basic knowledge of HTML to modify your comment form. Jump to DownloadExample of Use
For this example, we are going to add a field asking for a users age to the comments form.1. First, add the field to your comments form.
Typically your comments form is in your theme folder and is comments.php Most likely: (/wp-content/themes/YOURTHEME/comments.php) Enter the HTML of your new field into the desired spot. To add a textfield for the user to enter their age into, you would add the following to your form. I’ll add mine right below the url textfield.<p><input type="text" name="age" id="age" size="22" /> <label for="url"><small>Website</small></label></p>
2. Next, we need to add the field-variable to Wordpress.
Inside your Wordpress admin, click the ‘Settings’ menu. Then click the ‘Extra Comment Fields’ menu. Next, enter the name of the field. This has to be the exact name attribute you gave to the field you added to your comments form. For example, I added this field to my form:<p><input type="text" name="age" id="age" size="22" /> <label for="url"><small>Website</small></label></p>
3. Last we want to make use of the data somehow when showing comments.
Your extra fields will be in the $comments variable retrieved by Wordpress. The extra fields you added will have a prefix of ‘extra_’. So to access the data for our ‘age’ field, we use $comment->extra_age inside the comments loop. So, for example, if I modify the default theme’s comment.php file, I just insert one line to display the extra comment information (highlighted in bold).Another Example Posted on Problogger
How I added the Twitter ID field to comments on Twitip.comVersion History
1.2 - June 23rd, 2008- Corrected behavior when deleting/changing status of comment
- Fixed blank comment content field
- Updated for WP 2.5
- Added ability to edit comments
- Added ability to view comments in admin
- Extra Comments data deleted when comment is deleted
- Fixed database table prefix
- Initial Release
Download
NOTE: I am no longer developing this plugin. If you’d like to continue it, please consider it open source. If you release a new version, update users in the comments below. Thanks Download the Extra Comment Fields Wordpress Plugin version 1.2 Beta (For Wordpress 2.5+) Download the Extra Comment Fields Wordpress Plugin version 0.2 Alpha (Only for Wordpress 2.0 - 2.3) To install, unzip the files into your /wp- content/plugins/ folder. Then activate it under the Plugin menu in your Wordpress admin.Important Note When Upgrading from 0.2 to 1
If your Wordpress database tables do not start with ‘wp_’, you will likely need to rename the wp_comments_extra table in your database to match the other table’s prefix. This is a result of the first version incorrectly assuming the prefix across all installations. For example, if you have have tables named called prefix_posts, prefix_comments, prefix_options, etc then you should rename the wp_comments_extra table to prefix_comments_extra.One Pass Parent-Child Array Structure
During the time that I’ve been programming I’ve continually run into times when I needed to be able to store a multi-level list into a database and retrieve it. I’ve used this in a CMS system to allow uses to create and nest their own menu options or to allow users to create and nest categories of items. Saving it was never a problem, but retrieving it and building a PHP array with nested structure was a messy task.
| Database Table: Items | ||
| Id | Parent Id | Name |
| 1 | 0 | North America |
| 2 | 1 | Canada |
| 3 | 7 | California |
| 4 | 0 | Europe |
| 5 | 0 | Antartica |
| 6 | 3 | Los Angeles |
| 7 | 1 | United States |
| 8 | 7 | Florida |
| 9 | 3 | Hollywood |
| 10 | 2 | Quebec |
- Antartica
- North America
- Canada
- Quebec
- United States
- California
- Hollywood
- Los Angeles
- California
- Florida
- Canada
- South America
The Solution
Let me show you what it looks like:$refs = array();
$list = array();
$sql = "SELECT item_id, parent_id, name FROM items ORDER BY name";
$result = mysql_query($sql);
while($data = @mysql_fetch_assoc($result)) {
$thisref = &$refs[ $data['item_id'] ];
$thisref['parent_id'] = $data['parent_id'];
$thisref['name'] = $data['name'];
if ($data['parent_id'] == 0) {
$list[ $data['item_id'] ] = &$thisref;
} else {
$refs[ $data['parent_id'] ]['children'][ $data['item_id'] ] = &$thisref;
}
}
How it Works
PHP References
This solution’s core is based on using PHP References. A reference allows you to access the same variable but with different names. In other words, it allows you to assign aliases to a variable. This way, any changes made to the reference will also affect the original variable. Here’s an example:Two Lists
To solve this, we are going to use not one, but two arrays. We will have our main array which is the one we are building with multilple levels, and secondly, we will have a single-level array that is all references to parts of our main list. This will allow us to target deep inside of the array without knowing the depth, or all of the parents above the level. Let me explain how this will look in a more visual way.
On the left, we have our references array and on the right we have the list we are building with multiple levels. Now you have two ways to make an adjustment to a variable deep inside the main array, such as adding ‘Miami’ to Floria.
$main_list[‘North America’][‘children’][‘United States’][‘children’][‘Florida][‘children’][] = ‘Miami’; or $references[‘Florida’][‘children’][] = ‘Miami’; You can see how it is much easier to target deep inside of the array using the reference, rather having to know the entire structure above where Florida is.
All Together Now
So when you extract the data from the database you will do the following process, repeating until all the data has been processed.- Add item to reference list
- If item has no parent (meaning it’s a top level item), add item reference to top level of build list.
- If item has a parent, add the item reference to it’s parents list of children.
Watch It Step by Step
If I’ve completely lost you, I suggest that you take a look how this works step by step. I’ve provided an example of building the location list above, where it prints out what the reference and main list look like after each item as been added. You can view that here.Ternary Operator in PHP (and javascript)
Where I learned about it: http://blog.rightbrainnetworks.com/2006/09/18/10-things-you-probably-didnt-know-about-php/
