Created
February 13, 2012 23:34
-
-
Save rinatkhaziev/1821474 to your computer and use it in GitHub Desktop.
Google Custom Search Engine for WordPress (shortcode)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** Use it as [google-cse id="your-google-cse-id"] | |
* Might need a little tweaking | |
*/ | |
add_shortcode( 'google-cse', 'localtv_google_cse_shortcode' ); | |
function localtv_google_cse_shortcode( $atts ) { | |
extract( | |
shortcode_atts( | |
array( | |
'id' => '', | |
), $atts | |
) ); | |
$id = wp_filter_nohtml_kses( $id ); | |
if ( strlen( $id ) > 0 ): | |
?> | |
<div id="cse" style="width: 100%;">Loading</div> | |
<script src="http://www.google.com/jsapi" type="text/javascript"></script> | |
<script type="text/javascript"> | |
function parseQueryFromUrl () { | |
var queryParamName = "cse_q"; | |
var search = window.location.search.substr(1); | |
var parts = search.split('&'); | |
for (var i = 0; i < parts.length; i++) { | |
var keyvaluepair = parts[i].split('='); | |
if (decodeURIComponent(keyvaluepair[0]) == queryParamName) { | |
return decodeURIComponent(keyvaluepair[1].replace(/\+/g, ' ')); | |
} | |
} | |
return ''; | |
} | |
google.load('search', '1', {language : 'en'}); | |
google.setOnLoadCallback(function() { | |
var customSearchOptions = {}; | |
var customSearchControl = new google.search.CustomSearchControl( | |
'<?php echo esc_js($id) ?>', customSearchOptions); | |
customSearchControl.setResultSetSize(google.search.Search.FILTERED_CSE_RESULTSET); | |
var options = new google.search.DrawOptions(); | |
options.setAutoComplete(true); | |
customSearchControl.setAutoCompletionId('<?php echo esc_js($id) ?>+qptype:1'); | |
options.enableSearchResultsOnly(); | |
customSearchControl.draw('cse', options); | |
var queryFromUrl = parseQueryFromUrl(); | |
if (queryFromUrl) { | |
customSearchControl.execute(queryFromUrl); | |
} | |
}, true); | |
</script> | |
<?php | |
endif; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment