How to make a change to a file in wp-includes? - wordpress

I'm using the Hestia theme. I created a child theme for Hestia.
Hestia theme
wp-content/themes/hestia
Child Theme
wp-content/themes/hestia-child
I need to make a change in the file wp-includes/general-template.php
How Can I make the change below without directly altering the file from wp-includes?
wp-content/themes/hestia/archive.php
<?php the_archive_title( '<h1 class="hestia-title">', '</h1>' ); ?>
wp-includes/general-template.php
// This function calls get_the_archive_title
function the_archive_title( $before = '', $after = '' ) {
$title = get_the_archive_title();
if ( ! empty( $title ) ) {
echo $before . $title . $after;
}
}
// Original
function get_the_archive_title() {
if ( is_author() ) {
$title = sprintf( __( 'Author: %s' ), '<span class="vcard">' . get_the_author() . '</span>' );
}
}
// What I need to change - 'Author: %s' to '%s'
function get_the_archive_title() {
if ( is_author() ) {
$title = sprintf( __( '%s' ), '<span class="vcard">' .get_the_author() . '</span>' );
}
}

Some "filter" and "hook" putting this in your functions.php :
Please check below reference link.
Link1 :- https://wordpress.stackexchange.com/questions/60605/function-to-change-a-label-username-in-a-core-wordpress-file-wp-includes-gene/60607?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
Link2 :- https://wordpress.stackexchange.com/questions/255677/how-to-modify-files-inside-wp-includes-directory-in-wordpress?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa
add_filter( 'get_the_archive_title', function ( $title ) {
if( is_category() ) {
$title = single_cat_title( '', false );
}
return $title;
});

Related

programmatically serve different images for shop and category pages in woocommerce

