Categories
Wordpress

WordPress: Custom Post Permalink giving 404

In most of wordpress project we do, we have few custom post type and taxonomy. We use a nice plugin called “PODs” for the same. It is good plugin, we try some other in different project and most of them serve the purpose pretty well. But today we found something, or rather just an overlook stuff. In our project we need a taxonomy to hold “year” of manufacturing for product, client request that year to be a taxonomy (yes, out client is intelligent and know such stuffs. So?). We follow him and quickly create a taxonomy with slug “year”.

Now, what we did is we broke the permalink of wordpress. It either work for our custom post permalink or default wordpress page. We spend 5 hours to realise that “year” is one of wordpress keyword in sense that wordpress use it for “archive” or dated url permalink structure. I didn’t go in depth of why and what got it broken, but since wordpress use year it is bad idea to use it. Infact this post is reminder for me to not to use words like year, month, archive, category, date, day as my taxonomy of custom post type. They are just not good. Period.

And advice of word for pods, or any plugin that allow creation of such post type. PLEASE, put some validation to stop user from doing such things. User may not read this blog post soon.

Categories
PHP Programming Wordpress

How to Programmatically Add Multi Language Post in WordPress and WPML

I recently need to create wordpress post programmatically. It is so easy with wp_insert_post. However, the twist is how to add it using WPML for multi language support. WPML is nice plugin, but I didn’t find straight forward answer to it. Than I found a nice article from Ionuț Staicu, that does what I need. And it is the most popular article I found and seems like only solution people have. Article can be read in http://www.iamntz.com/3424/frontend-developer/programmatically-insert-posts-in-wordpress-and-set-language-for-wpml-plugin/. Though it doesn’t seems to solve my problem.

I email Ionuț Staicu, and to my surprise the nice guy email me back in couple of hour, and give me few suggestion and even his code snippet. I really love reading his code. On trying that code I found that he copy WPML API wpml_add_translateable_content function in his code and comment out the Check for duplicate addition of same content.

Doing so make my code work, but I was not satisfied. Sorry Ionuț Staicu, that doesn’t make me happy. Reason was simple. A company running such plugin cannot make such silly mistake. I trust WPML developer, they are of course better than me to realise what they are putting as check. 

So, what is wrong in my code? Well the answer was simple. WPML hook wp_insert_post to run “add_translate”. So, you don’t have to call it. However to add multiple language you need to call “wp_insert_post” for all language you want to add the code. This is easy..huh? no it is not easy. WPML call add_translate, but didn’t link them. I am not sure if they have any “insert” meta field that does the link. But there is no clearer way I found. So, I go back to add_translateable function and found that they have nothing but only

$sitepress->set_element_language_details(...);

other than checks. So, what does this function do. Simple, it change/add the Translation into database. So, all I have to do is, I need to update the Secondary language with the transalation id [3rd parameter of set_element_language_details ] to my default translation ID. Sound complex, no worries just read code below:

$_POST['icl_post_language'] = $language_code = 'he';  //Setting hebrew post. Ionuț Staicu suggest to have $_POST set. I follow him
$newPostID = wp_insert_post( $PostDATA );	//See wp_insert_post for details		

$trigid = wpml_get_content_trid('post_property', $newPostID); // Find Transalation ID function from WPML API. 

$_POST['icl_post_language'] = $language_code = 'fr'; // Set another language
$tpropertyid1 = wp_insert_post( $PostDATA ); // Insert French post
$sitepress->set_element_language_details($tpropertyid1, 'post_property', $trigid, $language_code); // Change this post translation ID to Hebrew's post id

//Repeating for English post.
$_POST['icl_post_language'] = $language_code = 'en'; 
$tpropertyid2 = wp_insert_post( $PostDATA );
$sitepress->set_element_language_details($tpropertyid2, 'post_property', $trigid, $language_code);

So, that just insert and link all languages you want. I did this in PHP CLI command line, and it works like charm. Hope this help someone. 

 

 

