Skip to content

Instantly share code, notes, and snippets.

@contempoinc
Created February 16, 2018 17:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save contempoinc/2322e43786a9589bf1bde470ce50b2fc to your computer and use it in GitHub Desktop.
Save contempoinc/2322e43786a9589bf1bde470ce50b2fc to your computer and use it in GitHub Desktop.
<?php
/**
* Theme Functions
*
* @package WP Pro Real Estate 6
* @subpackage Admin
*/
if (is_admin() && isset($_GET['activated'] ) && $pagenow == "themes.php" ) {
/* Call action that sets */
add_action('admin_head','ct_option_setup');
/* Do redirect */
header( 'Location: '.admin_url().'themes.php?page=optionsframework' ) ;
}
/*-----------------------------------------------------------------------------------*/
/* Body IDs */
/*-----------------------------------------------------------------------------------*/
function ct_body_id() {
if (is_home()) {
echo ' id="home"';
} elseif (is_single()) {
echo ' id="single"';
} elseif (is_page()) {
echo ' id="page"';
} elseif (is_search()) {
echo ' id="search"';
} elseif (is_archive()) {
echo ' id="archive"';
}
}
/*-----------------------------------------------------------------------------------*/
/* SEO Friendly Title Tags */
/*-----------------------------------------------------------------------------------*/
function ct_title() {
if (is_category()) {
echo wp_title(''); echo ' - ';
} elseif (function_exists('is_tag') && is_tag()) {
single_tag_title('Tag Archive for &quot;'); echo '&quot; - ';
} elseif (is_archive()) {
wp_title(''); echo ' Archive - ';
} elseif (is_page()) {
echo wp_title(''); echo ' - ';
} elseif (is_search()) {
echo 'Search for &quot;'.esc_html($s).'&quot; - ';
} elseif (!(is_404()) && (is_single()) || (is_page())) {
wp_title(''); echo ' - ';
} elseif (is_404()) {
echo 'Not Found - ';
} bloginfo('name');
}
/*-----------------------------------------------------------------------------------*/
/* Add Editor Stylesheet Support */
/*-----------------------------------------------------------------------------------*/
if ( function_exists('add_editor_style') ) {
add_editor_style();
}
/*-----------------------------------------------------------------------------------*/
/* Add Post Thumbnail Support */
/*-----------------------------------------------------------------------------------*/
add_theme_support('post-thumbnails');
/*-----------------------------------------------------------------------------------*/
/* Set Content Width */
/*-----------------------------------------------------------------------------------*/
if(!isset($content_width)) $content_width = 940;
/*-----------------------------------------------------------------------------------*/
/* Add WordPress 3.0 Menu Support */
/*-----------------------------------------------------------------------------------*/
if (function_exists('register_nav_menu')) {
register_nav_menus( array( 'primary' => __( 'Primary Menu', 'contempo' ) ) );
register_nav_menus( array( 'footer' => __( 'Footer Menu', 'contempo' ) ) );
}
function ct_nav() { ?>
<nav class="right">
<?php wp_nav_menu( array( 'container_id' => 'nav', 'menu_class' => 'cbp-tm-menu', 'menu_id' => 'cbp-tm-menu', 'theme_location' => 'primary', 'fallback_cb' => false) ); ?>
</nav>
<?php }
function ct_footer_nav() { ?>
<nav class="left">
<?php wp_nav_menu( array( 'container_id' => 'footer-nav', 'theme_location' => 'footer', 'fallback_cb' => false) ); ?>
</nav>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Screenr oEmbed Support
/*-----------------------------------------------------------------------------------*/
wp_oembed_add_provider('#http://(www\.)?screenr\.com/.*#i', 'http://www.screenr.com/api/oembed.json', true);
/*-----------------------------------------------------------------------------------*/
/* Enqueue main stylesheet
/*-----------------------------------------------------------------------------------*/
function ct_theme_style() {
wp_enqueue_style( 'ct-theme-style', get_bloginfo( 'stylesheet_url' ), array(), '1.0' );
}
add_action( 'wp_enqueue_scripts', 'ct_theme_style' );
/*-----------------------------------------------------------------------------------*/
/* Register Scripts and CSS */
/*-----------------------------------------------------------------------------------*/
function ct_register_cssjs() {
wp_register_script('transit', get_template_directory_uri() . '/js/jquery.transit.min.js', 'jquery', '1.0', false);
wp_register_script('gallery', get_template_directory_uri() . '/js/ct.gallery.js', 'jquery', '1.0', false);
wp_register_script('customSelect', get_template_directory_uri() . '/js/jquery.customSelect.min.js', 'jquery', '1.0', false);
wp_register_script('ctSelect', get_template_directory_uri() . '/js/ct.select.js', 'jquery', '1.0', false);
wp_register_script('tooltipMenu', get_template_directory_uri() . '/js/ct.tooltipmenu.min.js', 'jquery', '1.0', false);
wp_register_script('backstretch', get_template_directory_uri() . '/js/jquery.backstretch.min.js', 'jquery', '1.0', false);
wp_register_script('easing', get_template_directory_uri() . '/js/jquery.easing.1.3.js', 'jquery', '1.0', false);
wp_register_script('bxSlider', get_template_directory_uri() . '/js/jquery.bxslider.min.js', 'jquery', '1.0', false);
wp_register_script('validationEngine', get_template_directory_uri() . '/js/jquery.validationEngine.js', 'jquery', '1.0', true);
wp_register_script('flexslider', get_template_directory_uri() . '/js/jquery.flexslider-min.js', 'jquery', '1.0', true);
wp_register_script('retina', get_template_directory_uri() . '/js/retina.js', 'jquery', '1.0', true);
wp_register_script('cycle', get_template_directory_uri() . '/js/jquery.cycle.lite.js', 'jquery', '1.0', true);
wp_register_script('mobileMenu', get_template_directory_uri() . '/js/ct.mobile.menu.js', 'jquery', '1.0', true);
wp_register_script('prettyPhoto', get_template_directory_uri() . '/js/jquery.prettyPhoto.js', 'jquery', '1.0', true);
wp_register_script('fitvids', get_template_directory_uri() . '/js/jquery.fitvids.js', 'jquery', '1.0'å, true);
wp_register_script('gmaps', '/å/maps.google.com/maps/api/js?v=3.22', '', '1.0', false);
wp_register_script('marker', get_template_directory_uri() . '/js/markerwithlabel.js', 'gmaps', '1.0', true);
wp_register_script('infobubble', get_template_directory_uri() . '/js/infobubble.js', 'gmaps', '1.0', true);
wp_register_script('geocode', get_template_directory_uri() . '/js/ct.geocode.markers.js', 'gmaps', '1.0', true);
wp_register_script('mapping', get_template_directory_uri() . '/js/mapping.js', 'gmaps', '1.0', true);
wp_register_script('foresight', get_template_directory_uri() . '/js/foresight.min.js', 'jquery', '1.0', true);
wp_register_script('touchEffects', get_template_directory_uri() . '/js/toucheffects.js', 'jquery', '1.0', true);
wp_register_script('modernizer', get_template_directory_uri() . '/js/modernizr.custom.js', 'jquery', '1.0', true);
wp_register_script('classie', get_template_directory_uri() . '/js/classie.js', 'jquery', '1.0', true);
wp_register_script('hammer', get_template_directory_uri() . '/js/jquery.hammer.min.js', 'jquery', '1.0', true);
wp_register_script('shiv', 'http://html5shiv.googlecode.com/svn/trunk/html5.js', 'jquery', '1.0', true);
wp_register_script('base', get_template_directory_uri() . '/js/base.js', 'jquery', '1.0', true);
wp_register_style('base', get_template_directory_uri() . '/css/base.css', '', '', 'screen, projection');
wp_register_style('framework', get_template_directory_uri() . '/css/responsive-gs-12col.css', '', '', 'screen, projection');
wp_register_style('ie', get_template_directory_uri() . '/css/ie.css', '', '', 'screen, projection');
wp_register_style('layout', get_template_directory_uri() . '/css/layout.css', '', '', 'screen, projection');
wp_register_style('dropdowns', get_template_directory_uri() . '/css/ct-dropdowns.css', '', '', 'screen, projection');
wp_register_style('comments', get_template_directory_uri() . '/css/comments.css', '', '', 'screen, projection');
wp_register_style('validationEngine', get_template_directory_uri() . '/css/validationEngine.jquery.css', '', '', 'screen, projection');
wp_register_style('flexslider', get_template_directory_uri() . '/css/flexslider.css', '', '', 'screen, projection');
wp_register_style('flexsliderNav', get_template_directory_uri() . '/css/flexslider-direction-nav.css', '', '', 'screen, projection');
wp_register_style('prettyPhoto', get_template_directory_uri() . '/css/prettyPhoto.css', '', '', 'screen, projection');
wp_register_style('shortcodes', get_template_directory_uri() . '/admin/shortcodes/css/shortcodes.css', '', '', 'screen, projection');
wp_register_style('pageBuilder', get_template_directory_uri() . '/css/page-builder-blocks.css', '', '', 'screen, projection');
wp_register_style('fontawesome', get_template_directory_uri() . '/css/font-awesome.css', '', '', 'screen, projection');
wp_register_style('animate', get_template_directory_uri() . '/css/animate.min.css', '', '', 'screen, projection');
wp_register_style('bxSlider', get_template_directory_uri() . '/css/jquery.bxslider.css', '', '', 'screen, projection');
wp_register_style('dsidxpress', get_template_directory_uri() . '/css/dsidxpress.css', '', '', 'screen, projection');
wp_register_style('print', get_template_directory_uri() . '/css/listing-print.css', '', '', 'print');
wp_register_style( 'ct-theme-style', get_bloginfo( 'stylesheet_url' ), array(), '1.0' );
}
add_action('wp_enqueue_scripts', 'ct_register_cssjs');
function ct_init_scripts() {
global $ct_options;
// Enqueue Styles
wp_enqueue_style('base');
wp_enqueue_style('framework');
wp_enqueue_style('ie');
wp_enqueue_style('layout');
wp_enqueue_style('dropdowns');
wp_enqueue_style('prettyPhoto');
wp_enqueue_style('flexslider');
wp_enqueue_style('shortcodes');
wp_enqueue_style('pageBuilder');
wp_enqueue_style('fontawesome');
wp_enqueue_style('portCaptions');
wp_enqueue_style('flexsliderNav');
wp_enqueue_style('animate');
wp_enqueue_style('homeSlider');
wp_enqueue_style('megaSettings');
wp_enqueue_style('ctPortfolio');
wp_enqueue_style('wooCommerce');
wp_enqueue_style('bxSlider');
wp_enqueue_style('dsidxpress');
wp_enqueue_style('print');
if(is_single() || is_page()) {
wp_enqueue_style('comments');
}
if(is_page_template('template-contact.php') || is_front_page()) {
wp_enqueue_style('validationEngine');
}
wp_enqueue_style('ct-theme-style');
// Enqueue Scripts
wp_enqueue_script('prettyPhoto');
wp_enqueue_script('retina');
if($ct_options['ct_mode'] != "Single Listing") {
wp_enqueue_script('tooltipMenu');
}
wp_reset_query();
if(!is_page_template('template-dsidxpress.php')) {
wp_enqueue_script('customSelect');
wp_enqueue_script('ctSelect');
}
wp_enqueue_script('fitvids');
wp_enqueue_script('nav');
wp_enqueue_script('foresight');
wp_enqueue_script('mobileMenu');
wp_enqueue_script('cycle');
wp_enqueue_script('flexslider');
wp_enqueue_script('gmaps');
wp_enqueue_script('infobubble');
wp_enqueue_script('marker');
wp_enqueue_script('mapping');
wp_enqueue_script('modernizer');
wp_enqueue_script('classie');
wp_enqueue_script('hammer');
wp_enqueue_script('homeSlider');
wp_enqueue_script('touchEffects');
wp_enqueue_script('transit');
wp_enqueue_script('base');
if(is_single() || is_page()) {
wp_enqueue_script('comment-reply');
}
if(is_single()) {
wp_enqueue_script('backstretch');
}
if(is_single() || is_page_template('template-contact.php') || is_page_template('template-submit-listing.php') || is_front_page()) {
wp_enqueue_script('validationEngine');
}
}
add_action('wp_enqueue_scripts', 'ct_init_scripts');
/*-----------------------------------------------------------------------------------*/
/* CT Head */
/*-----------------------------------------------------------------------------------*/
function ct_wp_head() {
/* Load Theme Options */
global $ct_options; ?>
<!--[if lt IE 9]>
<script src="<?php echo get_template_directory_uri(); ?>/js/respond.min.js"></script>
<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<script>
jQuery(window).load(function() {
<?php if($ct_options['ct_mode'] != "Single Listing") { ?>
var menu = new cbpTooltipMenu( document.getElementById( 'cbp-tm-menu' ) );
<?php } ?>
<?php if(!is_singular('listings')) { ?>
// Slider
jQuery('.flexslider').flexslider({
animation: "<?php echo strtolower($ct_options['ct_flex_animation']); ?>",
slideDirection: "<?php echo strtolower($ct_options['ct_flex_direction']); ?>",
slideshow: true,
slideshowSpeed: <?php echo $ct_options['ct_flex_speed']; ?>,
animationDuration: <?php echo $ct_options['ct_flex_duration']; ?>,
controlNav: false,
directionNav: true,
keyboardNav: true,
randomize: <?php echo strtolower($ct_options['ct_flex_randomize']); ?>,
pauseOnAction: true,
pauseOnHover: false,
animationLoop: true
});
<?php } ?>
});
</script>
<?php if(is_page_template('template-contact.php')) { ?>
<script>
jQuery(document).ready(function() {
jQuery("#contactform").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "<?php echo get_template_directory_uri(); ?>/includes/ajax-submit-contact.php",
ajaxSubmitMessage: "<?php $contact_success = str_replace(array("\r\n", "\r", "\n"), " ", $ct_options['ct_contact_success']); _e($contact_success,'contempo'); ?>",
success : false,
failure : function() {}
})
});
</script>
<?php } ?>
<?php if(is_singular('listings')) { ?>
<script>
jQuery(window).load(function() {
jQuery('#carousel').flexslider({
animation: "slide",
controlNav: false,
animateHeight: true,
directionNav: true,
animationLoop: false,
slideshow: true,
slideshowSpeed: <?php echo $ct_options['ct_flex_speed']; ?>,
animationDuration: <?php echo $ct_options['ct_flex_duration']; ?>,
itemWidth: 120,
itemMargin: 0,
asNavFor: '#slider'
});
jQuery('#slider').flexslider({
animation: "slide",
<?php
$smooth = $ct_options['ct_enable_smootheight'];
if($smooth == 'Yes') {
echo 'smoothHeight: true,';
}
?>
controlNav: false,
animationLoop: false,
slideshow: false,
sync: "#carousel"
});
});
jQuery(document).ready(function() {
jQuery("#listingscontact").validationEngine({
ajaxSubmit: true,
ajaxSubmitFile: "<?php echo get_template_directory_uri(); ?>/includes/ajax-submit-listings.php",
ajaxSubmitMessage: "<?php $contact_success = str_replace(array("\r\n", "\r", "\n"), " ", $ct_options['ct_contact_success']); echo $contact_success; ?>",
success : false,
failure : function() {}
})
});
</script>
<?php } ?>
<?php
/* Inject Custom Google Fonts */
$ct_heading_font = isset( $instance['ct_heading_font'] ) ? esc_attr( $instance['ct_heading_font'] ) : '';
$ct_body_font = isset( $instance['ct_body_font'] ) ? esc_attr( $instance['ct_body_font'] ) : '';
$ct_heading_font = str_replace(' ','+',$ct_options['ct_heading_font']);
$ct_body_font = str_replace(' ','+',$ct_options['ct_body_font']);
?>
<link href='//fonts.googleapis.com/css?family=<?php echo $ct_heading_font; ?>:300,400,700' rel='stylesheet' type='text/css'>
<link href='//fonts.googleapis.com/css?family=<?php echo $ct_body_font; ?>:300,400,700' rel='stylesheet' type='text/css'>
<style type="text/css">
h1, h2, h3, h4, h5, h6 { font-family: '<?php echo $ct_options['ct_heading_font']; ?>' !important;}
body, .slider-wrap { font-family: '<?php echo $ct_options['ct_body_font']; ?>' !important;}
<?php if($ct_options['ct_mode'] == "Single Listing") { ?>
#topbar-wrap { border-bottom: none;}
<?php } ?>
</style>
<?php
/* Inject Custom Stylesheet */
if($ct_options['ct_use_styles'] == "Yes") {
include(TEMPLATEPATH . '/includes/custom-stylesheet.php');
}
if (Browser::isSafari()) { ?>
<link href="<?php echo get_template_directory_uri(); ?>/css/safari.css" rel="stylesheet" type="text/css" />
<?php }
if($ct_options['ct_boxed'] == "Boxed") {
echo '<style type="text/css">';
echo 'body { background-color: #ececec;} #wrapper { background: #fff;} .container { padding: 0 20px;} #top #top-inner { width: 1020px;} footer { padding-left: 0; padding-right: 0;}';
echo '</style>';
}
/* Date format */
$GLOBALS['ctdate'] = get_option('ct_dateformat');
if ( $GLOBALS['ctdate'] == "" )
$GLOBALS['ctdate'] = "M j, Y";
}
/*-----------------------------------------------------------------------------------*/
/* Get translated slugs for WPML */
/*-----------------------------------------------------------------------------------*/
function get_taxo_translated() {
$get_term = get_term_by( 'name', 'featured', 'ct_status' );
$get_term_id = icl_object_id( $get_term->term_id, 'ct_status', ICL_LANGUAGE_CODE );
return get_term_by( 'id', $get_term_id, 'ct_status' )->name;
}
/*-----------------------------------------------------------------------------------*/
/* Count Posts in WPML */
/*-----------------------------------------------------------------------------------*/
include_once( ABSPATH . 'wp-admin/includes/plugin.php' );
if(is_plugin_active('sitepress-multilingual-cms/sitepress.php')) {
function count_posts($language_code = '', $post_type = 'post', $post_status = 'publish'){
global $sitepress, $wpdb;
//get default language code
$default_language_code = $sitepress->get_default_language();
//adjust post type to format WPML uses
switch($post_type){
case 'page':
$post_type = 'post_page';
break;
case 'post':
$post_type = 'post_post';
break;
}
//are we dealing with originals or translations?
$slc_param = $sitepress->get_default_language() == $language_code ? "IS NULL" : "= '{$default_language_code}'";
echo $query = "SELECT COUNT( {$wpdb->prefix}posts.ID )
FROM {$wpdb->prefix}posts
LEFT JOIN {$wpdb->prefix}icl_translations ON {$wpdb->prefix}posts.ID = {$wpdb->prefix}icl_translations.element_id
WHERE {$wpdb->prefix}icl_translations.language_code = '{$language_code}'
AND {$wpdb->prefix}icl_translations.source_language_code $slc_param
AND {$wpdb->prefix}icl_translations.element_type = '{$post_type}'
AND {$wpdb->prefix}posts.post_status = '$post_status'";
return $wpdb->get_var( $query );
}
}
/*-----------------------------------------------------------------------------------*/
/* Get Current Page */
/*-----------------------------------------------------------------------------------*/
function currentPage(){
global $page;
return $page ? $page : 1;
}
/*-----------------------------------------------------------------------------------*/
/* Sort By Price */
/*-----------------------------------------------------------------------------------*/
function sort_by_price() {
$extraVars = "";
foreach($_GET AS $key=>$value) {
$extraVars .= '<input type="hidden" name="'.$key.'" value="'.$value.'" />';
} ?>
<form action="<?php get_site_url(); ?>" name="order "class="formsrch" method="get">
<?php echo $extraVars;?>
<select class="ct_orderby_price" id="ct_orderby_price" name="ct_orderby_price">
<option value=""><?php _e('Sort By', 'contempo'); ?></option>
<option value="DESC" <?php if($_GET['ct_orderby_price'] == 'DESC'){ ?> selected="selected" <?php } ?>><?php _e('Price - Highest', 'contempo'); ?></option>
<option value="ASC" <?php if($_GET['ct_orderby_price'] == 'ASC'){ ?> selected="selected" <?php } ?>><?php _e('Price - Lowest', 'contempo'); ?></option>
</select>
</form>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Geocode Address */
/*-----------------------------------------------------------------------------------*/
if($ct_options['ct_listing_lat_long'] != "Off") {
function ct_geocode_address($post_id) {
if($_POST['post_type'] != 'listings')
return;
$city = wp_get_post_terms($post_id, 'city');
$city = $city[0];
$city = $city->name;
$state = wp_get_post_terms($post_id, 'state');
$state = $state[0];
$state = $state->name;
$zip = wp_get_post_terms($post_id, 'zipcode');
$zip = $zip[0];
$zip = $zip->name;
$street = get_the_title($post_id);
if($street && $city) {
$url = "//maps.googleapis.com/maps/api/geocode/json?address=".urlencode($street.' '.$city.', '.$state.' '.$zip)."&sensor=false";
$resp = wp_remote_get($url);
if ( 200 == $resp['response']['code'] ) {
$body = $resp['body'];
$data = json_decode($body);
if($data->status=="OK"){
$latitude = $data->results[0]->geometry->location->lat;
$longitude = $data->results[0]->geometry->location->lng;
update_post_meta($post_id, "_ct_latlng", $latitude.','.$longitude);
}
}
}
}
add_action('save_post', 'ct_geocode_address', 999);
}
/*-----------------------------------------------------------------------------------*/
/* Contact Us Map */
/*-----------------------------------------------------------------------------------*/
function contact_us_map() {
global $ct_options;
if($ct_options['ct_contact_map'] =="Yes") { ?>
<script>
function setMapAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { address : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
var location = results[0].geometry.location;
var options = {
zoom: 15,
center: location,
mapTypeId: google.maps.MapTypeId.<?php echo strtoupper($ct_options['ct_contact_map_type']); ?>,
streetViewControl: true,
scrollwheel: false,
draggable: false
};
var mymap = new google.maps.Map( document.getElementById( 'map' ), options );
var marker = new google.maps.Marker({
map: mymap,
flat: true,
icon: '<?php echo get_template_directory_uri(); ?>/images/map-pin-res.png',
position: results[0].geometry.location
});
}
});
}
setMapAddress( "<?php echo $ct_options['ct_contact_map_location']; ?>" );
</script>
<div id="location" class="marB18">
<div id="map" style="height: 300px;"></div>
</div>
<?php }
}
function listing_map() {
global $ct_options;
?>
<script>
function setMapAddress(address) {
var geocoder = new google.maps.Geocoder();
geocoder.geocode( { address : address }, function( results, status ) {
if( status == google.maps.GeocoderStatus.OK ) {
<?php if((get_post_meta(get_the_ID(), "_ct_latlng", true))) { ?>
var location = new google.maps.LatLng(<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>);
<?php } else { ?>
var location = results[0].geometry.location;
<?php } ?>
var options = {
zoom: 15,
center: location,
scrollwheel: false,
mapTypeId: google.maps.MapTypeId.<?php echo strtoupper($ct_options['ct_contact_map_type']); ?>,
streetViewControl: true
};
var mymap = new google.maps.Map( document.getElementById( 'map' ), options );
var marker = new google.maps.Marker({
map: mymap,
draggable: false,
flat: true,
icon: '<?php echo get_template_directory_uri(); ?>/images/map-pin-res.png',
<?php if((get_post_meta(get_the_ID(), "_ct_latlng", true))) { ?>
position: new google.maps.LatLng(<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>)
<?php } else { ?>
position: results[0].geometry.location
<?php } ?>
});
}
});
}
<?php if((get_post_meta(get_the_ID(), "_ct_latlng", true))) { ?>
setMapAddress( "<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>" );
<?php } else { ?>
setMapAddress( "<?php the_title(); ?> <?php city(); ?> <?php state(); ?> <?php zipcode(); ?>" );
<?php } ?>
</script>
<div id="map"></div>
<?php }
function multi_marker_map() {
global $ct_options;
global $post;
$count = 0;
query_posts(array(
'post_type' => 'listings',
'posts_per_page' => 1000,
'order' => 'DSC'
)); ?>
<script>
var property_list = [];
var default_mapcenter = [];
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$count++; ?>
var property = {
thumb: '<?php ct_first_image_linked(); ?>',
<?php if( (get_post_meta($post->ID, "_ct_price", true)) != "" ) { ?>fullPrice: "<?php listing_price(); ?>",<?php } ?>
bed: "<?php beds(); ?>",
bath: "<?php baths(); ?>",
size: "<?php echo get_post_meta($post->ID, "_ct_sqft", true); ?> <?php sqftsqm(); ?>",
street: "<?php the_title(); ?>",
city: "<?php city(); ?>",
state: "<?php state(); ?>",
zip: "<?php zipcode(); ?>",
latlong: "<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>",
permalink: "<?php the_permalink(); ?>",
agentThumb: "<?php $agent = the_author_meta('ct_profile_url'); echo aq_resize($agent,40); ?>",
agentName: "<?php the_author_meta('first_name'); ?> <?php the_author_meta('last_name'); ?>",
agentTagline: "<?php if(get_the_author_meta('tagline')) { the_author_meta('tagline'); } ?>",
agentPhone: "<?php if(get_the_author_meta('office')) { the_author_meta('office'); } ?>",
agentEmail: "<?php if(get_the_author_meta('email')) { the_author_meta('email'); } ?>",
isHome: "<?php if(is_home()) { echo "false"; } else { echo "true"; } ?>",
commercial: "<?php if(has_type('commercial')) { echo 'commercial'; } ?>",
land: "<?php if(has_type('land')) { echo 'land'; } ?>",
siteURL: "<?php echo get_template_directory_uri(); ?>"
}
property_list.push(property);
<?php
endwhile; endif;
wp_reset_query();
?>
</script>
<script>var defaultmapcenter = {mapcenter: ""}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
<div id="map"></div>
<?php }
function featured_listings_map() {
global $ct_options;
global $post;
$count = 0;
query_posts(array(
'post_type' => 'listings',
'status' => 'featured',
'posts_per_page' => 1000,
'order' => 'DSC'
)); ?>
<script>
var property_list = [];
var default_mapcenter = [];
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$count++; ?>
var property = {
thumb: '<?php ct_first_image_linked(); ?>',
<?php if( (get_post_meta($post->ID, "_ct_price", true)) != "" ) { ?>fullPrice: "<?php listing_price(); ?>",<?php } ?>
bed: "<?php beds(); ?>",
bath: "<?php baths(); ?>",
size: "<?php echo get_post_meta($post->ID, "_ct_sqft", true); ?> <?php sqftsqm(); ?>",
street: "<?php the_title(); ?>",
city: "<?php city(); ?>",
state: "<?php state(); ?>",
zip: "<?php zipcode(); ?>",
latlong: "<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>",
permalink: "<?php the_permalink(); ?>",
agentThumb: "<?php $agent = the_author_meta('ct_profile_url'); echo aq_resize($agent,40); ?>",
agentName: "<?php the_author_meta('first_name'); ?> <?php the_author_meta('last_name'); ?>",
agentTagline: "<?php if(get_the_author_meta('tagline')) { the_author_meta('tagline'); } ?>",
agentPhone: "<?php if(get_the_author_meta('office')) { the_author_meta('office'); } ?>",
agentEmail: "<?php if(get_the_author_meta('email')) { the_author_meta('email'); } ?>",
isHome: "<?php if(is_home()) { echo "false"; } else { echo "true"; } ?>",
commercial: "<?php if(has_type('commercial')) { echo 'commercial'; } ?>",
land: "<?php if(has_type('land')) { echo 'land'; } ?>",
siteURL: "<?php echo get_template_directory_uri(); ?>"
}
property_list.push(property);
<?php
endwhile; endif;
wp_reset_query();
?>
</script>
<script>var defaultmapcenter = {mapcenter: ""}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
<div id="map"></div>
<?php }
function search_results_map() {
global $ct_options;
global $post;
$count = 0;
?>
<script>
var property_list = [];
var default_mapcenter = [];
<?php if ( have_posts() ) : while ( have_posts() ) : the_post();
$count++; ?>
var property = {
thumb: '<?php ct_first_image_linked(); ?>',
<?php if( (get_post_meta($post->ID, "_ct_price", true)) != "" ) { ?>fullPrice: "<?php listing_price(); ?>",<?php } ?>
bed: "<?php beds(); ?>",
bath: "<?php baths(); ?>",
size: "<?php echo get_post_meta($post->ID, "_ct_sqft", true); ?> <?php sqftsqm(); ?>",
street: "<?php the_title(); ?>",
city: "<?php city(); ?>",
state: "<?php state(); ?>",
zip: "<?php zipcode(); ?>",
latlong: "<?php echo get_post_meta(get_the_ID(), "_ct_latlng", true); ?>",
permalink: "<?php the_permalink(); ?>",
agentThumb: "<?php $agent = the_author_meta('ct_profile_url'); echo aq_resize($agent,40); ?>",
agentName: "<?php the_author_meta('first_name'); ?> <?php the_author_meta('last_name'); ?>",
agentTagline: "<?php if(get_the_author_meta('tagline')) { the_author_meta('tagline'); } ?>",
agentPhone: "<?php if(get_the_author_meta('office')) { the_author_meta('office'); } ?>",
agentEmail: "<?php if(get_the_author_meta('email')) { the_author_meta('email'); } ?>",
isHome: "<?php if(is_home()) { echo "false"; } else { echo "true"; } ?>",
commercial: "<?php if(has_type('commercial')) { echo 'commercial'; } ?>",
land: "<?php if(has_type('land')) { echo 'land'; } ?>",
siteURL: "<?php echo get_template_directory_uri(); ?>"
}
property_list.push(property);
<?php
endwhile; endif;
wp_reset_query();
?>
</script>
<script>var defaultmapcenter = {mapcenter: ""}; google.maps.event.addDomListener(window, 'load', function(){ estateMapping.init_property_map(property_list, defaultmapcenter); });</script>
<div id="map"></div>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Homepage Slider */
/*-----------------------------------------------------------------------------------*/
function ct_slider() {
global $ct_options;
global $post;
$slides = $ct_options['ct_flex_slider'];
if($slides > 1) { ?>
<div id="slider" class="flexslider">
<ul class="slides">
<?php
foreach ($slides as $slide => $value) {
if (!empty ($value['url'])) {
$imgURL = $value['url'];
$imgID = get_attachment_id_from_src($imgURL);
?>
<li>
<div class="flex-container">
<?php if (!empty ($value['title']) || !empty ($value['description'])) { ?>
<div class="flex-caption">
<?php if (!empty ($value['title'])) { ?>
<?php if (!empty ($value['link'])) { ?>
<h1 class="left"><?php _e($value['title'], 'contempo'); ?></h1><a class="left" href="<?php echo $value['link']; ?>"><i class="fa fa-angle-right"></i></a>
<div class="clear"></div>
<?php if (!empty ($value['description'])) { ?>
<p><?php _e($value['description'], 'contempo'); ?></p>
<?php } ?>
<?php } else { ?>
<h1><?php echo $value['title']; ?></h1>
<?php if (!empty ($value['description'])) { ?>
<p><?php _e($value['description'], 'contempo'); ?></p>
<?php } ?>
<?php } ?>
<?php if (!empty ($value['price'])) {
$currency_placement = $ct_options['ct_currency_placement'];
if($currency_placement == 'After') { ?>
<p class="price"><?php echo $value['price']; ?><?php currency(); ?></p>
<?php } else { ?>
<p class="price"><?php currency(); ?><?php echo $value['price']; ?></p>
<?php }
} ?>
<?php } ?>
</div>
<?php } ?>
</div>
<img src="<?php echo $imgURL; ?>" />
</li>
<?php } else {
if (!empty ($value['embed'])) {
echo '<li class="video">';
echo stripslashes($value['embed']);
echo '</li>';
}
}
} ?>
</ul>
</div>
<div class="clear"></div>
<?php }
}
/*-----------------------------------------------------------------------------------*/
/* Front End Featured Image Uploads */
/*-----------------------------------------------------------------------------------*/
function insert_attachment($file_handler,$post_id,$setthumb='false') {
// check to make sure its a successful upload
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ($setthumb) update_post_meta($post_id,'_thumbnail_id',$attach_id);
return $attach_id;
}
/*-----------------------------------------------------------------------------------*/
/* Submit Listing from Front End */
/*-----------------------------------------------------------------------------------*/
function submit_listing() {
global $ct_options;
$view = $ct_options['ct_view'];
if(isset($_POST['submitted']) && isset($_POST['post_nonce_field']) && wp_verify_nonce($_POST['post_nonce_field'], 'post_nonce')) {
if(trim($_POST['postTitle']) === '') {
$postTitleError = 'Please enter a title.';
$hasError = true;
} else {
$postTitle = trim($_POST['postTitle']);
}
$post_information = array(
'post_title' => wp_strip_all_tags( $_POST['postTitle'] ),
'post_content' => $_POST['postContent'],
'post_type' => 'listings',
'post_status' => 'pending'
);
$post_id = wp_insert_post($post_information);
if ($_FILES) {
foreach ($_FILES as $file => $array) {
$newupload = insert_attachment($file,$post_id);
}
}
if($post_id) {
// Update Custom Meta
update_post_meta($post_id, '_ct_price', esc_attr(strip_tags($_POST['customMetaPrice'])));
update_post_meta($post_id, '_ct_sqft', esc_attr(strip_tags($_POST['customMetaSqFt'])));
//Update Custom Taxonomies
wp_set_post_terms($post_id,array($_POST['ct_property_type']),'property_type',true);
wp_set_post_terms($post_id,array($_POST['customTaxBeds']),'beds',true);
wp_set_post_terms($post_id,array($_POST['customTaxBaths']),'baths',true);
wp_set_post_terms($post_id,array($_POST['ct_ct_status']),'ct_status',true);
wp_set_post_terms($post_id,array($_POST['customTaxCity']),'city',true);
wp_set_post_terms($post_id,array($_POST['customTaxState']),'state',true);
wp_set_post_terms($post_id,array($_POST['customTaxZip']),'zipcode',true);
wp_set_post_terms($post_id,array($_POST['customTaxFeat']),'additional_features',true);
// Redirect
wp_redirect( home_url() . '/?page_id=' . $view ); exit;
}
}
}
/*-----------------------------------------------------------------------------------*/
/* PayPal for Paid Submissions */
/*-----------------------------------------------------------------------------------*/
function ct_paypal() {
global $ct_options;
?>
<form class="paypalbutton" action="https://www.paypal.com//cgi-bin/webscr" method="post" target="_blank">
<input type="hidden" name="business" value="<?php echo $ct_options['ct_paypal']; ?>" />
<input type="hidden" name="cmd" value="_xclick" />
<input type="hidden" name="item_name" value="<?php the_title(); ?>" />
<input type="hidden" name="url" value="<?php the_permalink(); ?>" />
<input type="hidden" name="amount" value="<?php echo $ct_options['ct_price']; ?>" />
<input type="hidden" name="currency_code" value="USD" />
<input type="hidden" name="lc" value="US" />
<input type="image" name="submit" style="border: 0;" src="https://www.paypal.com/en_US/i/btn/btn_buynow_SM.gif" alt="PayPal - The safer, easier way to pay online" />
</form>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Login & Registration */
/*-----------------------------------------------------------------------------------*/
function ct_registration_form() {
// only show the registration form to non-logged-in members
if(!is_user_logged_in()) {
// check to make sure user registration is enabled
$registration_enabled = get_option('users_can_register');
// only show the registration form if allowed
if($registration_enabled) {
$output = ct_registration_form_fields();
} else {
$output = '<p class="no-registration">' . __('User registration is not enabled') . '</p>';
}
return $output;
}
}
add_shortcode('register_form', 'ct_registration_form');
// user login form
function ct_login_form() {
if(!is_user_logged_in()) {
$output = ct_login_form_fields();
} else {
// could show some logged in user info here
// $output = 'user info here';
}
return $output;
}
add_shortcode('login_form', 'ct_login_form');
// login form fields
function ct_login_form_fields() {
ob_start(); ?>
<h4 class="marB30"><?php _e('Already a member? Login here.', 'contempo'); ?></h4>
<?php
// show any error messages after form submission
ct_show_error_messages(); ?>
<form id="ct_login_form" class="ct_form" action="" method="post">
<fieldset>
<label for="ct_user_Login"><?php _e('Username', 'contempo'); ?></label>
<input name="ct_user_login" id="ct_user_login" class="required" type="text"/>
<label for="ct_user_pass"><?php _e('Password', 'contempo'); ?></label>
<input name="ct_user_pass" id="ct_user_pass" class="required" type="password"/>
<div class="clear"></div>
<input type="hidden" name="ct_login_nonce" value="<?php echo wp_create_nonce('ct-login-nonce'); ?>"/>
<input id="ct_login_submit" type="submit" value="Login"/>
</fieldset>
</form>
<?php
return ob_get_clean();
}
// registration form fields
function ct_registration_form_fields() {
ob_start(); ?>
<h4 class="marB30"><?php _e('Don\'t have an account? Register here.', 'contempo'); ?></h4>
<?php
// show any error messages after form submission
ct_show_error_messages(); ?>
<form id="ct_registration_form" class="ct_form" action="" method="POST">
<fieldset>
<label for="ct_user_Login"><?php _e('Username', 'contempo'); ?></label>
<input name="ct_user_login" id="ct_user_login" class="required" type="text"/>
<label for="ct_user_email"><?php _e('Email', 'contempo'); ?></label>
<input name="ct_user_email" id="ct_user_email" class="required" type="email"/>
<label for="ct_user_first"><?php _e('First Name', 'contempo'); ?></label>
<input name="ct_user_first" id="ct_user_first" type="text"/>
<label for="ct_user_last"><?php _e('Last Name', 'contempo'); ?></label>
<input name="ct_user_last" id="ct_user_last" type="text"/>
<label for="password"><?php _e('Password', 'contempo'); ?></label>
<input name="ct_user_pass" id="password" class="required" type="password"/>
<label for="password_again"><?php _e('Password Again', 'contempo'); ?></label>
<input name="ct_user_pass_confirm" id="password_again" class="required" type="password"/>
<div class="clear"></div>
<input type="hidden" name="ct_register_nonce" value="<?php echo wp_create_nonce('ct-register-nonce'); ?>"/>
<input type="submit" value="<?php _e('Register', 'contempo'); ?>"/>
</fieldset>
</form>
<?php
return ob_get_clean();
}
// register a new user
function ct_add_new_member() {
if (isset( $_POST["ct_user_login"] ) && wp_verify_nonce($_POST['ct_register_nonce'], 'ct-register-nonce')) {
$user_login = $_POST["ct_user_login"];
$user_email = $_POST["ct_user_email"];
$user_first = $_POST["ct_user_first"];
$user_last = $_POST["ct_user_last"];
$user_pass = $_POST["ct_user_pass"];
$pass_confirm = $_POST["ct_user_pass_confirm"];
// this is required for username checks
require_once(ABSPATH . WPINC . '/registration.php');
if(username_exists($user_login)) {
// Username already registered
ct_errors()->add('username_unavailable', __('Username already taken'));
}
if(!validate_username($user_login)) {
// invalid username
ct_errors()->add('username_invalid', __('Invalid username'));
}
if($user_login == '') {
// empty username
ct_errors()->add('username_empty', __('Please enter a username'));
}
if(!is_email($user_email)) {
//invalid email
ct_errors()->add('email_invalid', __('Invalid email'));
}
if(email_exists($user_email)) {
//Email address already registered
ct_errors()->add('email_used', __('Email already registered'));
}
if($user_pass == '') {
// passwords do not match
ct_errors()->add('password_empty', __('Please enter a password'));
}
if($user_pass != $pass_confirm) {
// passwords do not match
ct_errors()->add('password_mismatch', __('Passwords do not match'));
}
$errors = ct_errors()->get_error_messages();
// only create the user in if there are no errors
if(empty($errors)) {
$new_user_id = wp_insert_user(array(
'user_login' => $user_login,
'user_pass' => $user_pass,
'user_email' => $user_email,
'first_name' => $user_first,
'last_name' => $user_last,
'user_registered' => date('Y-m-d H:i:s'),
'role' => 'subscriber'
)
);
if($new_user_id) {
// send an email to the admin alerting them of the registration
wp_new_user_notification($new_user_id);
// log the new user in
wp_setcookie($user_login, $user_pass, true);
wp_set_current_user($new_user_id, $user_login);
do_action('wp_login', $user_login);
// send the newly created user to the home page after logging them in
wp_redirect(home_url()); exit;
}
}
}
}
add_action('init', 'ct_add_new_member');
// logs a member in after submitting a form
function ct_login_member() {
if(isset($_POST['ct_user_login']) && wp_verify_nonce($_POST['ct_login_nonce'], 'ct-login-nonce')) {
// this returns the user ID and other info from the user name
$user = get_userdatabylogin($_POST['ct_user_login']);
if(!$user) {
// if the user name doesn't exist
ct_errors()->add('empty_username', __('Invalid username'));
}
if(!isset($_POST['ct_user_pass']) || $_POST['ct_user_pass'] == '') {
// if no password was entered
ct_errors()->add('empty_password', __('Please enter a password'));
}
// check the user's login with their password
if(!wp_check_password($_POST['ct_user_pass'], $user->user_pass, $user->ID)) {
// if the password is incorrect for the specified user
ct_errors()->add('empty_password', __('Incorrect password'));
}
// retrieve all error messages
$errors = ct_errors()->get_error_messages();
// only log the user in if there are no errors
if(empty($errors)) {
wp_setcookie($_POST['ct_user_login'], $_POST['ct_user_pass'], true);
wp_set_current_user($user->ID, $_POST['ct_user_login']);
do_action('wp_login', $_POST['ct_user_login']);
wp_redirect(home_url()); exit;
}
}
}
add_action('init', 'ct_login_member');
// displays error messages from form submissions
function ct_show_error_messages() {
if($codes = ct_errors()->get_error_codes()) {
echo '<div class="ct_errors">';
// Loop error codes and display errors
foreach($codes as $code){
$message = ct_errors()->get_error_message($code);
echo '<span class="error"><strong>' . __('Error') . '</strong>: ' . $message . '</span><br/>';
}
echo '</div>';
}
}
// used for tracking error messages
function ct_errors(){
static $wp_error; // Will hold global variable safely
return isset($wp_error) ? $wp_error : ($wp_error = new WP_Error(null, null, null));
}
/*-----------------------------------------------------------------------------------*/
/* WPML Flags */
/*-----------------------------------------------------------------------------------*/
function ct_language_selector_flags(){
$languages = icl_get_languages('skip_missing=0&orderby=code');
if(!empty($languages)){
echo '<ul>';
foreach($languages as $l){
echo '<li>';
if(!$l['active']) echo '<a href="'.$l['url'].'">';
echo '<img src="'.$l['country_flag_url'].'" height="12" alt="'.$l['language_code'].'" width="18" />';
if(!$l['active']) echo '</a>';
echo '</li>';
}
echo '</ul>';
}
}
/*-----------------------------------------------------------------------------------*/
/* Remove CPTs from Blog Search */
/*-----------------------------------------------------------------------------------*/
function ct_searchfilter($query) {
if ($query->is_search) {
$query->set('post_type',array('post','page'));
}
return $query;
}
add_filter('pre_get_posts','ct_searchfilter');
/*-----------------------------------------------------------------------------------*/
/* Deregister Mortgage Calc Plugin CSS */
/*-----------------------------------------------------------------------------------*/
function ct_deregister_styles() {
wp_deregister_style( 'ct_mortgage_calc' );
}
add_action( 'wp_print_styles', 'ct_deregister_styles', 100 );
/*-----------------------------------------------------------------------------------*/
/* Add user profile fields. */
/*-----------------------------------------------------------------------------------*/
function ct_modify_contact_methods($profile_fields) {
// Add new fields
$profile_fields['twitterhandle'] = 'Twitter Username';
$profile_fields['facebookurl'] = 'Facebook URL';
$profile_fields['linkedinurl'] = 'LinkedIn URL';
$profile_fields['gplus'] = 'Google+ URL';
return $profile_fields;
}
add_filter('user_contactmethods', 'ct_modify_contact_methods');
/*-----------------------------------------------------------------------------------*/
/* Move Featured Image Meta Box To The Top */
/*-----------------------------------------------------------------------------------*/
function ct_move_meta_box() {
remove_meta_box( 'postimagediv', 'listings', 'side' );
add_meta_box('postimagediv', __('Featured Image'), 'post_thumbnail_meta_box', 'listings', 'side', 'high');
}
add_action('do_meta_boxes', 'ct_move_meta_box');
/*-----------------------------------------------------------------------------------*/
/* Fix Pagination on Search Results */
/*-----------------------------------------------------------------------------------*/
function ct_fix_query($query) {
global $paged;
if( $query->is_main_query() && $query->is_home() ) {
$query->set('post_type', array('post', 'listings'));
}
}
add_action('pre_get_posts', 'ct_fix_query');
/*-----------------------------------------------------------------------------------*/
/* Filter "Enter title here" with custom text */
/*-----------------------------------------------------------------------------------*/
function ct_change_default_title( $title ){
$screen = get_current_screen();
if ( 'listings' == $screen->post_type ) {
$title = 'Enter the listing address here';
}
return $title;
}
add_filter( 'enter_title_here', 'ct_change_default_title' );
/*-----------------------------------------------------------------------------------*/
/* Status Snipes */
/*-----------------------------------------------------------------------------------*/
function has_status( $status, $_post = null ) {
if ( empty( $status ) )
return false;
if ( $_post )
$_post = get_post( $_post );
else
$_post =& $GLOBALS['post'];
if ( !$_post )
return false;
$r = is_object_in_term( $_post->ID, 'ct_status', $status );
if ( is_wp_error( $r ) )
return false;
return $r;
}
function ct_status() { ?>
<?php if(has_status('reduced') || has_status('sold') || has_status('leased') || has_status('open-house') || has_status('for-rent') || has_status('rental')) { ?>
<h6 class="snipe <?php if(has_status('reduced')) { echo "reduced"; } elseif(has_status('sold')) { echo "sold"; } elseif(has_status('leased')) { echo "leased"; } elseif(has_status('open-house')) { echo "open-house"; } elseif(has_status('available')) { echo "available"; } elseif(has_status('for-rent') || has_status('rental')) { echo "rental"; } ?>"><?php if(has_status('reduced')) { ?><?php _e('Reduced', 'contempo'); ?><?php } elseif(has_status('leased')) { ?><?php _e('Leased', 'contempo'); ?><?php } elseif(has_status('sold')) { ?><?php _e('Sold', 'contempo'); ?><?php } elseif(has_status('open-house')) { ?><?php _e('Open House', 'contempo'); ?><?php } elseif(has_status('available')) { ?><?php _e('Available', 'contempo'); ?><?php } elseif(has_status('for-rent') || has_status('rental')) { ?><?php _e('Rental', 'contempo'); ?><?php } ?></h6>
<?php } ?>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Currency */
/*-----------------------------------------------------------------------------------*/
function currency() {
global $ct_options;
if($ct_options['ct_currency']) {
echo $ct_options['ct_currency'];
} else {
echo "$";
}
}
/*-----------------------------------------------------------------------------------*/
/* Listing Price */
/*-----------------------------------------------------------------------------------*/
function listing_price() {
global $post;
global $ct_options;
$currency_placement = $ct_options['ct_currency_placement'];
$price_meta = get_post_meta(get_the_ID(), '_ct_price', true);
$price_meta= preg_replace('/[\$,]/', '', $price_meta);
if($currency_placement == 'After') {
echo number_format_i18n($price_meta, 0);
currency();
} else {
currency();
echo number_format_i18n($price_meta, 0);
}
}
/*-----------------------------------------------------------------------------------*/
/* Map Pin Price */
/*-----------------------------------------------------------------------------------*/
function map_pin_price() {
global $post;
$ct_price = get_post_meta($post->ID, "_ct_price", true);
if($ct_price < 10000) {
echo substr($ct_price, 0, 4);
} elseif($ct_price < 100000) {
echo substr($ct_price, 0, 2) . 'K';
} elseif($ct_price < 1000000) {
echo substr($ct_price, 0, 3) . 'K';
} elseif($ct_price < 10000000) {
echo substr($ct_price, 0, 1) . 'M';
} elseif($ct_price < 100000000) {
echo substr($ct_price, 0, 2) . 'M';
} elseif($ct_price < 1000000000) {
echo substr($ct_price, 0, 3) . 'M';
} else {
echo '1G+';
}
}
/*-----------------------------------------------------------------------------------*/
/* Sq Ft or Sq Meters */
/*-----------------------------------------------------------------------------------*/
function sqftsqm() {
global $ct_options;
if($ct_options['ct_sq'] == "Sq Ft") {
echo _e(' Sq Ft', 'contempo');
} elseif($ct_options['ct_sq'] == "Sq Meters") {
echo _e(' m<sup>2</sup>', 'contempo');
}
}
/*-----------------------------------------------------------------------------------*/
/* Acres or Sq Meters */
/*-----------------------------------------------------------------------------------*/
function acres() {
global $ct_options;
if($ct_options['ct_acres'] == "Acres") {
echo _e(' Acres', 'contempo');
} elseif($ct_options['ct_acres'] == "Sq Ft") {
echo _e(' Sq Ft', 'contempo');
} elseif($ct_options['ct_acres'] == "Sq Meters") {
echo _e(' m<sup>2</sup>', 'contempo');
}
}
/*-----------------------------------------------------------------------------------*/
/* Property Type Tags */
/*-----------------------------------------------------------------------------------*/
function has_type( $type, $_post = null ) {
if ( empty( $type ) )
return false;
if ( $_post )
$_post = get_post( $_post );
else
$_post =& $GLOBALS['post'];
if ( !$_post )
return false;
$r = is_object_in_term( $_post->ID, 'property_type', $type );
if ( is_wp_error( $r ) )
return false;
return $r;
}
/*-----------------------------------------------------------------------------------*/
/* Advanced Search Select */
/*-----------------------------------------------------------------------------------*/
function ct_search_form_select($name, $taxonomy_name = null) {
global $search_values;
if (!$taxonomy_name) {
$taxonomy_name = $name;
}
?>
<select id="ct_<?php echo $name; ?>" name="ct_<?php echo $name; ?>">
<option value="0"><?php _e('Any', 'contempo'); ?></option>
<?php foreach( get_terms($taxonomy_name, 'hide_empty=true') as $t ) : ?>
<?php if ($search_values[$name] == $t->slug) { $selected = 'selected="selected" '; } else { $selected = ''; } ?>
<option <?php echo $selected; ?>value="<?php _e($t->slug, 'contempo'); ?>"><?php _e($t->name, 'contempo'); ?></option>
<?php endforeach; ?>
</select>
<?php
}
/*-----------------------------------------------------------------------------------*/
/* Numeric Pagination */
/*-----------------------------------------------------------------------------------*/
function ct_numeric_pagination() {
if( is_singular() )
return;
global $wp_query;
/** Stop execution if there's only 1 page */
if( $wp_query->max_num_pages <= 1 )
return;
$paged = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
$max = intval( $wp_query->max_num_pages );
/** Add current page to the array */
if ( $paged >= 1 )
$links[] = $paged;
/** Add the pages around the current page to the array */
if ( $paged >= 3 ) {
$links[] = $paged - 1;
$links[] = $paged - 2;
}
if ( ( $paged + 2 ) <= $max ) {
$links[] = $paged + 2;
$links[] = $paged + 1;
}
echo '<div class="pagination"><ul>' . "\n";
/** Previous Post Link */
if ( get_previous_posts_link() )
printf( '<li>%s</li>' . "\n", get_previous_posts_link() );
/** Link to first page, plus ellipses if necessary */
if ( ! in_array( 1, $links ) ) {
$class = 1 == $paged ? ' class="current"' : '';
printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( 1 ) ), '1' );
if ( ! in_array( 2, $links ) )
echo '<li>…</li>';
}
/** Link to current page, plus 2 pages in either direction if necessary */
sort( $links );
foreach ( (array) $links as $link ) {
$class = $paged == $link ? ' class="current"' : '';
printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $link ) ), $link );
}
/** Link to last page, plus ellipses if necessary */
if ( ! in_array( $max, $links ) ) {
if ( ! in_array( $max - 1, $links ) )
echo '<li>…</li>' . "\n";
$class = $paged == $max ? ' class="current"' : '';
printf( '<li%s><a href="%s">%s</a></li>' . "\n", $class, esc_url( get_pagenum_link( $max ) ), $max );
}
/** Next Post Link */
if ( get_next_posts_link() )
printf( '<li>%s</li>' . "\n", get_next_posts_link() );
echo '<div class="clear"></div>';
echo '</ul></div>' . "\n";
}
/*-----------------------------------------------------------------------------------*/
/* Pagination */
/*-----------------------------------------------------------------------------------*/
function ct_pagination($pages = '', $range = 2) {
$showitems = ($range * 2)+1;
global $paged;
if(empty($paged)) $paged = 1;
if($pages == '') {
global $wp_query;
$pages = $wp_query->max_num_pages;
if(!$pages) {
$pages = 1;
}
}
if(1 != $pages) {
echo "<div class='pagination'>";
if($paged > 2 && $paged > $range+1 && $showitems < $pages) echo "<a href='".get_pagenum_link(1)."'>&laquo;</a>";
if($paged > 1 && $showitems < $pages) echo "<a href='".get_pagenum_link($paged - 1)."'>&lsaquo;</a>";
for ($i=1; $i <= $pages; $i++)
{
if (1 != $pages &&( !($i >= $paged+$range+1 || $i <= $paged-$range-1) || $pages <= $showitems ))
{
echo ($paged == $i)? "<span class='current'>".$i."</span>":"<a href='".get_pagenum_link($i)."' class='inactive' >".$i."</a>";
}
}
if ($paged < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($paged + 1)."'>&rsaquo;</a>";
if ($paged < $pages-1 && $paged+$range-1 < $pages && $showitems < $pages) echo "<a href='".get_pagenum_link($pages)."'>&raquo;</a>";
echo "<div class='clear'></div>\n";
echo "</div>\n";
}
}
/**
* Returns the URL from the post.
*
* @uses get_the_link() to get the URL in the post meta (if it exists) or
* the first link found in the post content.
*
* Falls back to the post permalink if no URL is found in the post.
*/
function ct_get_link_url() {
$has_url = get_the_post_format_url();
return ( $has_url ) ? $has_url : apply_filters( 'the_permalink', get_permalink() );
}
/*-----------------------------------------------------------------------------------*/
/* Twitter Feed */
/*-----------------------------------------------------------------------------------*/
function ct_twitter_feed() {
global $ct_options;
$user = isset( $ct_options['ct_twitter_footer_user'] ) ? esc_attr( $ct_options['ct_twitter_footer_user'] ) : '';
$limit = isset( $ct_options['ct_twitter_footer_limit'] ) ? esc_attr( $ct_options['ct_twitter_footer_limit'] ) : '';
$feed = new Twitter($user, $limit);
$tweets = $feed->getTweets();
echo '<i class="fa fa-twitter left"></i>';
echo '<ul class="cycle">';
foreach($tweets as $tweet) {
echo "<li>". $tweet->content . __(' by', 'contempo') . " <a href='http://twitter.com/". $tweet->user ."'>". $tweet->author ."</a></li>";
}
echo "</ul>";
echo '<div class="clear"></div>';
}
/*-----------------------------------------------------------------------------------*/
/* Content Navigation */
/*-----------------------------------------------------------------------------------*/
function ct_content_nav() { ?>
<div class="clear"></div>
<nav class="content-nav">
<div class="nav-prev left"><?php next_posts_link( __( '<span class="meta-nav">&larr;</span> Older', 'contempo' ) ); ?></div>
<div class="nav-next right"><?php previous_posts_link( __( 'Newer <span class="meta-nav">&rarr;</span>', 'contempo' ) ); ?></div>
</nav>
<?php }
add_filter('next_posts_link_attributes', 'posts_link_attributes');
add_filter('previous_posts_link_attributes', 'posts_link_attributes');
function posts_link_attributes() {
return 'class="btn"';
}
/*-----------------------------------------------------------------------------------*/
/* Post Navigation */
/*-----------------------------------------------------------------------------------*/
function ct_post_nav() { ?>
<nav class="marT30 marB80">
<div class="nav-prev left"><?php next_post_link('%link', '<i class="fa fa-chevron-left"></i>', TRUE); ?></div>
<div class="nav-next right"><?php previous_post_link('%link', '<i class="fa fa-chevron-right"></i>', TRUE); ?></div>
<div class="clear"></div>
</nav>
<div class="clear"></div>
<?php }
add_filter('next_post_link', 'post_link_attributes');
add_filter('previous_post_link', 'post_link_attributes');
function post_link_attributes($output) {
$code = 'class="btn"';
return str_replace('<a href=', '<a '.$code.' href=', $output);
}
/*-----------------------------------------------------------------------------------*/
/* Get the Slug */
/*-----------------------------------------------------------------------------------*/
function the_slug() {
$post_data = get_post($post->ID, ARRAY_A);
$slug = $post_data['post_name'];
return $slug;
}
/*-----------------------------------------------------------------------------------*/
/* Remove WLW and RSD for validation */
/*-----------------------------------------------------------------------------------*/
remove_action('wp_head', 'wlwmanifest_link');
remove_action('wp_head', 'rsd_link');
/*-----------------------------------------------------------------------------------*/
/* Get image ID from URL - http://goo.gl/q9D9L
/*-----------------------------------------------------------------------------------*/
function get_attachment_id_from_src($image_src) {
global $wpdb;
$query = "SELECT ID FROM {$wpdb->posts} WHERE guid='$image_src'";
$id = $wpdb->get_var($query);
return $id;
}
/*-----------------------------------------------------------------------------------*/
/* Custom excerpt length */
/*-----------------------------------------------------------------------------------*/
function new_excerpt_length($length) {
global $ct_options;
$ct_excerpt_length = isset( $instance['ct_excerpt_length'] ) ? esc_attr( $instance['ct_excerpt_length'] ) : '';
$ct_excerpt_length = $ct_options['ct_excerpt_length'];
return $ct_excerpt_length;
}
add_filter('excerpt_length', 'new_excerpt_length');
/*-----------------------------------------------------------------------------------*/
/* Add read more link to excerpt */
/*-----------------------------------------------------------------------------------*/
function new_excerpt_more($more) {
return '.';
}
add_filter('excerpt_more', 'new_excerpt_more');
/*-----------------------------------------------------------------------------------*/
/* Read More Link */
/*-----------------------------------------------------------------------------------*/
function ct_read_more_link() {
global $ct_options;
$ct_read_more = $ct_options['ct_read_more']; ?>
<a class="read-more right" href="<?php the_permalink(); ?>'">
<?php if($ct_read_more) {
echo $ct_read_more;
} else {
echo "Read more <em>&rarr;</em>";
} ?>
</a>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Custom Author */
/*-----------------------------------------------------------------------------------*/
function ct_author() {
global $post;
if(get_post_meta($post->ID, "_ct_custom_author", true)) {
echo get_post_meta($post->ID, "_ct_custom_author", true);
} else {
the_author_meta('display_name');
}
}
/*-----------------------------------------------------------------------------------*/
/* Related Posts */
/*-----------------------------------------------------------------------------------*/
function ct_related_posts() {
global $post;
$tags = wp_get_post_tags($post->ID);
if ($tags) {
echo '<h4 class="marT40 marB20">Related Posts</h4>';
echo '<ul class="related">';
$first_tag = $tags[0]->term_id;
$args=array(
'tag__in' => array($first_tag),
'post__not_in' => array($post->ID),
'showposts'=>3,
'caller_get_posts'=>1
);
$my_query = new WP_Query($args);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post(); ?>
<li>
<h5><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?></a></h5>
</li>
<?php
endwhile;
}
echo '</ul>';
}
}
/*-----------------------------------------------------------------------------------*/
/* Allow Shortcodes to be used in widgets */
/*-----------------------------------------------------------------------------------*/
add_filter('widget_text', 'do_shortcode');
/*-----------------------------------------------------------------------------------*/
/* Add CPTs to RSS feed */
/*-----------------------------------------------------------------------------------*/
function myfeed_request($qv) {
if (isset($qv['feed']))
$qv['post_type'] = get_post_types();
return $qv;
}
add_filter('request', 'myfeed_request');
/*-----------------------------------------------------------------------------------*/
/* Remove height & width from post thumbnails */
/*-----------------------------------------------------------------------------------*/
function remove_thumbnail_dimensions( $html, $post_id, $post_image_id ) {
$html = preg_replace( '/(width|height)=\"\d*\"\s/', "", $html );
return $html;
}
add_filter( 'post_thumbnail_html', 'remove_thumbnail_dimensions', 10, 3 );
/*-----------------------------------------------------------------------------------*/
/* Get all of the images attached to the current post */
/*-----------------------------------------------------------------------------------*/
function ct_get_images($size = 'full') {
global $post;
$photos = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID') );
$results = array();
if ($photos) {
foreach ($photos as $photo) {
// get the correct image html for the selected size
$results[] = wp_get_attachment_url($photo->ID);
}
}
return $results;
}
/*-----------------------------------------------------------------------------------*/
/* Display all images attached to post - detail */
/*-----------------------------------------------------------------------------------*/
function ct_gallery_images() {
$photos = ct_get_images('full');
if ($photos) {
foreach ($photos as $photo) { ?>
<img class="marB18" src="<?php echo aq_resize($photo,945); ?>" />
<?php }
}
}
/*-----------------------------------------------------------------------------------*/
/* Display all images attached to post backstretch slider */
/*-----------------------------------------------------------------------------------*/
function ct_backslider_images() {
$photos = ct_get_images('full');
if ($photos) {
foreach ($photos as $photo) {
echo '"' . aq_resize($photo,2000) . '",';
}
}
}
/*-----------------------------------------------------------------------------------*/
/* Display first image listing - view */
/*-----------------------------------------------------------------------------------*/
function ct_first_image_linked_view() {
$photo = ct_get_post_image();
global $ct_options;
global $post;
the_post_thumbnail('large'); ?>
<div class="hover-content">
<div class="inner">
<a class="view" href="<?php the_permalink() ?>"><?php _e('View','contempo'); ?></a>
</div>
</div>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Display first image thumbnail - float right */
/*-----------------------------------------------------------------------------------*/
function ct_first_image_tn_right() {
global $post;
if(has_post_thumbnail()) { ?>
<div class="tn">
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(69,40); ?>
</a>
</div>
<?php }
}
/*-----------------------------------------------------------------------------------*/
/* Get the first image attached to the current post */
/*-----------------------------------------------------------------------------------*/
function ct_get_post_image() {
global $post;
$photos = get_children( array('post_parent' => $post->ID, 'post_status' => 'inherit', 'post_type' => 'attachment', 'post_mime_type' => 'image', 'order' => 'ASC', 'orderby' => 'menu_order ID'));
if ($photos) {
$photo = array_shift($photos);
return wp_get_attachment_url($photo->ID);
}
return false;
}
/*-----------------------------------------------------------------------------------*/
/* Display first image thumb */
/*-----------------------------------------------------------------------------------*/
function ct_first_image_tn() { ?>
<a href="<?php the_permalink(); ?>">
<?php the_post_thumbnail(array(150,150)); ?>
</a>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Display first image thumb */
/*-----------------------------------------------------------------------------------*/
function ct_first_image_lrg() {
the_post_thumbnail(array(600,250));
}
/*-----------------------------------------------------------------------------------*/
/* Display first image linked portfolio widget */
/*-----------------------------------------------------------------------------------*/
function ct_first_image_linked_portfolio_widget() { ?>
<a class="thumb" href="<?php the_permalink(); ?>">
<?php the_post_thumbnail('large'); ?>
</a>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Display all images attached to post */
/*-----------------------------------------------------------------------------------*/
function ct_slider_images() {
$photos = ct_get_images('full');
if ($photos) {
foreach ($photos as $photo) { ?>
<li data-thumb="<?php echo $photo; ?>">
<a href="<?php echo $photo; ?>" rel="prettyphoto[gallery]">
<img src="<?php echo $photo; ?>" title="<?php the_title(); ?>" />
</a>
</li>
<?php }
}
}
/*-----------------------------------------------------------------------------------*/
/* Display all images attached to post */
/*-----------------------------------------------------------------------------------*/
function ct_slider_carousel_images() {
$photos = ct_get_images('full');
if ($photos) {
foreach ($photos as $photo) { ?>
<li data-thumb="<?php echo $photo; ?>">
<img src="<?php echo $photo; ?>" title="<?php the_title(); ?>" />
</li>
<?php }
}
}
/*-----------------------------------------------------------------------------------*/
/* Display first image linked */
/*-----------------------------------------------------------------------------------*/
function ct_first_image_linked() {?><a class="thumb" href="<?php the_permalink(); ?>"><?php the_post_thumbnail('large'); ?></a><?php }
/*-----------------------------------------------------------------------------------*/
/* Get users */
/*-----------------------------------------------------------------------------------*/
function ct_get_users($users_per_page = 10, $paged = 1, $role = '', $orderby = 'login', $order = 'ASC', $usersearch = '' ) {
global $blog_id;
$args = array(
'number' => $users_per_page,
'offset' => ( $paged-1 ) * $users_per_page,
'role' => $role,
'search' => $usersearch,
'fields' => 'all_with_meta',
'blog_id' => $blog_id,
'orderby' => $orderby,
'order' => $order
);
$wp_user_search = new WP_User_Query( $args );
$user_results = $wp_user_search->get_results();
return $user_results;
}
/*-----------------------------------------------------------------------------------*/
/* Listings Navigation */
/*-----------------------------------------------------------------------------------*/
function ct_listings_nav() { ?>
<div class="clear"></div>
<nav class="content-nav marB30">
<div class="nav-previous left"><?php next_posts_link( __( '<span class="meta-nav"><i class="fa fa-chevron-left"></i></span> Older listings', 'contempo' ) ); ?></div>
<div class="nav-next right"><?php previous_posts_link( __( 'Newer listings <span class="meta-nav"><i class="fa fa-chevron-right"></i></span>', 'contempo' ) ); ?></div>
<div class="clear"></div>
</nav>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Content Navigation */
/*-----------------------------------------------------------------------------------*/
function ct_archive_content_nav() { ?>
<div class="nav-previous"><?php previous_posts_link('Previous') ?></div>
<div class="nav-next"><?php next_posts_link('Next','') ?></div>
<?php }
function ct_single_content_nav() { ?>
<div class="nav-previous"><?php previous_post_link( __( '%link', 'contempo' ) ); ?></div>
<div class="nav-next"><?php next_post_link( __( '%link', 'contempo' ) ); ?></div>
<?php }
/*-----------------------------------------------------------------------------------*/
/* Browser Detection */
/*-----------------------------------------------------------------------------------*/
class Browser {
private static $known_browsers = array(
'msie', 'firefox', 'safari',
'webkit', 'opera', 'netscape',
'konqueror', 'gecko', 'chrome'
);
private function __construct() {}
static public function get_info ($agent = null) {
// Clean up agent and build regex that matches phrases for known browsers
// (e.g. "Firefox/2.0" or "MSIE 6.0" (This only matches the major and minor
// version numbers. E.g. "2.0.0.6" is parsed as simply "2.0"
$agent = strtolower($agent ? $agent : $_SERVER['HTTP_USER_AGENT']);
// This pattern throws an exception if server is not up to date on regex lib
//$pattern = '#(?<browser>' . join('|', $known) .
// ')[/ ]+(?<version>[0-9]+(?:.[0-9]+)?)#';
// So we use this one
$pattern = '#(' . join('|',self::$known_browsers) .
')[/ ]+([0-9]+(?:.[0-9]+)?)#';
// Find all phrases (or return empty array if none found)
if (!preg_match_all($pattern, $agent, $matches)) return array();
// Since some UAs have more than one phrase (e.g Firefox has a Gecko phrase,
// Opera 7,8 have a MSIE phrase), use the last two found (the right-most one
// in the UA). That's usually the most correct.
$i = count($matches[1])-1;
$r = array($matches[1][$i] => $matches[2][$i]);
if ($i) $r[$matches[1][$i-1]] = $matches[2][$i-1];
return $r;
}
/******************************************************************************/
/**
* Is the user's browser that %#$@! of IE ?
* @return boolean
*/
static public function isIE () {
$bi = self::get_info();
return (!empty($bi['msie']));
}
static public function isIE6 () {
$bi = self::get_info();
return (!empty($bi['msie']) && $bi['msie'] == 6.0);
}
static public function isIE7 () {
$bi = self::get_info();
return (!empty($bi['msie']) && $bi['msie'] == 7.0);
}
static public function isIE8 () {
$bi = self::get_info();
return (!empty($bi['msie']) && $bi['msie'] == 8.0);
}
static public function isIE9 () {
$bi = self::get_info();
return (!empty($bi['msie']) && $bi['msie'] == 9.0);
}
/**
* Is the user's browser da good ol' Firefox ?
* @return boolean
*/
static public function isFirefox () {
return (strpos ($_SERVER['HTTP_USER_AGENT'], "Firefox") !== false);
}
/**
* Is the user's browser the shiny Chrome ?
* @return boolean
*/
static public function isChrome () {
$bi = self::get_info();
return (!empty($bi['chrome']));
}
/**
* Is the user's browser Safari ?
* @return boolean
*/
static public function isSafari () {
$bi = self::get_info();
return (!empty($bi['safari']) && !empty($bi['webkit']));
}
/**
* Is the user's browser the almighty Opera ?
* @return boolean
*/
static public function isOpera () {
$bi = self::get_info();
return ( strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'opera') !== false );
}
/**
* Is the user's platform iPhone ?
* @return boolean
*/
static public function isIphone () {
return ( strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'iphone') !== false );
}
/**
* Is the user's platform iPad ?
* @return boolean
*/
static public function isIpad () {
return ( strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'ipad') !== false );
}
/**
* Is the user's platform the awesome Android ?
* @return boolean
*/
static public function isAndroid () {
return ( strpos(strtolower($_SERVER['HTTP_USER_AGENT']),'android') !== false );
}
}
/**
* The code below is inspired by Justin Tadlock's Hybrid Core.
*
* ct_breadcrumbs() shows a breadcrumb for all types of pages. Themes and plugins can filter $args or input directly.
* Allow filtering of only the $args using get_the_breadcrumb_args.
*
* @since 3.7.0
* @param array $args Mixed arguments for the menu.
* @return string Output of the breadcrumb menu.
*/
function ct_breadcrumbs( $args = array() ) {
global $wp_query, $wp_rewrite;
/* Get the textdomain. */
$textdomain = 'contempo';
/* Create an empty variable for the breadcrumb. */
$breadcrumb = '';
/* Create an empty array for the trail. */
$trail = array();
$path = '';
/* Set up the default arguments for the breadcrumb. */
$defaults = array(
'separator' => '<i class="fa fa-angle-right"></i>',
'before' => '<span class="breadcrumb-title"></span>',
'after' => false,
'front_page' => true,
'show_home' => __( 'Home', $textdomain ),
'echo' => true
);
/* Allow singular post views to have a taxonomy's terms prefixing the trail. */
if ( is_singular() )
$defaults["singular_{$wp_query->post->post_type}_taxonomy"] = false;
/* Apply filters to the arguments. */
$args = apply_filters( 'ct_breadcrumbs_args', $args );
/* Parse the arguments and extract them for easy variable naming. */
extract( wp_parse_args( $args, $defaults ) );
/* If $show_home is set and we're not on the front page of the site, link to the home page. */
if ( !is_front_page() && $show_home )
$trail[] = '<a id="bread-home" href="' . home_url() . '" title="' . esc_attr( get_bloginfo( 'name' ) ) . '" rel="home" class="trail-begin">' . $show_home . '</a>';
/* If viewing the front page of the site. */
if ( is_front_page() ) {
if ( !$front_page )
$trail = false;
elseif ( $show_home )
$trail['trail_end'] = "{$show_home}";
}
/* If viewing the "home"/posts page. */
elseif ( is_home() ) {
$home_page = get_page( $wp_query->get_queried_object_id() );
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( $home_page->post_parent, '' ) );
$trail['trail_end'] = get_the_title( $home_page->ID );
}
/* If viewing a singular post (page, attachment, etc.). */
elseif ( is_singular() ) {
/* Get singular post variables needed. */
$post = $wp_query->get_queried_object();
$post_id = absint( $wp_query->get_queried_object_id() );
$post_type = $post->post_type;
$parent = $post->post_parent;
/* If a custom post type, check if there are any pages in its hierarchy based on the slug. */
if ( 'page' !== $post_type ) {
$post_type_object = get_post_type_object( $post_type );
/* If $front has been set, add it to the $path. */
if ( 'post' == $post_type || 'attachment' == $post_type || ( $post_type_object->rewrite['with_front'] && $wp_rewrite->front ) )
$path .= trailingslashit( $wp_rewrite->front );
/* If there's a slug, add it to the $path. */
if ( !empty( $post_type_object->rewrite['slug'] ) )
$path .= $post_type_object->rewrite['slug'];
/* If there's a path, check for parents. */
if ( !empty( $path ) )
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( '', $path ) );
/* If there's an archive page, add it to the trail. */
if ( !empty( $post_type_object->rewrite['archive'] ) && function_exists( 'get_post_type_archive_link' ) )
$trail[] = '<a href="' . get_post_type_archive_link( $post_type ) . '" title="' . esc_attr( $post_type_object->labels->name ) . '">' . $post_type_object->labels->name . '</a>';
}
/* If the post type path returns nothing and there is a parent, get its parents. */
if ( empty( $path ) && 0 !== $parent || 'attachment' == $post_type )
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( $parent, '' ) );
/* Display terms for specific post type taxonomy if requested. */
if ( isset( $args["singular_{$post_type}_taxonomy"] ) && $terms = get_the_term_list( $post_id, $args["singular_{$post_type}_taxonomy"], '', ', ', '' ) )
$trail[] = $terms;
/* End with the post title. */
$post_title = get_the_title( $post_id ); // Force the post_id to make sure we get the correct page title.
if ( !empty( $post_title ) )
$trail['trail_end'] = $post_title;
}
/* If we're viewing any type of archive. */
elseif ( is_archive() ) {
/* If viewing a taxonomy term archive. */
if ( is_tax() || is_category() || is_tag() ) {
/* Get some taxonomy and term variables. */
$term = $wp_query->get_queried_object();
$taxonomy = get_taxonomy( $term->taxonomy );
/* Get the path to the term archive. Use this to determine if a page is present with it. */
if ( is_category() )
$path = get_option( 'category_base' );
elseif ( is_tag() )
$path = get_option( 'tag_base' );
else {
if ( $taxonomy->rewrite['with_front'] && $wp_rewrite->front )
$path = trailingslashit( $wp_rewrite->front );
$path .= $taxonomy->rewrite['slug'];
}
/* Get parent pages by path if they exist. */
if ( $path )
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( '', $path ) );
/* If the taxonomy is hierarchical, list its parent terms. */
if ( is_taxonomy_hierarchical( $term->taxonomy ) && $term->parent )
$trail = array_merge( $trail, ct_breadcrumbs_get_term_parents( $term->parent, $term->taxonomy ) );
/* Add the term name to the trail end. */
$trail['trail_end'] = $term->name;
}
/* If viewing a post type archive. */
elseif ( function_exists( 'is_post_type_archive' ) && is_post_type_archive() ) {
/* Get the post type object. */
$post_type_object = get_post_type_object( get_query_var( 'post_type' ) );
/* If $front has been set, add it to the $path. */
if ( $post_type_object->rewrite['with_front'] && $wp_rewrite->front )
$path .= trailingslashit( $wp_rewrite->front );
/* If there's a slug, add it to the $path. */
if ( !empty( $post_type_object->rewrite['archive'] ) )
$path .= $post_type_object->rewrite['archive'];
/* If there's a path, check for parents. */
if ( !empty( $path ) )
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( '', $path ) );
/* Add the post type [plural] name to the trail end. */
$trail['trail_end'] = $post_type_object->labels->name;
}
/* If viewing an author archive. */
elseif ( is_author() ) {
/* If $front has been set, add it to $path. */
if ( !empty( $wp_rewrite->front ) )
$path .= trailingslashit( $wp_rewrite->front );
/* If an $author_base exists, add it to $path. */
if ( !empty( $wp_rewrite->author_base ) )
$path .= $wp_rewrite->author_base;
/* If $path exists, check for parent pages. */
if ( !empty( $path ) )
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( '', $path ) );
/* Add the author's display name to the trail end. */
$trail['trail_end'] = get_the_author_meta( 'display_name', get_query_var( 'author' ) );
}
/* If viewing a time-based archive. */
elseif ( is_time() ) {
if ( get_query_var( 'minute' ) && get_query_var( 'hour' ) )
$trail['trail_end'] = get_the_time( __( 'g:i a', $textdomain ) );
elseif ( get_query_var( 'minute' ) )
$trail['trail_end'] = sprintf( __( 'Minute %1$s', $textdomain ), get_the_time( __( 'i', $textdomain ) ) );
elseif ( get_query_var( 'hour' ) )
$trail['trail_end'] = get_the_time( __( 'g a', $textdomain ) );
}
/* If viewing a date-based archive. */
elseif ( is_date() ) {
/* If $front has been set, check for parent pages. */
if ( $wp_rewrite->front )
$trail = array_merge( $trail, ct_breadcrumbs_get_parents( '', $wp_rewrite->front ) );
if ( is_day() ) {
$trail[] = '<a href="' . get_year_link( get_the_time( 'Y' ) ) . '" title="' . get_the_time( esc_attr__( 'Y', $textdomain ) ) . '">' . get_the_time( __( 'Y', $textdomain ) ) . '</a>';
$trail[] = '<a href="' . get_month_link( get_the_time( 'Y' ), get_the_time( 'm' ) ) . '" title="' . get_the_time( esc_attr__( 'F', $textdomain ) ) . '">' . get_the_time( __( 'F', $textdomain ) ) . '</a>';
$trail['trail_end'] = get_the_time( __( 'j', $textdomain ) );
}
elseif ( get_query_var( 'w' ) ) {
$trail[] = '<a href="' . get_year_link( get_the_time( 'Y' ) ) . '" title="' . get_the_time( esc_attr__( 'Y', $textdomain ) ) . '">' . get_the_time( __( 'Y', $textdomain ) ) . '</a>';
$trail['trail_end'] = sprintf( __( 'Week %1$s', $textdomain ), get_the_time( esc_attr__( 'W', $textdomain ) ) );
}
elseif ( is_month() ) {
$trail[] = '<a href="' . get_year_link( get_the_time( 'Y' ) ) . '" title="' . get_the_time( esc_attr__( 'Y', $textdomain ) ) . '">' . get_the_time( __( 'Y', $textdomain ) ) . '</a>';
$trail['trail_end'] = get_the_time( __( 'F', $textdomain ) );
}
elseif ( is_year() ) {
$trail['trail_end'] = get_the_time( __( 'Y', $textdomain ) );
}
}
}
/* If viewing search results. */
elseif ( is_search() )
$trail['trail_end'] = sprintf( __( 'Search results for &quot;%1$s&quot;', $textdomain ), esc_attr( get_search_query() ) );
/* If viewing a 404 error page. */
elseif ( is_404() )
$trail['trail_end'] = __( '404 Not Found', $textdomain );
/* Connect the breadcrumb trail if there are items in the trail. */
if ( is_array( $trail ) ) {
/* Open the breadcrumb trail containers. */
$breadcrumb = '<div class="breadcrumb breadcrumbs ct-breadcrumbs right"><div class="breadcrumb-trail">';
/* If $before was set, wrap it in a container. */
if ( !empty( $before ) )
$breadcrumb .= '<span class="trail-before">' . $before . '</span> ';
/* Wrap the $trail['trail_end'] value in a container. */
if ( !empty( $trail['trail_end'] ) )
$trail['trail_end'] = '<span class="trail-end">' . $trail['trail_end'] . '</span>';
/* Format the separator. */
if ( !empty( $separator ) )
$separator = '<span class="sep">' . $separator . '</span>';
/* Join the individual trail items into a single string. */
$breadcrumb .= join( " {$separator} ", $trail );
/* If $after was set, wrap it in a container. */
if ( !empty( $after ) )
$breadcrumb .= ' <span class="trail-after">' . $after . '</span>';
/* Close the breadcrumb trail containers. */
$breadcrumb .= '</div></div>';
}
/* Allow developers to filter the breadcrumb trail HTML. */
$breadcrumb = apply_filters( 'ct_breadcrumbs', $breadcrumb );
/* Output the breadcrumb. */
if ( $echo )
echo $breadcrumb;
else
return $breadcrumb;
}
/*-----------------------------------------------------------------------------------*/
/* Get parents */
/*-----------------------------------------------------------------------------------*/
function ct_breadcrumbs_get_parents( $post_id = '', $path = '' ) {
/* Set up an empty trail array. */
$trail = array();
/* If neither a post ID nor path set, return an empty array. */
if ( empty( $post_id ) && empty( $path ) )
return $trail;
/* If the post ID is empty, use the path to get the ID. */
if ( empty( $post_id ) ) {
/* Get parent post by the path. */
$parent_page = get_page_by_path( $path );
if( empty( $parent_page ) )
// search on page name (single word)
$parent_page = get_page_by_title ( $path );
if( empty( $parent_page ) )
// search on page title (multiple words)
$parent_page = get_page_by_title ( str_replace( array('-', '_'), ' ', $path ) );
/* End Modification */
/* If a parent post is found, set the $post_id variable to it. */
if ( !empty( $parent_page ) )
$post_id = $parent_page->ID;
}
/* If a post ID and path is set, search for a post by the given path. */
if ( $post_id == 0 && !empty( $path ) ) {
/* Separate post names into separate paths by '/'. */
$path = trim( $path, '/' );
preg_match_all( "/\/.*?\z/", $path, $matches );
/* If matches are found for the path. */
if ( isset( $matches ) ) {
/* Reverse the array of matches to search for posts in the proper order. */
$matches = array_reverse( $matches );
/* Loop through each of the path matches. */
foreach ( $matches as $match ) {
/* If a match is found. */
if ( isset( $match[0] ) ) {
/* Get the parent post by the given path. */
$path = str_replace( $match[0], '', $path );
$parent_page = get_page_by_path( trim( $path, '/' ) );
/* If a parent post is found, set the $post_id and break out of the loop. */
if ( !empty( $parent_page ) && $parent_page->ID > 0 ) {
$post_id = $parent_page->ID;
break;
}
}
}
}
}
/* While there's a post ID, add the post link to the $parents array. */
while ( $post_id ) {
/* Get the post by ID. */
$page = get_page( $post_id );
/* Add the formatted post link to the array of parents. */
$parents[] = '<a href="' . get_permalink( $post_id ) . '" title="' . esc_attr( get_the_title( $post_id ) ) . '">' . get_the_title( $post_id ) . '</a>';
/* Set the parent post's parent to the post ID. */
$post_id = $page->post_parent;
}
/* If we have parent posts, reverse the array to put them in the proper order for the trail. */
if ( isset( $parents ) )
$trail = array_reverse( $parents );
/* Return the trail of parent posts. */
return $trail;
}
/*-----------------------------------------------------------------------------------*/
/* Get term parents */
/*-----------------------------------------------------------------------------------*/
function ct_breadcrumbs_get_term_parents( $parent_id = '', $taxonomy = '' ) {
/* Set up some default arrays. */
$trail = array();
$parents = array();
/* If no term parent ID or taxonomy is given, return an empty array. */
if ( empty( $parent_id ) || empty( $taxonomy ) )
return $trail;
/* While there is a parent ID, add the parent term link to the $parents array. */
while ( $parent_id ) {
/* Get the parent term. */
$parent = get_term( $parent_id, $taxonomy );
/* Add the formatted term link to the array of parent terms. */
$parents[] = '<a href="' . get_term_link( $parent, $taxonomy ) . '" title="' . esc_attr( $parent->name ) . '">' . $parent->name . '</a>';
/* Set the parent term's parent as the parent ID. */
$parent_id = $parent->parent;
}
/* If we have parent terms, reverse the array to put them in the proper order for the trail. */
if ( !empty( $parents ) )
$trail = array_reverse( $parents );
/* Return the trail of parent terms. */
return $trail;
} ?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment