Tag Archives: PHP

Small testing for array_combine in PHP4

One of mine bbPress plugin is not compatible with PHP4. It uses array_combine. There are few suggestions from comments, but it’s hard to pick one without information. Therefore I did a quick test, which is for execution speed.

<?php
$start = microtime();
define('RAND_MAX', mt_getrandmax());
$key = array();
for ($i=0; $i<5000; $i++)
    $key&#91;&#93; = 'key' . mt_rand(0, RAND_MAX);

$value = array();
for ($i=0; $i<5000; $i++)
    $value&#91;&#93; = 'value' . mt_rand(0, RAND_MAX);
// http://www.php.net/manual/en/function.array-combine.php#78244
function array_combine1($arr1,$arr2) {
    $out = array();
    foreach($arr1 as $key1 => $value1)
        $out[$value1] = $arr2[$key1];
    return $out;
    }
// http://www.php.net/manual/en/function.array-combine.php#77231
function array_combine2($keys, $values) {
    $result = array();
    foreach(array_map(null, $keys, $values) as $pair)
        $result[$pair[0]]=$pair[1];
    return $result;
    }
// http://www.php.net/manual/en/function.array-combine.php#76994
function array_combine3($keys, $values) {
    $result = array() ;
    while( ($k=each($keys)) && ($v=each($values)) ) $result[$k[1]] = $v[1] ;
    return $result ;
    }
// http://www.php.net/manual/en/function.array-combine.php#74412
function array_combine4($a1,$a2) {
    for($i=0;$i<count($a1);$i++)
        $ra&#91;$a1&#91;$i&#93;&#93; = $a2&#91;$i&#93;;
    if(isset($ra)) return $ra; else return false;
    }

echo microtime() - $start, "\n";

$start = microtime();
$kv = array_combine($key, $value);
echo microtime() - $start, "\n";

$start = microtime();
$kv1 = array_combine1($key, $value);
echo microtime() - $start, '|', $kv == $kv1, "\n";
unset($kv1);

$start = microtime();
$kv2 = array_combine2($key, $value);
echo microtime() - $start, '|', $kv == $kv2, "\n";
unset($kv2);

$start = microtime();
$kv3 = array_combine3($key, $value);
echo microtime() - $start, '|', $kv == $kv3, "\n";
unset($kv3);

$start = microtime();
$kv4 = array_combine4($key, $value);
echo microtime() - $start, '|', $kv == $kv4, "\n";
unset($kv4);
?>

Result is (tested in PHP 5.2.4, not quite a useful testing since should be tested in PHP 4):

0.03834
0.001877
0.005486|1
0.018785|1
0.037229|1
0.015718|1

Obviously, first one is the winner. It should also use less memory footprint, since the code is simpler than others (no additional function calls or double indexing).

Put Gravatar on

I wrote a Gravatar plugin for bbPress few days ago and I just saw Matt’s new post then, Gravatar-enabled.” It’s time to put avatars on my blog. It’s quite easy.

Where size is the size of avatar in pixel. Currently, Gravatar supports up to 80px. Soon, it will support up to 125px. The code can be done in just one line. Put it in proper place within comments loop, usually found in comments.php, and set a good style class avatar for img tag in your style.css.

If you have your own default image for commentators who haven’t used Gravatar, you can make the code as

Where $default_uri is the URI of your default image. If you default image has different size, you better to add width and height to img tag.

WP Plugin: On this day… 0.1 released

On this day...This plugin is inspired by “On this day” in Wikipedia’s home page. It can list posts which have same calendar date as today’s or as specific post’s.

Features

  • Support Widget
  • Options Page
  • Search Form

It should be used (as widget) at sidebar, at the main posts loop, or at single post. Usually, just call OTDList() where you need to list. You may need to add title to the list, e.g. “On this day…”, before calling OTDList(). If you use it as widget, then a default title will be added automatically.

