I got a WordPress Rating plugin from "http://www.smashingmagazine.com/2012/05/08/adding-custom-fields-in-wordpress-comment-form/"
I would like to count the total number of rating and print that number under the Blog Post. Is this possible?
I added some customisation in this code.
<?php
// Add fields after default fields above the comment box, always visible
add_action( 'comment_form_logged_in_after', 'additional_fields' );
add_action( 'comment_form_after_fields', 'additional_fields' );
function additional_fields () {
echo '<p class="comment-form-rating">'.
'<label for="rating">'. __('Rating') . '<span class="required">*</span></label>
<span class="commentratingbox">';
for( $i=1; $i <= 5; $i++ )
echo '<span class="commentrating"><input type="radio" checked name="rating" id="rating" value="'. $i .'"/>'. $i .' Star</span>';
echo'</span></p>';
}
// Save the comment meta data along with comment
add_action( 'comment_post', 'save_comment_meta_data' );
function save_comment_meta_data( $comment_id ) {
if ( ( isset( $_POST['rating'] ) ) && ( $_POST['rating'] != '') )
$rating = wp_filter_nohtml_kses($_POST['rating']);
add_comment_meta( $comment_id, 'rating', $rating );
}
// Add the filter to check if the comment meta data has been filled or not
add_filter( 'preprocess_comment', 'verify_comment_meta_data' );
function verify_comment_meta_data( $commentdata ) {
if ( ! isset( $_POST['rating'] ) )
wp_die( __( 'Error: You did not add your rating. Hit the BACK button of your Web browser and resubmit your comment with rating.' ) );
return $commentdata;
}
//Add an edit option in comment edit screen
add_action( 'add_meta_boxes_comment', 'extend_comment_add_meta_box' );
function extend_comment_add_meta_box() {
add_meta_box( 'title', __( 'Comment Metadata - Extend Comment' ), 'extend_comment_meta_box', 'comment', 'normal', 'high' );
}
function extend_comment_meta_box ( $comment ) {
$phone = get_comment_meta( $comment->comment_ID, 'phone', true );
$title = get_comment_meta( $comment->comment_ID, 'title', true );
$rating = get_comment_meta( $comment->comment_ID, 'rating', true );
wp_nonce_field( 'extend_comment_update', 'extend_comment_update', false );
?>
<p>
<label for="rating"><?php _e( 'Rating: ' ); ?></label>
<span class="commentratingbox">
<?php for( $i=1; $i <= 5; $i++ ) {
echo '<span class="commentrating"><input type="radio" name="rating" id="rating" value="'. $i .'"';
if ( $rating == $i ) echo ' checked="checked"';
echo ' />'. $i .' </span>';
}
?>
</span>
</p>
<?php
}
// Update comment meta data from comment edit screen
add_action( 'edit_comment', 'extend_comment_edit_metafields' );
function extend_comment_edit_metafields( $comment_id ) {
if( ! isset( $_POST['extend_comment_update'] ) || ! wp_verify_nonce( $_POST['extend_comment_update'], 'extend_comment_update' ) ) return;
if ( ( isset( $_POST['phone'] ) ) && ( $_POST['phone'] != '') ) :
$phone = wp_filter_nohtml_kses($_POST['phone']);
update_comment_meta( $comment_id, 'phone', $phone );
else :
delete_comment_meta( $comment_id, 'phone');
endif;
if ( ( isset( $_POST['title'] ) ) && ( $_POST['title'] != '') ):
$title = wp_filter_nohtml_kses($_POST['title']);
update_comment_meta( $comment_id, 'title', $title );
else :
delete_comment_meta( $comment_id, 'title');
endif;
if ( ( isset( $_POST['rating'] ) ) && ( $_POST['rating'] != '') ):
$rating = wp_filter_nohtml_kses($_POST['rating']);
update_comment_meta( $comment_id, 'rating', $rating );
else :
delete_comment_meta( $comment_id, 'rating');
endif;
}
// Add the comment meta (saved earlier) to the comment text
// You can also output the comment meta values directly in comments template
add_filter( 'comment_text', 'modify_comment');
function modify_comment( $text ){
$plugin_url_path = WP_PLUGIN_URL;
if( $commenttitle = get_comment_meta( get_comment_ID(), 'title', true ) ) {
$commenttitle = '<strong>' . esc_attr( $commenttitle ) . '</strong><br/>';
$text = $commenttitle . $text;
}
if( $commentrating = get_comment_meta( get_comment_ID(), 'rating', true ) ) {
$commentrating = '<p class="comment-rating"> <img src="'. $plugin_url_path .
'/ExtendComment/images/'. $commentrating . 'star.gif"/><br/>Rating: <strong>'. $commentrating .' / 5</strong></p>';
$text = $text . $commentrating;
return $text;
} else {
return $text;
}
}
It would go something like this. Appending the total for all ratings:
if( !is_admin() )
add_filter( 'the_content', 'content_so_23778986' );
function content_so_23778986( $content )
{
if( !is_single() )
return $content;
# Get all comments from current post
$comms = get_comments( array( 'post_id'=>get_the_ID() ) );
$counter = null;
if( $comms )
{
$total = count( $comms );
# Iterate all comments and add its rating to the counter
foreach( $comms as $c )
{
$rating = (int) get_comment_meta( $c->comment_ID, 'rating', true );
$counter += $rating;
}
# Calculate and print the totals
$counter = '<br />' . $counter / $total . ' de 5';
}
return $content . $counter;
}
Related
In Woocommerce I am using Woocommerce Product Add-Ons plugin and I am trying to figure out how I can hide the prices from Add-ons fields.
This is the current output with prices:
This is the desired Output without prices (yellow underlined):
I figured out that the the select.php in product-addons/templates/addons/select.php could be the the solution
I'm bad in php so i try to comment out some things ...
if I comment out line 27 then I have the desired output, but the Price from the addons does not count to the product total price:
$price_raw = apply_filters( 'woocommerce_product_addons_option_price_raw', $price, $option );
The select.php code:
<?php
/**
* The Template for displaying select field.
*
* #version 3.0.0
*/
$loop = 0;
$field_name = ! empty( $addon['field_name'] ) ? $addon['field_name'] : '';
$required = ! empty( $addon['required'] ) ? $addon['required'] : '';
$current_value = isset( $_POST['addon-' . sanitize_title( $field_name ) ] ) ? wc_clean( $_POST[ 'addon-' . sanitize_title( $field_name ) ] ) : '';
?>
<p class="form-row form-row-wide wc-pao-addon-wrap wc-pao-addon-<?php echo sanitize_title( $field_name ); ?>">
<select class="wc-pao-addon-field wc-pao-addon-select" name="addon-<?php echo sanitize_title( $field_name ); ?>" <?php if ( WC_Product_Addons_Helper::is_addon_required( $addon ) ) { echo 'required'; } ?>>
<?php if ( empty( $required ) ) { ?>
<option value=""><?php esc_html_e( 'None', 'woocommerce-product-addons' ); ?></option>
<?php } else { ?>
<option value=""><?php esc_html_e( 'Select an option...', 'woocommerce-product-addons' ); ?></option>
<?php } ?>
<?php foreach ( $addon['options'] as $i => $option ) {
$loop++;
$price = ! empty( $option['price'] ) ? $option['price'] : '';
$price_prefix = 0 < $price ? '+' : '';
$price_type = ! empty( $option['price_type'] ) ? $option['price_type'] : '';
$price_raw = apply_filters( 'woocommerce_product_addons_option_price_raw', $price, $option );
$label = ( '0' === $option['label'] ) || ! empty( $option['label'] ) ? $option['label'] : '';
if ( 'percentage_based' === $price_type ) {
$price_for_display = apply_filters( 'woocommerce_product_addons_option_price',
$price_raw ? '(' . $price_prefix . $price_raw . '%)' : '',
$option,
$i,
'select'
);
} else {
$price_for_display = apply_filters( 'woocommerce_product_addons_option_price',
$price_raw ? '(' . $price_prefix . wc_price( WC_Product_Addons_Helper::get_product_addon_price_for_display( $price_raw ) ) . ')' : '',
$option,
$i,
'select'
);
}
$price_display = WC_Product_Addons_Helper::get_product_addon_price_for_display( $price_raw );
if ( 'percentage_based' === $price_type ) {
$price_display = $price_raw;
}
?>
<option data-raw-price="<?php echo esc_attr( $price_raw ); ?>" data-price="<?php echo esc_attr( $price_display ); ?>" data-price-type="<?php echo esc_attr( $price_type ); ?>" value="<?php echo sanitize_title( $label ) . '-' . $loop; ?>" data-label="<?php echo esc_attr( wptexturize( $label ) ); ?>"><?php echo wptexturize( $label ) . ' ' . $price_for_display; ?></option>
<?php } ?>
</select>
</p>
Any help is appreciated.
Without overriding any template or changing core code, you could try to use one of the following hooked functions:
add_filter( 'woocommerce_product_addons_option_price', '__return_empty_string' );
Or may be if you need to add some IF statements like in this example:
add_filter( 'woocommerce_product_addons_option_price', 'filter_product_addons_option_price', 10, 4 );
function filter_product_addons_option_price( $price, $option, $i, $type ){
global $product;
if( $product->get_id() == 123 && $type = 'select' ) {
$price '';
}
return $price;
}
Code goes in function.php file of your active child theme (or active theme). It should works.
Add this code Functions.php
add_filter( 'woocommerce_get_price_html', 'react2wp_woocommerce_hide_product_price' );
function react2wp_woocommerce_hide_product_price( $price ) {
return 'Rate on Call';
Ask to everyone, i have problem. Here i try to use multiple chechbox to my custom post metabox.
<?php
function prodetail() {
add_meta_box('pro_metabox', 'Detail Property', 'pro_metabox', 'property', 'normal', 'default');
}
function pro_metabox() {
global $post;
echo '<input type="hidden" name="eventmeta_noncename" id="eventmeta_noncename" value="' .
wp_create_nonce( plugin_basename(__FILE__) ) . '" />';
$postmeta = maybe_unserialize( get_post_meta( $post->ID, 'elements', true ) );
$elements = array(
'pool' => 'Pool',
'garage' => 'Garage',
'balcon' => 'Balcon',
'yard' => 'Yard',
'internet' => 'Internet'
);
foreach ( $elements as $id => $element) {
if ( is_array( $postmeta ) && in_array( $id, $postmeta ) ) {
$checked = 'checked="checked"';
} else {
$checked = null;
}
?>
<div class="pro-inn">
<div class="procols">
<div class="pro-inn">
<input type="checkbox" name="multval[]" value="<?php echo $id; ?>" <?php echo $checked; ?> />
<?php echo $element;?>
</div>
</div>
</div>
<?php
}
}
function pro_meta($post_id, $post) {
if ( !wp_verify_nonce( $_POST['eventmeta_noncename'], plugin_basename(__FILE__) )) {
return $post->ID;
}
if ( !current_user_can( 'edit_post', $post->ID ))
return $post->ID;
if ( ! empty( $_POST['multval'] ) ) {
update_post_meta( $post_id, 'elements', $_POST['multval'] );
} else {
delete_post_meta( $post_id, 'elements' );
}
}
add_action('save_post', 'pro_meta', 1, 2);
?>
help me to add code to show this checked result to single.php because my code use foreach just show Array text not show text like Pool Garage Balcon ect.
Thanks
Use this code in your single.php file for your custom post
$meta_value = get_post_meta( $post->ID, 'elements', true );
foreach($meta_value as $key=>$value){
echo $value . ' ';
}
It will show results same as you mentioned in the question ie:
(Pool Garage Balcon ect.)
i'm searching for a way to display the modified date of a custom field / meta box. until now, i only know how to echo
the_modified_date('l, j.n.Y');
but this one only works with the entire post.
i'am using a meta_box for additional pdf files uploading, code:
<?php class PDF_Metabox_id1 {
function __construct() {
add_action( 'post_mime_types', array( $this, 'pdf_mime_type_id1' ) );
add_action( 'add_meta_boxes', array( $this, 'admin_scripts_id1' ), 5 );
add_action( 'add_meta_boxes', array( $this, 'metabox_add_id1' ) );
add_action( 'save_post', array( $this, 'pdf_save_postdata_id1') );
add_action( 'wp_ajax_refresh_pdf', array( $this, 'refresh_pdf_id1' ) ); }
function pdf_mime_type_id1() {
$post_mime_types['application/pdf'] = array( __( 'PDFs' ), __( 'Manage PDFs' ), _n_noop( 'PDF <span class="count">(%s)</span>', 'PDFs <span class="count">(%s)</span>' ) );
return $post_mime_types;
}
function admin_scripts_id1() {
wp_register_script( 'pdf_metabox_js', get_stylesheet_directory_uri() . '/js/pdf_metabox.js' );
}
function metabox_add_id1() {
$post_types = array( 'myposttype','anotherposttype' );
$context = 'normal'; $priority = 'low';
foreach( $post_types as $post_type ) {
add_meta_box( 'pdf_metabox_id1', __( 'PDF Box 1', 'pdf_metabox_id1' ), array( $this, 'pdf_metabox_id1' ), $post_type, $context, $priority );
wp_enqueue_media();
wp_enqueue_script( 'pdf_metabox_js' );
}
}
function pdf_metabox_id1( $post ) {
$original_post = $post; echo $this->pdf_metabox_html_id1( $post->ID ); $post = $original_post;
}
function pdf_item_id1( $id ) {
if(!$id) return; $pdf_url = esc_url_raw(wp_get_attachment_url($id)); $pdf = $pdf_url; return $pdf;
}
function pdf_metabox_html_id1( $post_id ) {
$current_value = ''; $post_meta = get_post_custom($post_id);
if( isset($post_meta['pdf_id_id1'][0] ) ) $current_value = $post_meta['pdf_id_id1'][0];
$return = ''; wp_nonce_field( plugin_basename( __FILE__ ), 'pdf_noncename' );
$return .= '<p>';
$return .= '<a title="'.__( 'PDF', 'pdf_metabox_id1' ).'" class="button button-primary insert-pdf-button" id="insert_pdf_button_id1" href="#" style="float:left">'.__( 'Upload / editiere PDF', 'pdf_metabox_id1' ).'</a><span id="pdf_spinner_id1" class="spinner" style="float:left"></span></p>';
$return .= '<div style="clear:both"></div>';
$return .= '<input type="hidden" name="pdf_id_id1" id="pdf_id_id1" value="'.$current_value.'">';
$return .= '<div style="clear:both"></div>';
$return .= '<div id="pdf_wrapper_id1">';
$pdf = $this->pdf_item_id1( $current_value ); if( empty( $pdf ) ) {
$return .= '<p>Diesem Feld ist kein PDF hinterlegt.</p>'; } else {
$return .= '<br />URL des PDF:<br /> ';
$return .= $pdf; }
$return .= '</div>';
return $return;
}
function pdf_save_postdata_id1($post_id){
if ( isset($_POST['post_type']) && 'post' == $_POST['post_type'] ) {
if ( !current_user_can( 'edit_post', $post_id ) ) return; } if ( !isset( $_POST['pdf_noncename'] ) || ! wp_verify_nonce( $_POST['pdf_noncename'], plugin_basename( __FILE__ ) ) ) return;
if(isset($_POST['pdf_id_id1']) ): update_post_meta($post_id, 'pdf_id_id1', sanitize_text_field( $_POST['pdf_id_id1'] ) );
else: if (isset($post_id)) {
delete_post_meta($post_id, 'pdf_id_id1'); }
endif;
}
function refresh_pdf_id1() {
if(isset($_POST['id'])){
$item = $_POST['id'];
if($item != '' && $item !=0){
$pdf = $this->pdf_item_id1( $item );
$ret = array();
if( !empty( $pdf ) ) {$ret['success'] = true;
$ret['pdf'] = $pdf; } else {
$ret['success'] = false; } } else {
$ret['success'] = true; $ret['pdf'] = ''; } } else {
$ret['success'] = false; } echo json_encode( $ret ); die();
}
}
$PDF_Metabox_id1 = new PDF_Metabox_id1();
in my theme i'm using:
$post_meta_id1 = get_post_custom(get_the_ID());
$pdf_id_id1 = $post_meta_id1['pdf_id_id1'][0];
$pdf_url_id1 = wp_get_attachment_url($pdf_id_id1);
...and now i want to display the modified date of this field. any ideas?
As per the comment
how do i save the modified date of this custom field and how do i get it?
You may need to check every custom field in loop one by one if any of custom fields doesnot matched with the current post data then save a new custom field to post_meta. then retrieve in your template/page.
Just an idea:
<?php
function attributes_save_postdata( $post_id ) {
$postcustom = get_post_custom( $post_id );
$is_modified = false;
foreach ( $postcustom as $key => $val ) {
var_dump( $val );
// check your post custom values and
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
// if database value ($getpostmeta) not equal to current post value($_POST['your_meta_key'])
if ( $getpostmeta != $_POST['your_meta_key'] ) {
$is_modified = true;
// if found any custom field updated set $modified = true
}
}
// if found any custom field updated add or update new date and time
if ( $is_modified ) {
$date = date( 'Y-m-d h:i:s' ); // example : 2016-02-02 12:00:00 current date and time
update_post_meta( $post_id, '_modifieddate', $date );
}
}
add_action( 'save_post', 'attributes_save_postdata' );
Then in your theme. get modified date.
$post_id = get_the_ID();
$getpostmeta = get_post_meta( $post_id, 'your_meta_key', true );
I think that wordpress built-in function about this would help you out even for the custom fields.
<p>Last modified: <?php the_modified_time(); ?></p>
I switched from intelliJ to VIM a few days ago and I have a few problems with my syntax highlighting. I'm mainly working with php and html and in some files some of the ; are marked with a red background (maybe meaning there is an error in my syntax?). This most likely happens when the ; is followed by a comment //. I'm pretty sure there are no errors...
Also a few files do not provide php syntax highlight at all after a blockcomment /**/ until the php tag ?> gets closed.
Any idea what im missing? Also I'd appreciate suggestions on alternatives for syntax highlighting. It's hard to find useful stuff for webdev since VIM isn't that popular in that sector I guess.
Here my current vim settings:
https://github.com/raQai/.vim
I'd appreciate your help
Edit:
Here is the code thats causing the problems:
<?php namespace KF\LINKS;
defined ( 'ABSPATH' ) or die ( 'nope!' );
/**
* Plugin Name: KF Attachment Links
* Description: Adding attatchemts to post, pages and teams (Kong Foos Team Manager)
* Version: 1.0.0
* Author: Patrick Bogdan
* Text Domain: kfl
* License: GPL2
*
* Copyright 2015 Patrick Bogdan
* TODO: Settings for post_types with checkboxes
*/
new KFLinksMetaBox();
class KFLinksMetaBox {
const kfl_key = 'kf-links-information';
function __construct() {
if (is_admin ()) {
add_action ( 'admin_enqueue_scripts', wp_enqueue_style ( 'kfl-admin-style', plugins_url( 'includes/css/admin-styles.css', plugin_basename( __FILE__ ) ) ) );
add_action ( 'admin_enqueue_scripts', wp_enqueue_script ( 'kfl-admin-js', plugins_url( 'includes/js/kfl-admin-scripts.js', plugin_basename( __FILE__ ) ) ) );
add_action ( 'add_meta_boxes', array( &$this, 'kf_links_meta_box_add' ) );
add_action ( 'save_post', array( &$this, 'kf_links_meta_box_save' ) );
}
register_deactivation_hook( __FILE__, array( &$this, 'kf_links_uninstall' ) );
add_filter( 'the_content', array( $this, 'kf_links_add_to_posts' ) );
}
function kf_links_uninstall() {
delete_post_meta_by_key( self::kfl_key );
}
function kf_links_add_to_posts( $content ) {
$links = $this->kf_links_explode( get_post_meta( get_the_ID(), self::kfl_key, true ) );
if ( $links['is_active'] == '1' && count($links['items']) > 0 ) {
$links_html = '';
if ( !empty($links['title']) ) {
$links_html .= '<strong>' . $links['title'] . '</strong>';
}
foreach ( $links['items'] as $link ) {
if ( !empty( $link['name'] ) && !empty( $link['url'] ) ) {
$links_html .= '<br />» ' . $link['name'] . '';
}
}
if ( !empty( $links_html ) ) {
$content .= '<p class="attachment-links">' . $links_html . '</p>';
}
}
return $content;
}
function kf_links_meta_box_add() {
$screens = array( 'post', 'page', 'teams' );
foreach( $screens as $screen)
{
add_meta_box (
'kf_links_meta_box', // id
'Linksammlung', // title
array( &$this, 'kf_links_meta_box_display' ), // callback
$screen, // post_type
'normal', // context
'high' // priority
);
}
}
function kf_links_meta_box_display( $post ) {
wp_nonce_field( 'kf_links_meta_box', 'kf_links_meta_box_nonce' );
$this->kf_links_meta_box_display_html( $post );
}
function kf_links_meta_box_display_html( $post )
{
$post_string = get_post_meta( $post->ID, self::kfl_key, true );
$links = $this->kf_links_explode( $post_string );
?>
<div class="kf-meta-box-checkbox">
<input onClick="kfl_checkboxDivDisplay( this.id, 'kf-links' ); kfl_creaetLinksString();" <?php if ( $links['is_active'] ) echo 'checked '; ?>type="checkbox" id="kf-links-checkbox" value="1" />
<label id="kf-links-checkbox-label" for="kf-links-checkbox">Linksammlung aktivieren</label>
</div>
<div id="kf-links" <?php if ( !$links['is_active'] ) echo 'style="display:none" '; ?>>
<div class="kf-meta-box-full">
<label for="kf-links-title">Titel der Linksammlung</label>
<input onChange="kfl_creaetLinksString()" id="kf-links-title" value="<?php echo $links['title']; ?>" placeholder="Titel der Linksammlung" />
</div>
<div class="kf-links-header">
<label>Name</label>
<label>URL</label>
</div>
<div id="kf-links-items">
<?php
foreach ( $links['items'] as $ID => $arr ) {
$this->kf_links_item_display_html( $ID, $arr, $links['is_active'] );
}
if ( count( $links['items'] ) < 1 ) {
$this->kf_links_item_display_html( 0, array( 'name' => '', 'url' => '' ), false );
}
?>
</div>
<h4>+ Weiteren Link hinzufügen</h4>
<input type="hidden" id="kf-links-counter" value="<?php echo ( ( count($links['items']) < 1 ) ? 1 : count($links['items']) ); ?>" />
<input type="hidden" name="<?php echo self::kfl_key; ?>" id="<?php echo self::kfl_key; ?>" value="<?php echo $post_string; ?>" />
</div>
<?php
}
function kf_links_item_display_html( $ID, $arr, $is_active )
{
?>
<div id="kf-links-item[<?php echo $ID; ?>]" class="kf-links-item">
<input onChange="kfl_creaetLinksString();" value="<?php echo $arr['name']; ?>" <?php if ( $is_active ) echo 'required '; ?>placeholder="Name" />
<input onChange="kfl_creaetLinksString();" value="<?php echo $arr['url']; ?>" <?php if ( $is_active ) echo 'required '; ?>placeholder="http://..." />
<input onClick="kfl_deleteLink( 'kf-links-item[<?php echo $ID; ?>]' ); kfl_creaetLinksString();" value="✗" type="button" class="button button-small button-primary" />
</div>
<?php
}
function kf_links_meta_box_save($post_id)
{
if ( !isset( $_POST['kf_links_meta_box_nonce'] ) || ! wp_verify_nonce( $_POST['kf_links_meta_box_nonce'], 'kf_links_meta_box' )) {
return $post_id;
}
$post_type = get_post_type_object( $_POST['post_type'] );
if ( !current_user_can( $post_type->cap->edit_post, $post_id ) ) {
return;
}
$new_meta_value = ( isset( $_POST[self::kfl_key] ) ? $_POST[self::kfl_key] : '');
update_post_meta( $post_id, self::kfl_key, $new_meta_value );
}
function kf_links_explode( $string )
{
if ( empty($string) || !is_string($string) ) {
$links['is_active'] = 0;
return $links;
}
$explode = explode( ';$;', $string );
$links['is_active'] = ( isset( $explode[0] ) ? $explode[0] : 0 );
$links['title'] = ( isset( $explode[1] ) ? $explode[1] : '' );
$links['items'] = array();
for ( $i = 2; $i < count( $explode ); $i++ ) {
$explode2 = explode( ';?;', $explode[$i] );
$link = array(
'name' => $explode2[0],
'url' => $explode2[1]
);
$links['items'][] = $link;
}
return $links;
}
}
And here some screenshots:
https://www.dropbox.com/sh/jj3gluc7ok001hu/AABq_hRiKcbbDo1E0rKpP2Jxa?dl=0
Try :syntax sync fromstart.
If that works, add autocmd BufEnter * :syntax sync fromstart to your .vimrc
Explanation: if the syntax highlighter does not process every line of code from the beginning, it may not receive a critical piece of information to understand what type of code it's processing. E.g., if you're in an HTML file and deep within a script tag, the syntax highlighter may not look back far enough to see the script tag and therefore processes your JS code as HTML.
I have a premium WordPress theme which has breadcrumbs by default, but it does not show Category (and Sub-Category) item when on post page: Home > Category > Sub-Category > Post Title
Instead it just displays like this: Home > Post Title
This is the function which handles breadcrumbs:
(I marked the part of the code that I think is important with this sign, to save you time: ==========>>)
// BREADCRUMBS
if ( ! function_exists( 'ishyoboy_get_breadcrumbs' ) ) {
function ishyoboy_get_breadcrumbs() {
global $ish_options, $ish_woo_id;
$return = '';
$return .= '<div class="ish-pb-breadcrumbs"><div><div>' . "\n";
if ( ! is_front_page() ) {
if ( function_exists('is_woocommerce') ) {
if ( !is_woocommerce() && !is_woocommerce_page() ){
$return .= '<a class="ish-pb-breadcrumbs-home" href="';
$return .= home_url();
$return .= '">';
$return .= '<span>' . __( 'Home', 'ishyoboy' ) . '</span>';
$return .= "</a> > ";
}
}
else{
$return .= '<a class="ish-pb-breadcrumbs-home" href="';
$return .= home_url();
$return .= '">';
$return .= '<span>' . __( 'Home', 'ishyoboy' ) . '</span>';
$return .= "</a> > ";
}
}
else {
$return .= '<span class="ish-pb-breadcrumbs-home">';
$return .= '<span>' . __( 'Home', 'ishyoboy' ) . '</span>';
$return .= "</span>";
}
if ( !is_front_page() && is_home() ) {
global $page;
$return .= $page->post_title;
}
if ( is_archive() && 'post' == get_post_type() && ! is_category() && ( !function_exists('is_woocommerce') || !is_woocommerce() ) ) {
$hpage = get_page( get_option( 'page_for_posts' ) );
if ( 'page' == get_option('show_on_front') && isset($hpage) && '' != $hpage ){
$return .= get_page_parents($hpage->ID, TRUE, ' > ', FALSE );
}
if ( is_day() ) :
$return .= sprintf( __( 'Daily Archives: %s', 'ishyoboy' ), '<span>' . get_the_date() . '</span>' );
elseif ( is_month() ) :
$return .= sprintf( __( 'Monthly Archives: %s', 'ishyoboy' ), '<span>' . get_the_date( _x( 'F Y', 'monthly archives date format', 'ishyoboy' ) ) . '</span>' );
elseif ( is_year() ) :
$return .= sprintf( __( 'Yearly Archives: %s', 'ishyoboy' ), '<span>' . get_the_date( _x( 'Y', 'yearly archives date format', 'ishyoboy' ) ) . '</span>' );
else :
$return .= __( 'Archives', 'ishyoboy' );
endif;
}
else if ( is_archive() && 'post' != get_post_type() && ( !function_exists('is_woocommerce') || !is_woocommerce() ) ) {
$type = get_post_type( get_the_ID() );
$obj = get_post_type_object( $type );
if ( is_object( $obj ) ){
$return .= $obj->labels->name;
}
}
if ( (is_category() || is_single()) && ( ( !function_exists('is_woocommerce_page') || !function_exists('is_woocommerce' ) ) || ( !is_woocommerce() && !is_woocommerce_page() ) ) ) {
$post_id = ish_get_the_ID();
$post_type = get_post_type();
switch ($post_type){
case 'portfolio-post' :
$terms = get_the_terms($post_id, 'portfolio-category' );
$term = ( ! empty( $terms ) ) ? array_pop($terms) : '';
if (isset($ish_options['page_for_custom_post_type_portfolio-post']) && '-1' != $ish_options['page_for_custom_post_type_portfolio-post']){
$portfolio_page = get_page($ish_options['page_for_custom_post_type_portfolio-post']);
$separator = " > ";
$return .= ''.$portfolio_page->post_title.'' . $separator;
}
if ( ! empty( $term ) ){
$return .= get_term_parents($term->term_id, 'portfolio-category', TRUE, ' > ', FALSE );
}
break;
// from here ==========>>
case 'post' :
if ( is_category() ){
global $cat;
$category = get_category($cat);
if ( $category->parent && ( $category->parent != $category->term_id ) ){
$return .= get_category_parents($category->parent, TRUE, ' > ', FALSE );
}
$return .= single_cat_title('', false);
}
else{
$category = get_the_category();
if ( is_object( $category ) ){
$ID = $category[0]->cat_ID;
$return .= get_category_parents($ID, TRUE, ' > ', FALSE );
}
}
break;
// to here ==========>>
default :
$type = get_post_type( get_the_ID() );
$obj = get_post_type_object( $type );
if ( is_object( $obj ) ){
$return .= '' . $obj->labels->name . ' > ';
}
}
}
else if ( ( function_exists('is_woocommerce_page') && function_exists('is_woocommerce') ) && (is_woocommerce() || is_woocommerce_page() )){
ob_start();
woocommerce_breadcrumb(array(
'delimiter' => ' > ',
'wrap_before' => '',
'wrap_after' => '',
'before' => '',
'after' => '',
'home' => '<span class="ish-pb-breadcrumbs-home"><span>' . _x( 'Home', 'breadcrumb', 'woocommerce' ) . '</span></span>',
));
$return .= ob_get_contents();
ob_end_clean();
ob_end_flush();
}
else if (is_tax()){
if (is_tax('portfolio-category')){
$current_term = get_queried_object();
if ( !empty($current_term) ){
//var_dump($current_term);
if (isset($ish_options['page_for_custom_post_type_portfolio-post']) && '-1' != $ish_options['page_for_custom_post_type_portfolio-post']){
$portfolio_page = get_page($ish_options['page_for_custom_post_type_portfolio-post']);
$separator = " > ";
$return .= ''.$portfolio_page->post_title.'' . $separator;
}
if ($current_term->parent != 0 ){
$return .= get_term_parents($current_term->parent, 'portfolio-category', TRUE, ' > ', FALSE );
}
$return .= $current_term->name;
}
}
}
else if (is_page()){
global $post;
if ($post->post_parent != 0 ){
$return .= get_page_parents($post->post_parent, TRUE, ' > ', FALSE );
}
}
if (!function_exists('is_woocommerce_page') || !is_woocommerce_page()){
if(is_single()) {$return .= get_the_title();}
if(is_page()) {
global $post;
$frontpage = get_option('page_on_front');
if ( $frontpage && $frontpage == $post->ID){
/*$return .= '<a class="home" href="';
$return .= home_url();
$return .= '">';
$return .= '<span>' . __( 'Home', 'ishyoboy' ) . '</span>';
$return .= "</a>";*/
} else {
$return .= get_the_title();
}
}
if(is_tag()){ $return .= __( 'Tag: ', 'ishyoboy' ) . single_tag_title('',FALSE); }
if(is_404()){ $return .= __( '404 - Page not Found', 'ishyoboy' ); }
if(is_search()){ $return .= __( 'Search', 'ishyoboy' ); }
if(is_year()){ $return .= get_the_time('Y'); };
}
$return .= '</div></div></div>';
return $return;
}
}
if ( !function_exists('the_post_thumbnail_caption') ) {
function the_post_thumbnail_caption(){
$thumb = get_post_thumbnail_id();
if ( ! empty( $thumb ) ){
$thumb_object = get_post( $thumb );
if ( ! empty( $thumb_object ) ) {
echo '<div class="wp-caption"><p class="wp-caption-text">' . $thumb_object->post_excerpt . '</p></div>';
}
}
}
}
if ( !function_exists('get_the_post_thumbnail_caption') ) {
function get_the_post_thumbnail_caption(){
$thumb = get_post_thumbnail_id();
if ( ! empty( $thumb ) )
return get_post( $thumb )->post_excerpt;
return null;
}
}
if ( ! function_exists( 'ishyoboy_activate_fancybox_on_blog_single' ) ) {
function ishyoboy_activate_fancybox_on_blog_single() {
if ( is_singular() && !is_singular( 'product' ) ){
?>
<script type="text/javascript">
jQuery(document).ready(function($){
var thumbnails = jQuery("a:has(img)").not(".nolightbox").filter( function() { return /\.(jpe?g|png|gif|bmp)$/i.test(jQuery(this).attr('href')) });
if ( thumbnails.length > 0){
thumbnails.addClass( 'openfancybox-image' ).attr( 'rel', 'fancybox-post-image-<?php the_ID() ?>');
}
});
</script>
<?php
}
}
}
add_action( 'wp_head', 'ishyoboy_activate_fancybox_on_blog_single' );
if ( ! function_exists( 'ishyoboy_dummy_functions' ) ) {
function ishyoboy_dummy_functions() {
if ( false ) {
posts_nav_link();
wp_link_pages();
$args = '';
add_theme_support( 'custom-header', $args );
add_theme_support( 'custom-background', $args );
}
}
}
And then I've made a change in code which generated the desired change - Category appeared in breadcrumbs: Home > Category > Sub-Category > Post Title
But on the Category archive page breadcrumbs look like this: Home > Category > Category
Live example: http://pigtelligent.com/science/
The change I've made in above-mentioned code:
case 'post' :
$terms = get_the_terms($post_id, 'category' );
$term = ( ! empty( $terms ) ) ? array_pop($terms) : '';
if ( ! empty( $term ) ){
$return .= get_term_parents($term->term_id, 'category', TRUE, ' > ', FALSE );
}
I know that for someone smarter this should be easy, but I've spent whole day trying to figure this out, so can you please help me? :)
Categories can get tricky fast as posts can have multiple categories, and category landing pages can access a lot of meta which can get misleading. Make sure you've reviewed the Template Hierarchy page on the codex and you've got a firm understanding of how WP handles taxonomy.
Use What The File to find out what template you're actually on as you might not be on a category page, causing is_category() to return false. You could be on a single (as the if statement wrapping the logic you pointed out is checking is_category() || is_single()), or you might need to add a check for is_archive().
My best suggestion is to figure out if you're on a category page first, then stop all that extra logic and just spit out the category's name. Not too much help, I know, but hopefully that'll point you in the right direction
function the_breadcrumb() {
global $post;
echo '<ul id="breadcrumbs">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo '</a></li><li class="separator"> / </li>';
if (is_category() || is_single()) {
echo '<li>';
the_category(' </li><li class="separator"> / </li><li> ');
if (is_single()) {
echo '</li><li class="separator"> / </li><li>';
the_title();
echo '</li>';
}
} elseif (is_page()) {
if($post->post_parent){
$anc = get_post_ancestors( $post->ID );
$title = get_the_title();
foreach ( $anc as $ancestor ) {
$output = '<li>'.get_the_title($ancestor).'</li> <li class="separator">/</li>';
}
echo $output;
echo '<strong title="'.$title.'"> '.$title.'</strong>';
} else {
echo '<li><strong> '.get_the_title().'</strong></li>';
}
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ul>';
}
?>
Get using: <?php the_breadcrumb(); ?>