Hi – is it possible to serve a different image, than the predefined woocommerce thumbnails for the shop and category pages in a programmatical manner? For instance a different image that shows a product detail? Without digging into the code, my guess is to add to the product-image, another field labeled product-detail-image. In this field i can choose, from the media library, the detail image for a given product. Then assign a custom-size in functions.php and finally fetch the image in the appropriate place with something like this:
$product->get_image('detail_img_size');
Thanks for any hint.
It is possible with the following steps:
add an additional image meta box, source (applause for this):
//in functions.php or plugin
add_action( 'add_meta_boxes', 'detail_image_add_metabox' );
function detail_image_add_metabox () {
add_meta_box( 'listingimagediv', __( 'Detail-Bild', 'text-domain' ), 'detail_image_metabox', 'product', 'side', 'low');//post, page, product
}
function detail_image_metabox ( $post ) {
global $content_width, $_wp_additional_image_sizes;
$image_id = get_post_meta( $post->ID, '_detail_image_id', true );
$old_content_width = $content_width;
$content_width = 254;
if ( $image_id && get_post( $image_id ) ) {
if ( ! isset( $_wp_additional_image_sizes['post-thumbnail'] ) ) {
$thumbnail_html = wp_get_attachment_image( $image_id, array( $content_width, $content_width ) );
} else {
$thumbnail_html = wp_get_attachment_image( $image_id, 'post-thumbnail' );
}
if ( ! empty( $thumbnail_html ) ) {
$content = $thumbnail_html;
$content .= '<p class="hide-if-no-js"><a href="javascript:;" id="remove_listing_image_button" >' . esc_html__( 'Entferne das Detail-Bild', 'text-domain' ) . '</a></p>';
$content .= '<input type="hidden" id="upload_listing_image" name="_product_detail_image" value="' . esc_attr( $image_id ) . '" />';
}
$content_width = $old_content_width;
} else {
$content = '<img src="" style="width:' . esc_attr( $content_width ) . 'px;height:auto;border:0;display:none;" />';
$content .= '<p class="hide-if-no-js"><a title="' . esc_attr__( 'wähle das Detail-Bild', 'text-domain' ) . '" href="javascript:;" id="upload_listing_image_button" id="set-listing-image" data-uploader_title="' . esc_attr__( 'Wähle ein Detail-Bild', 'text-domain' ) . '" data-uploader_button_text="' . esc_attr__( 'wähle das Detail-Bild', 'text-domain' ) . '">' . esc_html__( 'wähle das Detail-Bild', 'text-domain' ) . '</a></p>';
$content .= '<input type="hidden" id="upload_listing_image" name="_product_detail_image" value="" />';
}
echo $content;
}
add_action( 'save_post_product', 'detail_image_save', 10, 1 );
function detail_image_save ( $post_id ) {
//check if the image is set and not empty
if( isset( $_POST['_product_detail_image'] ) && !empty($_POST['_product_detail_image']) ) {
$image_id = (int) $_POST['_product_detail_image'];
echo $image_id;
update_post_meta( $post_id, '_detail_image_id', $image_id );
} else {
//else delete the post meta
delete_post_meta($post_id, '_detail_image_id');
}
}
This creates an image meta box on the product edit screen.
add a script that communicates with the media library:
jQuery(document).ready(function($) {
// Uploading files
var file_frame;
jQuery.fn.upload_listing_image = function( button ) {
var button_id = button.attr('id');
var field_id = button_id.replace( '_button', '' );
// If the media frame already exists, reopen it.
if ( file_frame ) {
file_frame.open();
return;
}
// Create the media frame.
file_frame = wp.media.frames.file_frame = wp.media({
title: jQuery( this ).data( 'uploader_title' ),
button: {
text: jQuery( this ).data( 'uploader_button_text' ),
},
multiple: false
});
// When an image is selected, run a callback.
file_frame.on( 'select', function() {
var attachment = file_frame.state().get('selection').first().toJSON();
jQuery("#"+field_id).val(attachment.id);
jQuery("#listingimagediv img").attr('src',attachment.url);
jQuery( '#listingimagediv img' ).show();
jQuery( '#' + button_id ).attr( 'id', 'remove_listing_image_button' );
jQuery( '#remove_listing_image_button' ).text( 'enterne das Detail-Bild' );
});
// Finally, open the modal
file_frame.open();
};
jQuery('#listingimagediv').on( 'click', '#upload_listing_image_button', function( event ) {
event.preventDefault();
jQuery.fn.upload_listing_image( jQuery(this) );
});
jQuery('#listingimagediv').on( 'click', '#remove_listing_image_button', function( event ) {
event.preventDefault();
jQuery( '#upload_listing_image' ).val( '' );
jQuery( '#listingimagediv img' ).attr( 'src', '' );
jQuery( '#listingimagediv img' ).hide();
jQuery( this ).attr( 'id', 'upload_listing_image_button' );
jQuery( '#upload_listing_image_button' ).text( 'wähle das Detail-Bild' );
});
});
enqueue the script in functions.php or plugin:
//load script only for product admin
function load_admin_metabox_script() {
$current_screen = get_current_screen();
if ( $current_screen->post_type === 'product' ) {
wp_enqueue_script( 'zcustom_js', get_template_directory_uri() . '/js/image_meta_box.js', array( 'jquery' ));
}
}
add_action( 'admin_enqueue_scripts', 'load_admin_metabox_script' );
assign images to the loop running for the shop and category pages:
//in functions.php or plugin
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10 );
add_action( 'woocommerce_before_shop_loop_item_title', 'custom_loop_product_detail_thumbnail', 10 );
function custom_loop_product_detail_thumbnail() {
global $product;
$id = $product->get_id();
$size = 'woocommerce_thumbnail';
$detail_img_id = get_post_meta( $id , '_detail_image_id', true );
//check if image id is available and not empty
if (isset($detail_img_id) && !empty($detail_img_id)){
$detail_img = wp_get_attachment_image( $detail_img_id, $size );
echo $detail_img;
//else fallback to the original product image
} else {
$image_size = apply_filters( 'single_product_archive_thumbnail_size', $size );
echo $product ? $product->get_image( $image_size ) : '';
}
}
The same is applicable for the product widget. Just alter the template content-widget-product.php by overriding it in your child theme.
<!-- get detail images-->
<?php $id = $product->get_id();
//i use a custom size
$size = 'my_small_size';
$detail_img_id = get_post_meta( $id , '_detail_image_id', true );
if (isset($detail_img_id) && !empty($detail_img_id)){
$detail_img = wp_get_attachment_image( $detail_img_id, $size );
echo $detail_img;
} else {
//if detail images are not available use the original product image
echo $product->get_image('my_small_size'); // PHPCS:Ignore WordPress.Security.EscapeOutput.OutputNotEscaped
}
?>
This method allows to use a different set of product images for the shop and category pages. It may enhance the visibility of important product features and adds visual variety, at least it does it for my project.