If you need to list posts which have same calendar date as a specific post, you can pass this post object as the first parameter when calling OTDList(), e.g. OTDList($specificPost).

There is a plugin options page, you can set the default options in that page. You still can override option when calling OTDList(), if necessary.

Please visit this plugin’s website for more information, submiting bugs, or discuss here.

Code Snippets: On this day…

Updated: New plugin based on these code snippets.

I think if I can know what I wrote in one year ago, then I may be able to write another post after one year. So I wrote these simple code. The first one is used in main posts loop, you might want to use is_single() for checking whether is in single post mode.


$onthisday = $wpdb->get_results("SELECT ID, post_title, post_date FROM $wpdb->posts WHERE post_status= \"publish\" AND post_type=\"post\" AND post_date_gmtID ORDER BY post_date DESC LIMIT 5");
$oldPost = $post;
if(sizeof($onthisday)>0)
foreach($onthisday as $post)
echo get_the_time("Y") . ': ID) . '">' . the_title('','',FALSE) . '
';
else
echo "No other post on this day.";
$post = $oldPost;

First line, retreive posts which have been published before current time, and posts’ publishing month and day are the same as current viewing post’s. For each post, prints the year, then the post’s title and link.

Next code snippet is similar to first one. It should be used as showing posts whose publishing month and day are the same as current month and day. In order to match time zone offset, we need to get gmt_offset from WordPress and use the offset to query from wp_posts.