Categories
Bookmarked Wordpress

Some Cool WordPress Plugin

Lately, I got lot of wordpress site, that were not just blog or business website. But they are ecommerce, Restaurant Ordering, Video streaming and much more. Been a developer I always remain engage in making some sort of plugin for them. Though following list of plugin assist me a big time in saving time to do some of works I usually have to do to make some really nasty site in wordpress:

The list is of plugin I usually use, but not restricted to. There are couple more of plugin but currently I am unable to recall them. Meanwhile we also create a small plugin used for very limited set of user:

https://github.com/Vikasumit/wpl [Allow only members to see the complete site].

I have few other plugin coming up, but still not ready to launch them in public as they are not yet finish or are mature products. Love the fact that WordPress plugin development is as cool as working on any other project. Just need some good idea to make it possible.

Categories
Joyous PHP Programming Wordpress

Video Shopping Plugin

Just finish coding major stuff of Video plugin for wordpress that enable Purchase of Video and then view to only registered members. This use Paypal Express Checkout as payment gateway. Love coding on wordpress at time, though it is not as good as doing in custom CMS, but still very much a home for me now. I use couple of other plugin to support my plugin, but in all just love the expendability of WordPress. The hooks, filter they are all awesome. 

I love the concept of Hooks in wordpress than any other open source software I worked on. However still trying to figure why wordpress use so much of database query and why they do not certain function outside the loop. 

Telling more about my plugin, it allow admin to upload Video files, put their price. Then on front end choose filter to find video and add to cart using AJAX. once in cart you can proceed with checkout as wordpress user only and pay through paypal. View purchased video in MY Video pages, unless you are logged in you cannot view the video not from direct link too. 

Unfortunately this plugin is built on contract and need lot of work to make it generic to release under my belt, but if anyone need it I can still help with it :). Someday probably I can release this plugin under my name. What you think shall I release it free or paid … 

Categories
Wordpress

WordPress Plugin: Localization

This is quick steps on how to create your own Language file for wordpress plugin. I hope you know that you can call wordpress localization functions as

echo __('text your want to display', 'your-unique-language-textdomain'); 

This localization is done using internal function of wordpress, where it load language file for given language wordpress is set, and then loading relevant language files for translation  Since you are making your own plugin you need to create your own language file. So to do that simply do this:

1. Download POEdit software from : http://sourceforge.net/projects/poedit

2. Now create a new catalogue and define the Source Path as your plugin folder.

3. Define keywords as “__” double underscore and “_e” .

4. Once done click “Update” or “parse code” to prepare dictionary of text.

5. Simply select text and edit it in your language.

6. Now save the file in a folder within your plugin folder with any name just add dash followed by Language code as you define in “WPLANG” i.e. -hi-IN for Hindi-India. 

7. Add or call following if you have your language file in “lang” folder or change path as per your language file path.

load_plugin_textdomain('your-unique-language-textdomain', false, basename( dirname( __FILE__ ) ) . '/lang');

8. Enjoy

Categories
PHP Wordpress

WordPress: Black and White Post Overlay Image

One of my client ask us to create Black and white thumbnail for wordpress blog post that on mouse over turn coloured. This is pretty common effect now a days and with my custom PHP or ASP.NET programming we usually create black and white image at time of upload and save it. This is what we need to do in WordPress. To save time in research [or rather I found this good article] http://bavotasan.com/2011/create-black-white-thumbnail-wordpress/ Where author try to give a good way of creating thumbnail.

At first I was impressed and feel lucky to find a good looking tutorial/article and thought it will be piece of cake now, however as I progress I found that main article miss few things

1. It doesn’t work. Yes the article in its current state didn’t work.

2. It do not filter image if it is of same size as size you need on thumbnail [as define by one of commenter].

3. It fail to create Black and white image

4. It fail to get Black and White image in HTML piece of code.