How to display parent page of custom post type ( if have any ) inside the single post of respective custom post type?

I have a custom post type (a child page of a parent page called about). I want to display breadcrumbs like
home >> parent-page-name-of-custom-post-type >> custom-post-type-singular-name >> current single post name
I am currently using this function to display breadcrumbs, however it only displays:
home >> custom-post-type-singular-name >> current single post name
function get_hansel_and_gretel_breadcrumbs()
{
// Set variables for later use
$here_text = __( 'You are currently here!' );
$home_link = home_url('/');
$home_text = __( 'Home' );
$link_before = '<span typeof="v:Breadcrumb">';
$link_after = '</span>';
$link_attr = ' rel="v:url" property="v:title"';
$link = $link_before . '<a' . $link_attr . ' href="%1$s">%2$s</a>' . $link_after;
$delimiter = ' » '; // Delimiter between crumbs
$before = '<span class="current">'; // Tag before the current crumb
$after = '</span>'; // Tag after the current crumb
$page_addon = ''; // Adds the page number if the query is paged
$breadcrumb_trail = '';
$category_links = '';
/**
* Set our own $wp_the_query variable. Do not use the global variable version due to
* reliability
*/
$wp_the_query = $GLOBALS['wp_the_query'];
$queried_object = $wp_the_query->get_queried_object();
// Handle single post requests which includes single pages, posts and attatchments
if ( is_singular() )
{
/**
* Set our own $post variable. Do not use the global variable version due to
* reliability. We will set $post_object variable to $GLOBALS['wp_the_query']
*/
$post_object = sanitize_post( $queried_object );
// Set variables
$title = apply_filters( 'the_title', $post_object->post_title );
$parent = $post_object->post_parent;
$post_type = $post_object->post_type;
$post_id = $post_object->ID;
$post_link = $before . $title . $after;
$parent_string = '';
$post_type_link = '';
if ( 'post' === $post_type )
{
// Get the post categories
$categories = get_the_category( $post_id );
if ( $categories ) {
// Lets grab the first category
$category = $categories[0];
$category_links = get_category_parents( $category, true, $delimiter );
$category_links = str_replace( '<a', $link_before . '<a' . $link_attr, $category_links );
$category_links = str_replace( '</a>', '</a>' . $link_after, $category_links );
}
}
if ( !in_array( $post_type, ['post', 'page', 'attachment'] ) )
{
$post_type_object = get_post_type_object( $post_type );
$archive_link = esc_url( get_post_type_archive_link( $post_type ) );
$post_type_link = sprintf( $link, $archive_link, $post_type_object->labels->singular_name );
}
// Get post parents if $parent !== 0
if ( 0 !== $parent )
{
$parent_links = [];
while ( $parent ) {
$post_parent = get_post( $parent );
$parent_links[] = sprintf( $link, esc_url( get_permalink( $post_parent->ID ) ), get_the_title( $post_parent->ID ) );
$parent = $post_parent->post_parent;
}
$parent_links = array_reverse( $parent_links );
$parent_string = implode( $delimiter, $parent_links );
}
// Lets build the breadcrumb trail
if ( $parent_string ) {
$breadcrumb_trail = $parent_string . $delimiter . $post_link;
} else {
$breadcrumb_trail = $post_link;
}
if ( $post_type_link )
$breadcrumb_trail = $post_type_link . $delimiter . $breadcrumb_trail;
if ( $category_links )
$breadcrumb_trail = $category_links . $breadcrumb_trail;
}
// Handle archives which includes category-, tag-, taxonomy-, date-, custom post type archives and author archives
if( is_archive() )
{
if ( is_category()
|| is_tag()
|| is_tax()
) {
// Set the variables for this section
$term_object = get_term( $queried_object );
$taxonomy = $term_object->taxonomy;
$term_id = $term_object->term_id;
$term_name = $term_object->name;
$term_parent = $term_object->parent;
$taxonomy_object = get_taxonomy( $taxonomy );
$current_term_link = $before . $taxonomy_object->labels->singular_name . ': ' . $term_name . $after;
$parent_term_string = '';
if ( 0 !== $term_parent )
{
// Get all the current term ancestors
$parent_term_links = [];
while ( $term_parent ) {
$term = get_term( $term_parent, $taxonomy );
$parent_term_links[] = sprintf( $link, esc_url( get_term_link( $term ) ), $term->name );
$term_parent = $term->parent;
}
$parent_term_links = array_reverse( $parent_term_links );
$parent_term_string = implode( $delimiter, $parent_term_links );
}
if ( $parent_term_string ) {
$breadcrumb_trail = $parent_term_string . $delimiter . $current_term_link;
} else {
$breadcrumb_trail = $current_term_link;
}
} elseif ( is_author() ) {
$breadcrumb_trail = __( 'Author archive for ') . $before . $queried_object->data->display_name . $after;
} elseif ( is_date() ) {
// Set default variables
$year = $wp_the_query->query_vars['year'];
$monthnum = $wp_the_query->query_vars['monthnum'];
$day = $wp_the_query->query_vars['day'];
// Get the month name if $monthnum has a value
if ( $monthnum ) {
$date_time = DateTime::createFromFormat( '!m', $monthnum );
$month_name = $date_time->format( 'F' );
}
if ( is_year() ) {
$breadcrumb_trail = $before . $year . $after;
} elseif( is_month() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$breadcrumb_trail = $year_link . $delimiter . $before . $month_name . $after;
} elseif( is_day() ) {
$year_link = sprintf( $link, esc_url( get_year_link( $year ) ), $year );
$month_link = sprintf( $link, esc_url( get_month_link( $year, $monthnum ) ), $month_name );
$breadcrumb_trail = $year_link . $delimiter . $month_link . $delimiter . $before . $day . $after;
}
} elseif ( is_post_type_archive() ) {
$post_type = $wp_the_query->query_vars['post_type'];
$post_type_object = get_post_type_object( $post_type );
$breadcrumb_trail = $before . $post_type_object->labels->singular_name . $after;
}
}
// Handle the search page
if ( is_search() ) {
$breadcrumb_trail = __( 'Search query for: ' ) . $before . get_search_query() . $after;
}
// Handle 404's
if ( is_404() ) {
$breadcrumb_trail = $before . __( 'Error 404' ) . $after;
}
// Handle paged pages
if ( is_paged() ) {
$current_page = get_query_var( 'paged' ) ? get_query_var( 'paged' ) : get_query_var( 'page' );
$page_addon = $before . sprintf( __( ' ( Page %s )' ), number_format_i18n( $current_page ) ) . $after;
}
$breadcrumb_output_link = '';
$breadcrumb_output_link .= '<div class="breadcrumb">';
if ( is_home()
|| is_front_page()
) {
// Do not show breadcrumbs on page one of home and frontpage
if ( is_paged() ) {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '' . $home_text . '';
$breadcrumb_output_link .= $page_addon;
}
} else {
$breadcrumb_output_link .= $here_text . $delimiter;
$breadcrumb_output_link .= '' . $home_text . '';
$breadcrumb_output_link .= $delimiter;
$breadcrumb_output_link .= $breadcrumb_trail;
$breadcrumb_output_link .= $page_addon;
}
$breadcrumb_output_link .= '</div><!-- .breadcrumbs -->';
return $breadcrumb_output_link;
}
echo get_hansel_and_gretel_breadcrumbs();
Source of this code : https://wordpress.stackexchange.com/a/221476/181412
Thank you.