$time = time() + (get_option('gmt_offset') * 3600);
$onthisday = $wpdb->get_results("SELECT ID, post_title, post_date FROM $wpdb->posts WHERE post_status= \"publish\" AND post_type=\"post\" AND post_date_gmt 0)
foreach($onthisday as $post)
echo get_the_time("Y") . ': ID) . '">' . the_title('','',FALSE) . '
';
else
echo "No other post on this day.";
$post = $oldPost;

Please copy the source here. You can see the result below this line.

Stick in execute-pings.php in WordPress 2.0.4

When you save or publish a post, then you get stuck… Then you found out the problem is on execute-ping.php. I did some seraching works. But none of them can solve this problem. Finally, I found out and I think the problem is caused by a while loop in wp-includes\functions.php

$response = '';
fputs( $fp, $head );
while ( !feof( $fp ) && strpos( $response, "\r\n\r\n" ) == false )
	$response .= fgets( $fp, 2048 );

Continue reading

lb_langlink: 在WordPress文章標題後加入其他語言版本的連結

Screenshot這是第一個公開版本,這個WordPress Plugin能讓你在文章標題後面加入到其他特定文章連結,這些連接是該篇文章的其他語言版本。你只需要加入一個Custom Field,詳細的安裝及使用請閱讀這個wiki頁面,你也可以在頁面下載檔案。
如果你使用一段PHP來顯示你最近幾篇的文章,你可能也想要這個plugin能在這段PHP作用。以下是我用在sidebar的PHP

< ?php
$how_many=5; //How many posts do you want to show
require_once("wp-config.php"); // Change this for your path to wp-config.php file
$news = $wpdb->get_results("SELECT `ID`,`post_title`, `post_date` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_date_gmt` < = UTC_TIMESTAMP() ORDER BY 'post_date' DESC LIMIT ".$how_many);
if(sizeof($news)>0){
	echo "<ul>";
	foreach($news as $np){
		echo '<li>';
		echo apply_filters('the_title', '<a href="' . get_permalink($np->ID) . '">' . $np->post_title . '</a>', $np);
		echo '</li>';
		}
	echo "</ul>";
	}
?>

另外如果你使用WordPress Related Entries 2.0 Plugin,可能會出現些問題。你可以修改

$title = stripslashes(apply_filters('the_title', $result->post_title));

成為

$title = stripslashes(apply_filters('the_title', $result->post_title, $result));

related-posts.php,就應該沒有問題了。

lb_langlink: Adding language links after post title in WordPress

ScreenshotThis is first public release. This WordPress Plugin can add links after posts’ title. The links are other languages of current post. If you write a post in different languages, this plugin can add links for you. The only thing you have to setup is adding a Custom Field. For detail installation and usage, please read this wiki page. And you can also download it from that wiki page.
If you have a PHP code for showing recent posts of your blog, you may want this plugin also works for that PHP code. Here is a sample code I used in my sidebar.

< ?php
$how_many=5; //How many posts do you want to show
require_once("wp-config.php"); // Change this for your path to wp-config.php file
$news = $wpdb->get_results("SELECT `ID`,`post_title`, `post_date` FROM $wpdb->posts WHERE `post_status`= \"publish\" AND `post_date_gmt` < = UTC_TIMESTAMP() ORDER BY 'post_date' DESC LIMIT ".$how_many);
if(sizeof($news)>0){
	echo "<ul>";
	foreach($news as $np){
		echo '<li>';
		echo apply_filters('the_title', '<a href="' . get_permalink($np->ID) . '">' . $np->post_title . '</a>', $np);
		echo '</li>';
		}
	echo "</ul>";
	}
?>

If you use WordPress Related Entries 2.0 Plugin, there might be some problems. You can replace

$title = stripslashes(apply_filters('the_title', $result->post_title));

with

$title = stripslashes(apply_filters('the_title', $result->post_title, $result));

in related-posts.php. This should work.

Hiding some contents when you are the visitor on WordPress and MediaWiki systems

I don’t want visitor tracking service provider to track me. I am the webmaster. I should not in log. So I use the following code:

< ?php
$showthem = true;
if(defined('WPLANG')){ // Check for WordPress
	global $user_identity;
	if($user_identity == 'YOURNAME'){
		$showthem = false;
		}
	}
if(defined('MEDIAWIKI')){ // Check for MediaWiki
	global $wgUser;
	if($wgUser->getName() == 'YOURNAME'){
		$showthem = false;
		}
	}
if($showthem){
?>
	Contents for real visitors
< ?php
	}
?>

Note: I don’t know is that a good idea for detecting WordPress by using WPLANG.

Listing blog recent posts in root’s index page

I have WordPress Blog system in /blog, but the index page of my website is in /. How do I add recent posts in root’s index page. Designing a root’s index page you like. And add the following code in the place you list the recent posts:

< ?php
define('WP_USE_THEMES', true);

if (! isset($wp_did_header)):
if ( !file_exists( dirname(__FILE__) . '/blog/wp-config.php') ) {
	if ( strstr( $_SERVER&#91;'PHP_SELF'&#93;, 'wp-admin') ) $path = '';
	else $path = 'wp-admin/';
    die("There doesn't seem to be a <code>wp-config.php file. I need this before we can get started. Need more help? <a href='http://wordpress.org/docs/faq/#wp-config'>We got it</a>. You can <a href='{$path}setup-config.php'>create a <code>wp-config.php</code> file through a web interface</a>, but this doesn't work for all server setups. The safest way is to manually create the file.");
}

$wp_did_header = true;

require_once( dirname(__FILE__) . '/blog/wp-config.php');

wp();
gzip_compression();

$how_many=10; //How many posts do you want to show

$news=$wpdb->get_results("SELECT `ID`,`post_title`,`post_date` FROM $wpdb->posts
WHERE `post_status`= \"publish\" AND `post_date_gmt` < = UTC_TIMESTAMP() ORDER BY 'post_date' DESC LIMIT ".$how_many);
foreach($news as $np){
print ("<tr><td>");
echo $np->post_date;
print ("</td><td><a href=\"");
echo get_permalink($np->ID);
print ("\">$np->post_title</a></td>");
}
endif;
?>

The code might have some dummies, because I don’t quite understand the WP system and PHP. But it works. If you want to list more information like authors or category, you may read Database Description of WP for more info.

Design a site like this with WordPress.com
Get started