Starting from #1, ofcourse I get it to working now. So that will you will see later. I follow the commenter’s code to fix the point 2,and frankly I personnally don’t know if it is any good or not. But check looks good in current state so I keep it. Now the problem is it doesn’t create Black and white image for some user and for me. After searching for couple of minutes I found that it does create black and white image, but at different location than the code suggest.

Author is picking the wp_upload_dir() function which return the latest upload path, however in wordpress all upload goes in folder hirerchy as YYYY/MM (Year/month). And if you are uploading in older post then WordPress will upload media for that post in month and year of that post’s publish date and not current year and date. What this does is that it broke the path of black and white image upload and hence imagefilter() php function start giving error. Solution was rather simple. I use $meta’s original upload file path, strip file name and put image path in same folder as original image.

The Next problem is that on HTML page it doesn’t pick the black and white image. Again the code forgot or miss to change the Thumbnail-bw path to it’s new file. Some commenter did mention it but I didn’t get their point until at the time of writting of this article. These two crucial things once fixed the code works just fine for me. So, nothing gets change except the BW_Filter function which I have given below. Rest of code is same as original post. [link above]

add_filter('wp_generate_attachment_metadata','bw_images_filter');
function bw_images_filter($meta) {	

	$file = wp_upload_dir();
	// Need to check to see if their was even a generated 'thumb-m' in case the image uploaded was the appropriate size
	// and therefore will be used in it's largest form
	if (isset($meta['sizes']['thumbnail-bw'])) {
		$tmpfile = trailingslashit($file['basedir']);
		$explodedPath = explode("/", $meta['file']);
		unset($explodedPath[count($explodedPath)-1]); //Remove file name from path
		$explodedPath = implode("/", $explodedPath);
		$file = $tmpfile.trailingslashit($explodedPath).$meta['sizes']['thumbnail-bw']['file'];
		
		$updateFileName = explode(".",$meta['sizes']['thumbnail-bw']['file']);
		$ext = $updateFileName[count($updateFileName)-1];
		unset ($updateFileName[count($updateFileName)-1]); //remove it for now.
		$updateFileName = implode(".", $updateFileName);
		$updateFileName = $updateFileName ."-bw.". $ext;
		$meta['sizes']['thumbnail-bw']['file'] = $updateFileName;
	// The thumbnail didn't get created because the uploaded image was the correct size before scaling / cropping.
	// Need to get base directory instead of path here because the original file already has the year/month structure in it's file attribute.
	} else {
		$file = trailingslashit($file['basedir']).$meta['file'];
		$explodedPath = explode("/", $meta['file']);
 
		// Manually insert the thumbnail-bw that didn't get created upon upload and append '-bw' to the filename
		$explodedFileName = explode(".", $exploded[2]);
		$updatedFileName = $explodedFileName[0] . '-bw.' . $explodedFileName[1];
		$meta['sizes']['thumbnail-bw']['file'] = $updatedFileName;		
	}
	
	$meta['sizes']['thumbnail-bw']['width'] = 421; // Set these dimensions to match the dimensions for the add_image_size above
	$meta['sizes']['thumbnail-bw']['height'] = 220;
	

	list($orig_w, $orig_h, $orig_type) = @getimagesize($file);
	$image = wp_load_image($file);
	imagefilter($image, IMG_FILTER_GRAYSCALE);
	//imagefilter($image, IMG_FILTER_GAUSSIAN_BLUR);
	switch ($orig_type) {
		case IMAGETYPE_GIF:
			$file = str_replace(".gif", "-bw.gif", $file);
			imagegif( $image, $file );
			break;
		case IMAGETYPE_PNG:
			$file = str_replace(".png", "-bw.png", $file);
			imagepng( $image, $file );
			break;
		case IMAGETYPE_JPEG:
			$file = str_replace(".jpg", "-bw.jpg", $file);
			imagejpeg( $image, $file );
			break;
	}
	
	
	return $meta;
}

Hope this code works for you. If not please share the fix and solution, I will try to keep it updates as I found better than this.