Is it safe to remove/modify default WordPress classes/templates to implement BEM?

I am creating a WordPress theme using BEM methodology for public release. To implement BEM methodology, I am removing/modifying some default WordPress templates and classes. For example, to implement BEM methodology in post comment list, I have created custom walker class:
<?php
// Walker class used to create an HTML list of comments.
class BEM_Walker_Comment extends Walker_Comment {
// Starts the list before the elements are added.
public function start_lvl( &$output, $depth = 0, $args = array() ) {
$GLOBALS['comment_depth'] = $depth + 1;
$output .= '<ol class="comment__children">' . "\n";
}
// Ends the list of items after the elements are added.
public function end_lvl( &$output, $depth = 0, $args = array() ) {
$GLOBALS['comment_depth'] = $depth + 1;
$output .= "</ol>\n";
}
// Starts the element output.
public function start_el( &$output, $comment, $depth = 0, $args = array(), $id = 0 ) {
$depth++;
$GLOBALS['comment_depth'] = $depth;
$GLOBALS['comment'] = $comment;
if ( ! empty( $args['callback'] ) ) {
ob_start();
call_user_func( $args['callback'], $comment, $args, $depth );
$output .= ob_get_clean();
return;
}
if ( ( 'pingback' === $comment->comment_type || 'trackback' === $comment->comment_type ) && $args['short_ping'] ) {
ob_start();
$this->ping( $comment, $depth, $args );
$output .= ob_get_clean();
} else {
ob_start();
$this->html5_comment( $comment, $depth, $args );
$output .= ob_get_clean();
}
}
// Ends the element output, if needed.
public function end_el( &$output, $comment, $depth = 0, $args = array() ) {
if ( ! empty( $args['end-callback'] ) ) {
ob_start();
call_user_func( $args['end-callback'], $comment, $args, $depth );
$output .= ob_get_clean();
return;
}
$output .= "</li>\n";
}
// Outputs a comment in the HTML5 format.
protected function html5_comment( $comment, $depth, $args ) {
?>
<li <?php $this->comment_class( $this->has_children ? 'comment__parent' : '', $comment ); ?>>
<article class="comment__body">
<footer class="comment__meta">
<div class="comment__author">
<?php
if ( 0 !== $args['avatar_size'] ) {
echo get_avatar( $comment, $args['avatar_size'] );
}
$url = get_comment_author_url( $comment );
$author = get_comment_author( $comment );
if ( empty( $url ) || 'http://' === $url ) {
$author_name = $author;
} else {
$author_name = '<a class="comment__author-url" href="' . esc_url( $url ) . '" rel="external nofollow">' . esc_html( $author ) . '</a>';
}
printf( '<b class="comment__author-name">%s</b>', $author_name );
?>
</div>
<div class="comment-metadata">
<a href="<?php echo esc_url( get_comment_link( $comment, $args ) ); ?>">
<time datetime="<?php comment_time( 'c' ); ?>">
<?php printf( __( '%1$s at %2$s', 'runway' ), get_comment_date( '', $comment ), get_comment_time() ); ?>
</time>
</a>
<?php edit_comment_link( __( 'Edit', 'runway' ), '<span class="comment__edit">', '</span>' ); ?>
</div>
<?php if ( '0' === $comment->comment_approved ) : ?>
<p class="comment-awaiting-moderation"><?php esc_html_e( 'Your comment is awaiting moderation.', 'runway' ); ?></p>
<?php endif; ?>
</footer>
<div class="comment__content">
<?php comment_text(); ?>
</div>
<?php
comment_reply_link( array_merge( $args, array(
'add_below' => 'div-comment',
'depth' => $depth,
'max_depth' => $args['max_depth'],
'before' => '<div class="comment__reply">',
'after' => '</div>',
) ) );
?>
</article>
<?php
}
// Generates semantic classes for each comment element.
protected function comment_class( $class = '', $comment = null, $post_id = null, $echo = true ) {
$classes = join( ' ', get_comment_class( $class, $comment, $post_id ) );
$classes = str_replace( ' byuser', ' comment--by-user', $classes );
$classes = str_replace( ' comment-author-',' comment--author-', $classes );
$classes = str_replace( ' bypostauthor', ' comment--by-post-author', $classes );
$classes = str_replace( ' odd', ' comment--odd', $classes );
$classes = str_replace( ' alt', ' comment--alt', $classes );
$classes = str_replace( ' even', ' comment--even', $classes );
$classes = str_replace( ' thread-odd', ' comment--thread-odd', $classes );
$classes = str_replace( ' thread-alt', ' comment--thread-alt', $classes );
$classes = str_replace( ' thread-even', ' comment--thread-even', $classes );
$classes = str_replace( ' depth-', ' comment--depth-', $classes );
// Separates classes with a single space, collates classes for comment DIV.
$class = 'class="' . $classes . '"';
if ( $echo ) {
echo $class;
} else {
return $class;
}
}
} // BEM_Walker_Comment class
?>
Similarly, I have also created walker class for Navigation menu, and modified comment form to implement BEM methodology.
But is it safe to remove/modify default WordPress classes and templates?
But is it safe to remove/modify default WordPress classes and templates?
Yes!
I use BEM for my WordPress templates and I remove all the original CSS classes from WordPress. The only things we need to keep are:
id="s" for the search field;
Several elements in the comments, including the id="com-{commentId}" on comment items, it is used by a JS helper from WordPress to move the "reply" field.

