Take 2 on UTF8 BOM : Remove BOM with PHP

Some people asked me about my UTF8 BOM problems in PHP and XML. They were wondering if it was possible to remove the BOM from the files, without damaging them. And if PHP could do this. They had hundreds of files with UTF8 BOM in them and it would be time consuming to remove by hand, if they weren’t able to find a solution.

My answer was, “of course”. PHP can read and remove BOM from every file. As we encounter this problem only in text based files, a string remover will do the trick. Applause for substr().

I wrote a php based bom remover that works both from web and command line. You can download/fork the code from the github repository.

Please backup your files before running the script.

 

WordPress: How To Show The Featured Image Of Posts In Social Sharing Sites

We all see people sharing links with images attached to them, on Facebook and Friendfeed. Most other sharing sites also support adding an image to your shares automatically.

This is simply done by a meta link tag: <link rel="image_src" href="your_image_url" />

If your WordPress template supports featured images, it is relatively easy to add this meta tag. Open your template’s php file, which sends out the headers (meta tags, link tags, title, etc, everything between the <head> </head> tags). The file you’ll be changing most probably is named header.php. Some themes have headers in index.php. So check these two files out.

Add these three lines of codes inside the head tags:

<?php if ( is_single() and function_exists('has_post_thumbnail') and has_post_thumbnail($post->ID) ) : ?>
<link rel="image_src" href="<?php $thumb = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'medium'); echo $thumb[0]; ?>" />
<?php endif; ?>

If your image has a post thumbnail (featured image) attached to it, this code will create the link tag. Now when anybody shares this post on social sites, your post thumbnail will appear. You can change the size of the image to thumbnail, medium, large or full. But sharing sites most probably will resize it.

If your theme comes with other thumbnail sizes, you can find them in functions.php file of your theme. Look for a line starting with add_image_size() wp function, and you can find the name of the attachment.

But my theme does not support featured images?

Then you have two solutions for the problem. First, you can force your theme to support post thumbnails. You’ll be able to add an image to your posts, but you’ll not be able to see it when you publish the post. However, the attachment will be made, and link tag will be created for you.

To enable the thumbnail support, open your theme’s functions.php file, and add these lines at the beginning.

add_theme_support('post-thumbnails', array( 'post' ));
add_image_size('link-thumbnail', 200, 200, true)

Now you have thumbnail support. Plus, the second line adds a new kind of image size called “link-thumbnail” with size of 200px width and height, which you can use in the link tag creation. You can change the “true” part at the end, if you do not want to smart-crop your images.

Remember, you’ll also need to insert the first code I gave into your header.php (or again to index.php depending on your theme) file.

Don’t need thumbnail support, what is the second solution?

Well, you can check for images in the post content, and use the first image as a link tag. Again in the head section of your theme (either in your theme’s header.php or index.php as I mentioned earlier) you’ll need to add these lines of code:

<?php
if ( is_single() ) :
	$postimages = array();
 	preg_match_all('@<img.+src="(.*)".*>@Uims' , $post->post_content, $postimages);
	$image = end($postimages);
?>
<?php if($image): ?>
<link rel="image_src" href="<?php echo $image[0]; ?>" />
<?php endif;
endif;
?>

This will get the post’s attachments, and create the link tag from the first one.

An addition for those who have the post thumbnails support

You can also add the last code I gave here. Even if you did not attach any post thumbnails but included some images in your posts, your post will be shared with an image.

And the end…

It is possible to have more than one link image tag in your posts. You can alter the last code to include all your images (you might have seen how on Facebook some links come with more than one thumbnails while you are adding a link). To accomplish this, the last code I gave you becomes:

<?php
if ( is_single() ):
	$postimages = array();
 	preg_match_all('@<img.+src="(.*)".*>@Uims', $post->post_content, $postimages);
?>
<?php foreach($postimages[1] as $image): ?>
<link rel="image_src" href="<?php echo $image; ?>" />
<?php endforeach;
endif;
?>

After you arranged your files with the new code, try sharing one of your posts on Facebook, Friendfeed or some other site that supports images with links. If it is not working for you, you might be doing something wrong, leave a comment.

Have fun :)

WordPress: Include your featured post image in RSS feeds

If you want to see your featured post image in your feeds, and want them to appear when your share it in social sites, all you need is to include this code in your theme’s functions.php file:

// Featured image in RSS feeds
add_filter('the_excerpt_rss', 'eg_insertthumbnailrss');
add_filter('the_content_feed', 'eg_insertthumbnailrss');
function eg_insertthumbnailrss($content) {
   global $post;
   if ( has_post_thumbnail( $post->ID )) {
		$content = "

" . get_the_post_thumbnail ( $post->ID, 'thumbnail' ) . "


" . $content; } return $content; }

If your post has thumbnail pictures, they will appear on the top in paragraph tags. You can change how you want to see it, by manipulation the <code>$content</code> part in the <code>if ( has_post_thumbnail( $post->ID ))</code> statement.

You can also change which post image size you’d like to see. WordPress comes with three sizes by default, and one selection for the full image (thumbnail, medium, large or full). Your theme can also assign its own post thumbnail image sizes. Look for <code>add_image_size(‘post-image-name’);</code> line in your functions.php, and check the name, if you want to use your theme’s thumbnails.

Create sitemap.xml In WordPress Without Using Any Plugins

Everybody likes plugins, and most of them are really great (in case of WordPress). But some people like me, tend to do the work by themselves.

So, here is a simple code that will re-create a sitemap.xml file, everytime you publish a post or page. Copy the code and paste it to your theme’s functions.php file (wp-content/themes/your_theme_folder/functions.php).

add_action("publish_post", "eg_create_sitemap");
add_action("publish_page", "eg_create_sitemap");

function eg_create_sitemap() {
  $postsForSitemap = get_posts(array(
    'numberposts' => -1,
    'orderby' => 'modified',
    'post_type'  => array('post','page'),
    'order'    => 'DESC'
  ));

  $sitemap = '<?xml version="1.0" encoding="UTF-8"?>';
  $sitemap .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';

  foreach($postsForSitemap as $post) {
    setup_postdata($post);

    $postdate = explode(" ", $post->post_modified);

    $sitemap .= '<url>'.
      '<loc>'. get_permalink($post->ID) .'</loc>'.
      '<lastmod>'. $postdate[0] .'</lastmod>'.
      '<changefreq>monthly</changefreq>'.
    '</url>';
  }

  $sitemap .= '</urlset>';

  $fp = fopen(ABSPATH . "sitemap.xml", 'w');
  fwrite($fp, $sitemap);
  fclose($fp);
}

If you’ve got custom post types, you’ll need to add the registered taxonomy to ‘post_type’ array part of the code.

For a big blog with thousands of posts, creating a sitemap.xml file with every post publish action might not be a good solution, so keep that in mind.

Random Rotate Maxscript Version 1.1

The script rotates the selected meshes in any (or any combination of, or all) axis. Just enable one or more of the axises, adjust minimum, maximum values to your liking, press the random rotate button. Check out the gallery for how to install and run the script.

Download Random Rotate

You can use “random rotate” with my “random scale” script for more randomness.

Random Material Assigner for Objects with Multiple MaterialIDs

Works on one or multiple object selections. Script detects the materialID count and creates a multi-sub material(s) for the selected object(s), and changes the diffuse channel with a random color. If there is only one materialID on the object, script simply creates a standart material.

Download Random Material Assigner for Objects with MaterialID

As this is a macroscript, after running it, you need to add it to a quad menu, or an icon on a toolbar, or to a menu. Script’s category is “emrahgunduz.com”.

Keep these in mind

  • Created materials are named after the object’ own name.
  • Materials in the multi-sub object will be “Standard”.
  • Changes diffuse channel color with a random one.
  • Works only with poly, mesh or patch object. There is no nurbs or basic object support.

Randomly Delete Objects With Maxscript

The script randomly deletes meshes from the selection. As the script depends on the random numbers created by 3dsmax, the percentage can be %0-1 off what you expected. Just select the meshes you want to randomly delete. Enter a percentage, click the Delete button.

Download Random Delete

Random Color Maxscript

I hate how wire coloring (default color max assigns to objects when they first created) works in max. After working a few hours, all objects start to appear in lots of colors which really distract me. So, a few months back, I wrote a script to color them in gray. For sharing, I changed the script, added a gui and some improvements.

Download Random Color

This one can randomly color the selected objects in RGB, or simply red, green, blue or a color of gray. If you need to color every object for ObjectID in post processing, you might need something like this.

Random Face Deletion / Selection with Maxscript

For sometime now, some of my friends asked me to write a script for random face selection for poly objects. Here is a simple code for doing exactly what it’s asked for:

sel = selection as array
count = 1

undo on
(
	if sel.count > 0 then
	(
		while count <= sel.count do
		(
			select sel[count]
			count += 1
			
			facenumber = polyop.getNumFaces $
			randomset = #()
			for i=1 to facenumber do
			(
				rand = random 0 100
				if rand < 50 do append randomset i
			)
			
			polyop.deleteFaces $ randomset delIsoVerts:true
		)
	)
)
select sel

It is not hard to write a simple random face select/delete script. This script will go through every selected poly object, and randomly delete some of the faces. I did not add any error checking in this, so if you select any object that’s not a poly, you’ll get an error. You can also disable the viewport update and enable after the faces get deleted. This will make the script run faster on high-poly count objects.

If you are experiencing errors before script deletes any faces, change the random range's 0 to 1. For more randomness use a big number for the second part of the random statement. 100 seems OK. If you do not want to delete isolated vertices –vertices that do not belong to any faces-, just change delIsoVerts to false. For keeping the original object, just add an Edit Poly modifier and then run the script. By this way, removing the modifier might save you some production time.

Requested addition #1: And, this script will only randomly select faces, but not delete them :

sel = selection as array
count = 1

undo on
(
	if sel.count > 0 then
	(
		while count <= sel.count do
		(
			select sel[count]
			count += 1
			
			facenumber = polyop.getNumFaces $
			randomset = #()
			for i=1 to facenumber do
			(
				rand = random 0 100
				if rand < 50 do append randomset i
			)
			
			subobjectlevel = 4
			polyop.setFaceSelection $ randomset
		)
	)
)
select sel

Requested Addition #2: This one will assign a new material id that is not used on the mesh to the randomly selected polys.

sel = selection as array
count = 1
 
undo on
(
	if sel.count > 0 then
	(
		while count <= sel.count do
		(
			select sel[count]
			count += 1

			facenumber = polyop.getNumFaces $
			randomset = #()
			newID = 0
				for i=1 to facenumber do
				(
					if (polyop.getFaceMatID $ facenumber) > newID do newID = (polyop.getFaceMatID $ facenumber)+1
					rand = random 0 100
					if rand < 50 do append randomset i
				)

			polyop.setFaceMatID $ randomset newID
		)
	)
)
select sel

Make Unique (Deinstance) Maxscript

Here is a simple maxscript that works with instanced objects. While working with Maxwell, I always have problems with instanced light meshes. So, I thought writing a script for this job would be fine.

Download DeInstance

Just select some objects from the scene. Script checks every one of them, finds instances and makes them unique. As this is a macroscript, you need to add it to a quad menu, a toolbar or a menu. You can find the script in category “emrahgunduz.com”, named as “DeInstance”.