Developing a custom store locator map: Create a PHP file to output the XML

Welcome to the fourth post in our series on creating your own store locator map. In this post we are going to create an XML file which will process the calls to the database in a browser.

Copy and paste this code into a blank text file:

<?php
require("databaseconnect.php");

// Get parameters from URL
$center_lat = $_GET&#91;"lat"&#93;;
$center_lng = $_GET&#91;"lng"&#93;;
$radius = $_GET&#91;"radius"&#93;;

// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("Sheet1");
$parnode = $dom->appendChild($node);

// Opens a connection to a mySQL server
$connection=mysql_connect (localhost, $username, $password);
if (!$connection) {
  die("Not connected : " . mysql_error());
}

// Set the active mySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
  die ("Can\'t use db : " . mysql_error());
}

// Search the rows in the Sheet1 table
$query = sprintf("SELECT address, name, lat, lng, ( 3959 * acos( cos( radians('%s') ) * cos( radians( lat ) ) * cos( radians( lng ) - radians('%s') ) + sin( radians('%s') ) * sin( radians( lat ) ) ) ) AS distance FROM markers HAVING distance < '%s' ORDER BY distance LIMIT 0 , 20",
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($center_lng),
  mysql_real_escape_string($center_lat),
  mysql_real_escape_string($radius));
$result = mysql_query($query);

$result = mysql_query($query);
if (!$result) {
  die("Invalid query: " . mysql_error());
}

header("Content-type: text/xml");

// Iterate through the rows, adding XML nodes for each
while ($row = @mysql_fetch_assoc($result)){
  $node = $dom->createElement("Sheet1");
  $newnode = $parnode->appendChild($node);
  $newnode->setAttribute("name", $row['name']);
  $newnode->setAttribute("address", $row['address']);
  $newnode->setAttribute("lat", $row['lat']);
  $newnode->setAttribute("lng", $row['lng']);
  $newnode->setAttribute("distance", $row['distance']);
}

echo $dom->saveXML();
?>

Save it as getoutput.php.  Upload the file to your server. To make sure that the XML is outputting correctly, go to www.yourwebsite.com/getoutput.php?lat=37&lng=-122&radius=25. You should see output like this:

<?xml version="1.0"?>
<Sheet1><marker name="Location #1" address="Address 1" lat="37.402653" lng="-122.079353" distance="0.38091455044131"/>
<marker name="Location #2" address="Address 2" lat="37.393887" lng="-122.078918" distance="0.5596115438175"/>
<marker name="Location #3" address="Address 3" lat="37.387138" lng="-122.083237" distance="1.0796074495809"/>
...
</Sheet1>

Once we have the XML working in the browser, we are ready to move on to creating the actual map.

Here are links to all of the posts in this series on how to create your own store locator map:

 

Create a spreadsheet of your store locations

Create and populate the MySQL table

Create a PHP file which will be used to connect to the database

Create a PHP file which will output the XML file results of a search

Create the HTML page which contains the store locator map

 

 And here are some hints and tips to help create and customize your store locator map:

Using your own custom markers for the locations in place of Google’s default markers

How to prevent the map from zooming in to close on a single location

Developing a custom store locator map: Create a PHP file to connect to the database

This is the third post in my series on creating your own custom store locator map using Google maps, PHP, and XML. In this post we are going to create a simple PHP file which will be used to connect the store locator in our website to the database of store locations.

Select and copy this code:

<?
$username="YOUR DATABASE USERNAME";
$password="YOUR DATABASE PASSWORD";
$database="YOUR DATABASE NAME";
?>

Past the code into a blank text file. Simply replace the values in the code with the correct values to your database.

Save the file as databaseconnect.php or whatever you want to call it (as long as it has the .php extension). Upload the file to your server.

The next step in creating our own store locator is to create the XML file which will process the calls for store locations in a browser.

Here are links to all of the posts in this series on how to create your own store locator map:

 

Create a spreadsheet of your store locations

Create and populate the MySQL table

Create a PHP file which will be used to connect to the database

Create a PHP file which will output the XML file results of a search

Create the HTML page which contains the store locator map

 

 And here are some hints and tips to help create and customize your store locator map:

Using your own custom markers for the locations in place of Google’s default markers

How to prevent the map from zooming in to close on a single location

Developing a custom store locator map: Creating and populating the MySQL table

This is the second post in my series on how to create your store locator map using Google maps, PHP, and Javascript.

Now that we have our store locations in a usable format, we need to create the table on our website’s database and import the data for the locations.

Log into the phpMyAdmin account for your website. Create a new table – for this example, we will call the table Sheet1.

Add the columns to the table that you want to use in your store locator map, i.e.: store name, address, phone number, website address, longitude, and latitude. Make sure that you add columns for longitude and latitude – use float for the type and (10,6) for the length. These values will let the longitude and latitude fields store 6 digits after the decimal, plus up to 4 digits before the decimal.

Here is a screenshot of an example table (from http://code.google.com/apis/maps/articles/phpsqlsearch.html):

If you prefer to create the table by writing an SQL commands, use something like this:

CREATE TABLE `Sheet1` (
  `id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
  `name` VARCHAR( 60 ) NOT NULL ,
  `address` VARCHAR( 80 ) NOT NULL ,
 `phone` VARCHAR( 80 ) NOT NULL ,
`website` VARCHAR( 80 ) NOT NULL ,
  `lat` FLOAT( 10, 6 ) NOT NULL ,
  `lng` FLOAT( 10, 6 ) NOT NULL
) ENGINE = MYISAM ;

 

Once you have the table and the columns you want created, it is time to import your locations. Import the csv or xls file that we created in our last post. Now all of your store locations should be stored in your site’s database.

The next step will be creating a PHP page which will be used to connect the store locator on our website to the database of locations that we just created.

Here are links to all of the posts in this series on how to create your own store locator map:

 

Create a spreadsheet of your store locations

Create and populate the MySQL table

Create a PHP file which will be used to connect to the database

Create a PHP file which will output the XML file results of a search

Create the HTML page which contains the store locator map

 

 And here are some hints and tips to help create and customize your store locator map:

Using your own custom markers for the locations in place of Google’s default markers

How to prevent the map from zooming in to close on a single location

Developing a custom store locator map: Create a spreadsheet of your locations

This is the first post in my series covering how to develop your own store locator by integrating Google maps into your website with PHP and Javascript. In this post we will cover how to create a spreadsheet of your store locations.

You can use either a CSV file or an XLS file to compile your store locations.

One of the most important things you need is the latitude and longitude for each location. The easiest way that I found to get these values, is by using http://www.gpsvisualizer.com/geocoder/.

Simply copy and paste or type each of your locations into the “Input” box (one location per line), and then click the “Start geocoding” button.

Your locations along with the longitude and latitude for each one will be displayed in the box under the map of your locations. Highlight and copy the results once all of the locations have been processed and paste them into a new text file (I prefer to use Notepad if I am on a PC and TextEdit if I am on a Mac). Save the file as locations.csv (or any name that you want to use, as long as it has the extention .csv).

Now, create a new Google spreadsheet at https://docs.google.com/. Go to File -> Import and import the locations.csv file that you just created.

Once you have your new spreadsheet populated and all of the fields that you want for your store locator map created (location name, address, website, phone number, etc.), go to File -> Download As -> Excel. This will download a file called locations.xls to your computer.

You are now ready to move on to the next step, which is Creating and populating the MySQL table.

Here are links to all of the posts in this series on how to create your own store locator map:

 

Create a spreadsheet of your store locations

Create and populate the MySQL table

Create a PHP file which will be used to connect to the database

Create a PHP file which will output the XML file results of a search

Create the HTML page which contains the store locator map

 

 And here are some hints and tips to help create and customize your store locator map:

Using your own custom markers for the locations in place of Google’s default markers

How to prevent the map from zooming in to close on a single location

Creating a custom Twitter feed of search results for a specific term

Here are the codes you need to create a custom Twitter feed that displays search results for a specific term or user.

First, let’s create the Javascript file that makes it all work.

Copy and paste this code into your favorite text editor:

$(document).ready(function() {
    // json call to twitter to request tweets containing our keyword, in this case 

'thelibzter'
    $.getJSON("http://search.twitter.com/search.json?q=<span style="color: #ff0000;">thelibzter</span>&callback=?", function(data) 

{
        // loop around the result
        $.each(data.results, function() {
            var text = this.text;
    
            if(text.charAt(0) != '@') {
                // construct tweet and add append to our #tweets div
                var tweet = $("<div></div>").addClass('tweet').html(text);
                // analyse our tweet text and turn urls into working links, hash 

tags into search links, and @replies into profile links.
                tweet.html('<div>' +
                    tweet.html()
                    .replace(/((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:

[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi,'<a href="$1">$1</a>')
                    .replace(/(^|\s)#(\w+)/g,'$1<a 

href="http://search.twitter.com/search?q=%23$2">#$2</a>')
                    .replace(/(^|\s)@(\w+)/g,'$1<a href="http://twitter.com/

$2">@$2</a>')
                    + '<br /><a href="http://www.twitter.com/' + 

this.from_user + '/status/' + this.id_str + '" target="_blank">' + $.timeSinceTweet

(this.created_at) + '</a></div>'
                    )
                    .prepend('<a href="http://www.twitter.com/' + 

this.from_user + '" target="_blank"><img src="' + this.profile_image_url + '" width="48" 

height="48" /></a>')
                    .appendTo('#tweets')
                    .fadeIn();
            }
        });
    });
});

(function($) {
    $.timeSinceTweet = function(time) {
        var date = new Date(time);
        var diff = ((new Date()).getTime() - date.getTime()) / 1000;
        var day_diff = Math.floor(diff / 86400);
        
        if (day_diff < 0 || day_diff >= 31 || isNaN(day_diff)) {
            return "View tweet";
        }
        
        if(day_diff == 0) {
            if(diff < 60) {
                return Math.ceil(diff) + " seconds ago";
            }
            else if(diff < 120) {
                return "1 minute ago";
            }
            else if(diff < 3600) {
                return Math.floor( diff / 60 ) + " minutes ago";
            }
            else if(diff < 7200) {
                return "1 hour ago";
            }
            else if(diff < 86400) {
                return Math.floor( diff / 3600 ) + " hours ago";
            }
        }
        
        if(day_diff == 1) {
            return "Yesterday";
        }
        else if(day_diff < 7) {
            return day_diff + " days ago";
        }
        else if(day_diff < 31) {
            return Math.ceil( day_diff / 7 ) + " weeks ago";
        }
        else {
            return "View Tweet";
        }    
    }
})(jQuery);&#91;/code&#93;
&nbsp;

You will want to change the words highlighted in red above (thelibzter) to whatever search term you want to use.

Save the file as <strong>main.js</strong> and upload it to your server.

Now, add this line of code to the <head> section of your website:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script type="text/javascript" src="main.js"></script>

Make sure that the path to main.js is correct.

You will want to style the Twitter feed to match the design of your web page. Add this code to your stylesheet and feel free to edit it to make the Twitter display the way you want:

#container { width: 500px; margin: 0 auto; } 
#tweets .tweet {
  padding: 10px 20px;
  font-size: 15px;
  position: relative;
  border-bottom: 1px dashed #ededed;
  overflow: hidden;
}
#tweets .tweet img { margin-right: 12px; float: left; }
#tweets .tweet .content { width: 400px; float:  left; }
#tweets .tweet .content a.view { font-size: 10px; }

Now, simply add this code to your web page wherever you want the Twitter feed to appear:

<div id="container">
  <h1>Search results for "TheLibzter"</h1>
  <div id="tweets"></div>
</div>

And that's it! Let me know if you run into any issues or have any questions.

You can find instructions and codes to use to create your own custom Twitter feed here - creating a custom Twitter widget for your website.

You can also find several custom Twitter feeds that I designed and are available for you to use here - custom Twitter feeds for your website.

WordPress: How to change the length of blog post excerpts

Here is the line of code that I use to change the default length (55 words) of excerpts in WordPress.

Copy and paste this snippet into your functions.php file:

function new_excerpt_length($length) {
	return 20;
}
add_filter('excerpt_length', 'new_excerpt_length');

Simply change the number “20” in the example above to the number of words that you want to display in excerpts.

As always, just let me know if you run into any issues at all.

WordPress: How to show a different number of posts on different pages

Here is the line of code that I use to control the number of posts on particular pages in a WordPress site.

Note: the website that this code was written for is set up to display different categories of posts on different pages.

Copy this line of code:

<?php if(is_category('3')) { query_posts('cat=3&posts_per_page=3&paged='.$paged);
} else if(is_category('5')) { query_posts('cat=5&posts_per_page=8&paged='.$paged);
} else if(is_category('6')) { query_posts('cat=6&posts_per_page=10&paged='.$paged);
} else if(is_category('7')) { query_posts('cat=7&posts_per_page=5&paged='.$paged);
} else if(is_category('4')) { query_posts('cat=4&posts_per_page=13&paged='.$paged);
} else if(is_category('1')) { query_posts('cat=1&posts_per_page=1&paged='.$paged);
}
$paged = ( get_query_var('paged') && get_query_var('paged') > 1 ) ? get_query_var('paged') : 1;
?>

And paste it into your page.php template, just before the loop is called.

Then just edit the category IDs and the number of posts you want to display on each page.

This code worked perfectly for me but, as always, just let me know if you run into any issues!

WordPress: Manually control which blog pages show excerpts and which show full posts

Here is how to manually control which blog pages on your WordPress site display posts as excerpts and which show the entire posts.

For the site that I developed this solution for, the pages are set up to display posts from a particular category on each particular page.

First, open the loop-page.php file in your WordPress admin panel.

Between the two tags:

and , paste this code:

<?php if ( is_category(3) ) { ?>
<?php the_content(); ?>

<?php } else { ?>
<?php the_excerpt(); ?>

<?php } ?>

In this example, we are telling WordPress that if the page is displaying posts from category ID 3, show the entire post. Otherwise, on all other pages, show the exerpts of posts.

Of course, you will want to edit to whatever category ID or page ID (using ) or post ID (using ) that you are trying to control.

If you want to control the excerpts and/or full posts on multiple pages or posts or categories, you would use this line at the beginning of the previous code:

<?php if ( is_category(array(3,5)) ) { ?>

Let me know if you have any questions or trouble with this!

WordPress: Display latest posts from a particular category in the sidebars of specific pages

After spending hours trying to figure out a way to display the latest posts from a certain category in WordPress on specific pages, I have finally found a solution!

First of all, it is important to note that the site I am working on is set up to display only posts from a particular category on specific pages.

The first thing I did was install the Exec-PHP plugin (which allows you to add php code to your sidebar widgets) and the Widget Logic plugin (which allows you to control which widgets show up on which pages’ sidebars).

Next, I added a “text” widget to my sidebar. I named the widget “Latest posts in Video.”

Then I pasted this code into the text area of the widget:

<?php
 global $cat;
 $recentPosts = new WP_Query();
 $recentPosts->query('showposts=5&cat=7');
?>
<?php while ($recentPosts->have_posts()) : $recentPosts->the_post(); ?>
 <li><a href="<?php the_permalink() ?>" rel="bookmark"><?php the_title(); ?></a></li>
<?php endwhile; ?>

I changed the category ID (in this case: “7”) to the category ID that I wanted to display on the Video page.

Next, in the Widget Logic field of the widget, I used this line of code to tell the widget which page to appear on:

is_category(7)

That is where I had been going wrong. I had been using is_page(26) (which is the page ID where I have Video posts being displayed), but WordPress sees that page as a category page and not as a page page (because of the fact that I had it set up to show only a certain category of posts), so once I changed the Widget Logic code to is_category, rather than is_page, my solution worked perfectly.

As always, let me know if you have any questions or issues with this, I would be happy to help.

WordPress Tricks: Disable the parent links in a navigation menu

Here is the line of code I use to disable the top, or parent, links in a navigation menu in a WordPress site.

Insert this line of code into your header.php file, right before the closing tag:

<script type="text/javascript">jQuery(function($) {    $("li.page-item-7").children("a").attr('href', "javascript:void(0)");});</script>

Now, simply change the page-item-7 to the ID of the page that you wish to disable. If you want to disable more than one of the parent menu items, use this code:

<script type="text/javascript">
jQuery(function($) {
$("li.page-item-7,li.page-item-14,li.page-item-20,li.page-item-28").children("a").attr('href', "javascript:void(0)");
});
</script>

Let me know if you run into any issues or have any questions at all.