Trim title at side bare

My wordpress theme has a "save post as a favortite" function. And it marks the post as a favorite at side bar. but it wont shorten the title. the long titles at sidebar looks messy. in function i use:
function short_title( $after = '', $length ) {
$mytitle = get_the_title();
if( mb_strlen( $mytitle ) > $length ) {
$mytitle = mb_substr( $mytitle, 0, $length );
echo $mytitle . $after;
} else echo $mytitle;
}
and i call it with:
<?php short_title( '...', 99 ); ?>
how can i put short_title in to here:
echo '</p>';
echo '<h4>' . stripslashes( strip_tags( $post_obj_fave->post_title ) ) . '</h4>';
echo '<p class="info">';
You need to apply the shorten title function to $post_obj_fave->post_title
So change your code from:
echo '<h4>' . stripslashes( strip_tags( $post_obj_fave->post_title ) ) . '</h4>';
To:
echo '<h4>' . stripslashes( strip_tags( shorten_title($post_obj_fave->post_title, $length=99) ) ) . '</h4>';
Now create a function for shorten_title()
Here it is:
function shorten_title($var, $length ) {
if( mb_strlen( $var ) > $length ) {
$var= mb_substr( $var, 0, $length );
return $var;
} else return $var;
}
This should shorten the passed variable ($post_obj_fave->post_title) in this case according to associated length.

Exclude Terms from custom Taxonomy?

I have a custom post type in which I have custom taxonomies setup.
I want to print out the categories(custom taxonomy) that a post is included in, but exclude one. I cannot find a solution to exclude the category though.
Here is my code to output a list of the categories the custom post type is filed under:
<?php the_terms( $post->ID, 'critter_cat', 'Critter Type: ', ', ', ' ' ); ?>
How do I exclude a specific category?
Thanks.
You could create a function in your functions.php file that calls get_the_terms to return the list of terms as an array and then remove the item you don't want.
Give this a try:
function get_excluded_terms( $id = 0, $taxonomy, $before = '', $sep = '', $after = '', $exclude = array() ) {
$terms = get_the_terms( $id, $taxonomy );
if ( is_wp_error( $terms ) )
return $terms;
if ( empty( $terms ) )
return false;
foreach ( $terms as $term ) {
if(!in_array($term->term_id,$exclude)) {
$link = get_term_link( $term, $taxonomy );
if ( is_wp_error( $link ) )
return $link;
$excluded_terms[] = '' . $term->name . '';
}
}
$excluded_terms = apply_filters( "term_links-$taxonomy", $excluded_terms );
return $before . join( $sep, $excluded_terms ) . $after;
}
and then use it like this:
<?php echo get_excluded_terms( $post->ID, 'critter_cat', 'Critter Type: ', ', ', ' ', array(667)); ?>

Resources