"Exclude current post" Widget wordpress (PHP help) - php

Hi :) I am working on my site with the "flexible post widget" to show the related contents or the content that I am interested in showing on the sidebar.
The widget works very well and I'm interested in continuing to use it, especially for the design and adaptability options with my site.
The problem? It does not include a function for "exclude the current post".
I was reviewing the code (I add it to this thread) and I think I could add some lines of code for this function (exclude the post I'm reading).
Unfortunately I'm new to programming and I'm lost with what and where to add it.
Could you help me?
<?php
/**
* Flexible Posts Widget: Default widget template
*
* #since 3.4.0
*
* This template was added to overcome some often-requested changes
* to the old default template (widget.php).
*/
// Block direct requests
if ( !defined('ABSPATH') )
die('-1');
echo $before_widget;
if ( ! empty( $title ) )
echo $before_title . $title . $after_title;
if ( $flexible_posts->have_posts() ):
function be_exclude_current_post( $args ) {
if( is_singular() && !isset( $args['post__in'] ) )
$args['post__not_in'] = array( get_the_ID() );
return $args;
}
add_filter( 'widget_posts_args', 'be_exclude_current_post' );
?>
<ul class="dpe-flexible-posts">
<?php while ( $flexible_posts->have_posts() ) : $flexible_posts->the_post(); global $post; ?>
<li id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<a href="<?php echo the_permalink(); ?>">
<?php
if ( $thumbnail == true ) {
// If the post has a feature image, show it
if ( has_post_thumbnail() ) {
the_post_thumbnail( $thumbsize );
// Else if the post has a mime type that starts with "image/" then show the image directly.
} elseif ( 'image/' == substr( $post->post_mime_type, 0, 6 ) ) {
echo wp_get_attachment_image( $post->ID, $thumbsize );
}
}
?>
<div class="title"><?php the_title(); ?></div>
</a>
</li>
<hr>
<?php endwhile; ?>
</ul><!-- .dpe-flexible-posts -->
<?php
endif; // End have_posts()
echo $after_widget;

Add this to your theme's 'functions.php' and remove it from the widget template.
function be_exclude_current_post( $args ) {
if( is_singular() && !isset( $args['post__in'] ) )
$args['post__not_in'] = array( get_the_ID() );
return $args;
}
add_filter( 'dpe_fpw_args', 'be_exclude_current_post' );

Related

WooCommerce - Don't display cross sells products which are out of the stock on cart page

My theme displays cross sell products on cart page which is fine.
This is done via the code below which can be found in the cart/cross-sells.php template file.
<?php foreach ( $cross_sells as $cross_sell ) : ?>
<?php
$post_object = get_post( $cross_sell->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited, Squiz.PHP.DisallowMultipleAssignments.Found
wc_get_template_part( 'content', 'product' );
?>
<?php endforeach; ?>
But I dont want to display products which are out of the stock
I managed to change number of columns for cross sells etc but i cant find anywhere some snippet that displays only available products.
Can someone walk me through how to do that?
There are always multiple solutions but 1 of them could be by overwriting the template file
https://github.com/woocommerce/woocommerce/blob/3.8.0/templates/cart/cross-sells.php
Replace (line: 28 - 38)
<?php foreach ( $cross_sells as $cross_sell ) : ?>
<?php
$post_object = get_post( $cross_sell->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.OverrideProhibited, Squiz.PHP.DisallowMultipleAssignments.Found
wc_get_template_part( 'content', 'product' );
?>
<?php endforeach; ?>
With
<?php foreach ( $cross_sells as $cross_sell ) : ?>
<?php
$stock_status = $cross_sell->get_stock_status();
if ( $stock_status != 'outofstock' ) {
$post_object = get_post( $cross_sell->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.OverrideProhibited, Squiz.PHP.DisallowMultipleAssignments.Found
wc_get_template_part( 'content', 'product' );
}
?>
<?php endforeach; ?>
woocommerce->settings->productst->inventory->out of stock visibility = check this button.
Inspired by #7uc1f3r's answer, I came up with this solution that also hides the title in the cas there's no product to display.
I did override /wp-content/plugins/woocommerce/templates/cart/cross-sells.php, creating a file in my child theme /wp-content/themes/MY-CHILD-THEME/woocommerce/content-product.php, with the following code:
<?php
/**
* Cross-sells
*
* This template can be overridden by copying it to yourtheme/woocommerce/cart/cross-sells.php.
*
* HOWEVER, on occasion WooCommerce will need to update template files and you
* (the theme developer) will need to copy the new files to your theme to
* maintain compatibility. We try to do this as little as possible, but it does
* happen. When this occurs the version of the template file will be bumped and
* the readme will list any important changes.
*
* #see https://docs.woocommerce.com/document/template-structure/
* #package WooCommerce\Templates
* #version 4.4.0
*/
defined( 'ABSPATH' ) || exit;
if ( $cross_sells ) : ?>
<?php
ob_start();
foreach ( $cross_sells as $cross_sell ) :
$stock_status = $cross_sell->get_stock_status();
if ( $stock_status != 'outofstock' ) { // only display product if it is not out of stock
$post_object = get_post( $cross_sell->get_id() );
setup_postdata( $GLOBALS['post'] =& $post_object ); // phpcs:ignore WordPress.WP.GlobalVariablesOverride.Prohibited, Squiz.PHP.DisallowMultipleAssignments.Found
wc_get_template_part( 'content', 'product' );
}
endforeach;
$html = ob_get_clean();
if ($html) { // only display the whole cross sells section of there's something to display
?>
<div class="cross-sells">
<?php
$heading = apply_filters( 'woocommerce_product_cross_sells_products_heading', __( 'You may be interested in…', 'woocommerce' ) );
if ( $heading ) :
?>
<h2><?php echo esc_html( $heading ); ?></h2>
<?php endif; ?>
<?php woocommerce_product_loop_start(); ?>
<?php echo $html; ?>
<?php woocommerce_product_loop_end(); ?>
</div>
<?php
}
?>
<?php
endif;
wp_reset_postdata();

Customising position of WordPress Featured Image

Is it possible to build an option in Wordpress which allows user to customise placement of featured image?
Currently the theme I am building, puts the featured image as a banner across the top of the post. Have some users requesting for option to be able to have featured images appear top right of the post with text wrapping around it.
Not sure about how to approach this. My first thought is to put an option in the customiser but I'm concerned this will apply to all blog posts rather than on an individual basis.
Another idea is to build a metabox into the post editing screen (underneath feat. image box) and then build a function to hook into wp post.
I've scoured over google on ways how to do this but all I can find so far is information on how to edit content.php to universally change/edit placement of all featured images.
It's hard to give an exact answer without knowing how your template is marked up, but I think you'll have two options of doing this. Either use a plugin (Advanced Custom Fields), or the solution you mentioned of adding a meta box to the post editor.
I would recommend Option 1 because the plugin is stable, configurable, and will save you some time if you need to add more fields.
Option 1: Use Advanced Custom Fields
Download and install the plugin from their site: https://www.advancedcustomfields.com
Use the plugin to add a custom field. These directions might help: https://www.advancedcustomfields.com/resources/creating-a-field-group/
Make note of the Field Name as you will need this in your code. You might use something such as image_placement. I'd recommend setting up a select box with values such as Left, Center, and Right.
Then, in your PHP template file, you'll want something like this:
<?php if( get_option('image_placement') === 'left' ) : ?>
// Write the markup here when the image be left-aligned
<?php else if( get_option('image_placement') === 'right' ) : ?>
// Write the markup here when the image should be right-aligned
<?php else : ?>
// Write the markup here when the image should be shown as a banner
<?php endif; ?>
Option 2: Add a custom meta box to each post
Add the following code to your functions.php:
// add the meta box to the post editor page
function add_image_meta_box( $post ) {
add_meta_box( 'image_meta_box', 'Image Placement', 'image_build_meta_box', 'post', 'side', 'low' );
}
add_action( 'add_meta_boxes', 'add_image_meta_box' );
// build the front-end for the meta box (shown on the post editor page)
function image_build_meta_box( $post ) {
wp_nonce_field( basename( __FILE__ ), 'image_meta_box_nonce' );
$image_placement = get_post_meta( $post->ID, '_post_image_placement' );
?>
<h3>Image Placement URL</h3>
<select name="image_placement">
<option value="left" <?php ($image_placement[0] === 'left') ?; echo 'selected'; ?>>Left</option>
<option value="center" <?php ($image_placement[0] === 'center') ?; echo 'selected'; ?>>Center</option>
<option value="right" <?php ($image_placement[0] === 'right') ?; echo 'selected'; ?>>Right</option>
</select>
<?php
}
// save the setting
function image_save_meta_box_data( $post_id ) {
// Check the user's permissions.
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
$image_placement = $_POST['image_placement'];
if( isset( $image_placement ) ){
update_post_meta( $post_id, '_post_image_placement', sanitize_text_field( $image_placement ) );
}
}
add_action( 'save_post', 'image_save_meta_box_data' );
This will add a field to each of your posts which can be used in the markup like thus:
<?php $image_placement = get_post_meta( $post->ID, '_post_image_placement' )[0]; ?>
<?php if( $image_placement === 'left' ) : ?>
// Write the markup here when the image be left-aligned
<?php else if( $image_placement === 'right' ) : ?>
// Write the markup here when the image should be right-aligned
<?php else : ?>
// Write the markup here when the image should be shown as a banner
<?php endif; ?>
kudos to #rideron89 for helping me with the solution. So here it is if anyone needs to use it (in some implementation):
I'm keeping functions.php a bit clean so I put it into another php file within 'incl' folder and it gets included within functions.php"
// add the meta box to the post editor page
function add_image_meta_box( $post ) {
add_meta_box( 'image_meta_box', 'Featured Image Placement', 'image_build_meta_box', 'post', 'side', 'low' );
}
add_action( 'add_meta_boxes', 'add_image_meta_box' );
// build the front-end for the meta box (shown on the post editor page)
function image_build_meta_box( $post ) {
wp_nonce_field( basename( __FILE__ ), 'image_meta_box_nonce' );
$image_placement_array = get_post_meta( $post->ID, '_post_image_placement' );
$image_placement = implode (" ",$image_placement_array);
?>
<p>Please select the layout/alignment of your featured image <em>(default is full width banner)</em></p>
<select name="image_placement">
<option value="default" name="feat_img_align" <?php if($image_placement === 'default'){ echo "selected"; } ?>>Default</option>
<option value="left" name="feat_img_align" <?php if($image_placement === 'left'){ echo "selected"; } ?>>Left</option>
<option value="right" name="feat_img_align" <?php if($image_placement === 'right'){ echo "selected"; } ?>>Right</option>
</select>
<?php
}
// save the setting
function image_save_meta_box_data( $post_id ) {
// Check the user's permissions.
if ( !current_user_can( 'edit_post', $post_id ) ) {
return;
}
$image_placement = $_POST['image_placement'];
if( isset( $image_placement ) ){
update_post_meta( $post_id, '_post_image_placement', sanitize_text_field( $image_placement ) );
}
}
add_action( 'save_post', 'image_save_meta_box_data' );
The code that I inserted into the post content.php template was:
<?php
$post_feat_img = quick_resize_to_ratio_and_size(get_post_thumbnail_id($post->ID),1,1,250);
$alt_text = get_post_meta(get_post_thumbnail_id($post->ID), '_wp_attachment_image_alt', true);
$image_placement_array = get_post_meta( $post->ID, '_post_image_placement' );
$image_placement = implode (" ",$image_placement_array);
?>
<?php if ($image_placement === 'default') { ?>
<p><?php echo get_the_post_thumbnail($post->ID, 'large', array( 'class'=>'img-responsive center-block img-thumbnail')); ?></p>
<?php } else if ($image_placement === 'left') { ?>
<img src="<?php echo $post_feat_img; ?>" alt="<?php echo $alt_text ?>" class="alignFeatleft img-thumbnail img-responsive">
<?php } else if ($image_placement === 'right') { ?>
<img src="<?php echo $post_feat_img; ?>" alt="<?php echo $alt_text ?>" class="alignFeatRight img-thumbnail img-responsive">
<?php } else { ?>
<p><?php echo get_the_post_thumbnail($post->ID, 'large', array( 'class'=>'img-responsive center-block img-thumbnail')); ?></p>
<?php } ?>
<?php the_content(); ?>

How to substring element inside html

I need to shorten the title in the previous and next buttons in a WP theme.
Here's the code:
<?php
/* ----------------------------------------------------------------------------------
Display navigation to next/previous pages when applicable.
---------------------------------------------------------------------------------- */
if ( ! function_exists( 'thinkup_input_nav' ) ) :
function thinkup_input_nav( $nav_id ) {
global $wp_query, $post;
// Don't print empty markup on single pages if there's nowhere to navigate.
if ( is_single() ) {
$previous = ( is_attachment() ) ? get_post( $post->post_parent ) : get_adjacent_post( false, '', true );
$next = get_adjacent_post( false, '', false );
if ( ! $next && ! $previous )
return;
}
// Don't print empty markup in archives if there's only one page.
if ( $wp_query->max_num_pages < 2 && ( is_home() || is_archive() || is_search() ) )
return;
?>
<nav role="navigation" id="<?php echo $nav_id; ?>">
<?php if ( is_single() ) : ?>
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav">%title</span>' ); ?>
<?php next_post_link( '<div class="nav-next">%link</div>', '<span class="meta-nav">%title</span><span class="meta-icon"><i class="icon-angle-right icon-large"></i></span>' ); ?>
<?php elseif ( $wp_query->max_num_pages > 1 && ( is_home() || is_archive() || is_search() ) ) : // navigation links for home, archive, and search pages ?>
<?php if ( get_next_posts_link() ) : ?>
<div class="nav-previous"><?php next_posts_link( __( 'Older posts', 'lan-thinkupthemes') ); ?></div>
<?php endif; ?>
<?php if ( get_previous_posts_link() ) : ?>
<div class="nav-next"><?php previous_posts_link( __( 'Newer posts', 'lan-thinkupthemes') ); ?></div>
<?php endif; ?>
<?php endif; ?>
</nav><!-- #<?php echo $nav_id; ?> -->
<?php
}
endif;
/* ----------------------------------------------------------------------------------
Display navigation to next/previous image when applicable.
---------------------------------------------------------------------------------- */
if ( ! function_exists( 'thinkup_input_imagesnav' ) ) :
function thinkup_input_imagesnav() {
global $wp_query, $post;
?>
<nav role="navigation" id="nav-below">
<div class="nav-previous"><?php previous_image_link( 'false', '<div class="nav-previous"><span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav">' . __( 'Previous', 'lan-thinkupthemes') . ' </span></div>' ); ?></div>
<div class="nav-next"><?php next_image_link( 'false', '<span class="meta-nav">' . __( 'Next', 'lan-thinkupthemes') . '</span><span class="meta-icon"><i class="icon-angle-right icon-large"></i></span>' ); ?></div>
</nav><!-- #image-navigation -->
<?php
}
endif;
/* Display comments at bottom of post, page and project pages. */
function thinkup_input_allowcomments() {
if ( comments_open() || '0' != get_comments_number() )
comments_template( '/comments.php', true );
}
/* ----------------------------------------------------------------------------------
Returns true if a blog has more than 1 category.
---------------------------------------------------------------------------------- */
function thinkup_input_categorizedblog() {
if ( false === ( $all_the_cool_cats = get_transient( 'all_the_cool_cats' ) ) ) {
// Create an array of all the categories that are attached to posts
$all_the_cool_cats = get_categories( array(
'hide_empty' => 1,
) );
// Count the number of categories that are attached to the posts
$all_the_cool_cats = count( $all_the_cool_cats );
set_transient( 'all_the_cool_cats', $all_the_cool_cats );
}
if ( '1' != $all_the_cool_cats ) {
return true;
} else {
return false;
}
}
/* Flush out the transients used in thinkup_input_categorizedblog. */
function thinkup_input_transient_flusher() {
delete_transient( 'all_the_cool_cats' );
}
add_action( 'edit_category', 'thinkup_input_transient_flusher' );
add_action( 'save_post', 'thinkup_input_transient_flusher' );
What I tried was to add substring to this line:
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav">%title</span>' ); ?>
to:
<?php previous_post_link( '<div class="nav-previous">%link</div>', '<span class="meta-icon"><i class="icon-angle-left icon-large"></i></span><span class="meta-nav"><?php echo substr(%title,0,10)?></span>' ); ?>
but upon reloading the page it displayed an empty text instead.
What am I doing wrong?
You can override the previous_post_link() function in your functions.php file of your theme as like this :
function previous_post_link($format='« %link', $link='%title', $in_same_cat = false, $excluded_categories = '',$limit = -1) {
if ( is_attachment() )
$post = & get_post($GLOBALS['post']->post_parent);
else
$post = get_previous_post($in_same_cat, $excluded_categories);
if ( !$post )
return;
$title = apply_filters('the_title', $post->post_title, $post);
if ($limit>-1) {$title = substr($title,0,$limit).'…';}
$string = '<a href="'.get_permalink($post->ID).'">';
$link = str_replace('%title', $title, $link);
$link = $pre . $string . $link . '</a>';
$format = str_replace('%link', $link, $format);
echo $format;
And then you can call the function with the additional argument to define your desired trim length:
<li><?php previous_post_link('%link','&laquo %title',FALSE,'',20); ?></li>
Hope it helps you.
Taken from https://wordpress.org/support/topic/using-substr-to-limit-characters-in-post-title

Can't Echo Custom Field In Widget

I'm trying to display a custom field in a widget I'm customizing but I can't get the custom field to display. I think it has something to do with the variable I'm using to get the post ID in the loop because when I change it to the standard the_title function, the widget works, so it has something to do with how I'm calling the custom field.
I know the key to the custom field is "wpcf-promo-title" but no matter what I've tried, the custom field (which holds a shortened version of the post title for the sidebar) just won't display. This code results in the thumbnails showing, but not the promo title. You can see this in action at http://www.cantstopshipping.com
Here's my code, including the query and the front end of the widget.
function widget($args, $instance) {
extract( $args );
$title = apply_filters( 'widget_title', empty($instance['title']) ? 'Recent Posts' : $instance['title'], $instance, $this->id_base);
$show_date = isset( $instance['show_date'] ) ? $instance['show_date'] : false;
if ( ! $number = absint( $instance['number'] ) ) $number = 5;
if( ! $cats = $instance["cats"] ) $cats='';
// array to call recent posts.
$crpw_args=array(
'showposts' => $number,
'category__in'=> $cats,
);
$crp_widget = null;
$crp_widget = new WP_Query($crpw_args);
echo $before_widget;
// Widget title
echo $before_title;
echo $instance["title"];
echo $after_title;
// Post list in widget
echo "<ul>\n";
while ( $crp_widget->have_posts() )
{
$crp_widget->the_post();
?>
<li class="crpw-item">
<p style="float:left">
<?php the_post_thumbnail('sidebar-small'); ?>
</p>
<?php $promotitle = get_post_meta($post->ID, 'wpcf-promo-title', true); ?>
<p style="float:right; width:200px">
<?php echo $promotitle; ?>
</p>
<?php if ( $show_date ) : ?>
<span class="crpw-date"><?php echo "("; ?><?php echo get_the_date(); ?><?php echo ")"; ?></span>
<?php endif; ?>
</li>
<?php
}
wp_reset_query();
echo "<div class=\"fix\"></div>";
echo "</ul>\n";
echo $after_widget;
}
It looks like your global $post is missing.
But you could try get_the_ID() instead of $post->ID.
You should also consider getting rid of extract(), it's now considered a "bad" practice.
Another thing is that you should use wp_reset_postdata() to restore the global $post object. The wp_reset_query() call should be used with the query_posts() call.

Insert featured image into post content

I am using a wordpress theme for my website and I'm trying to alter the php so that the featured image is displayed within the post content instead of before or after (the top of the post or the bottom)
Here's the original code:
<?php if ( ( has_post_thumbnail( $post_id ) || '' != get_post_meta( $post_id, 'Thumbnail', true ) ) && 'on' == et_get_option( 'origin_thumbnails' ) ) { ?>
<div class="post-thumbnail">
<?php
if ( has_post_thumbnail( $post_id ) ) the_post_thumbnail( 'full' );
else printf( '<img src="%1$s" alt="%2$s" />', esc_attr( get_post_meta( $post_id, 'Thumbnail', true ) ), the_title_attribute( array( 'echo' => 0 ) ) );
?>
</div> <!-- end .post-thumbnail -->
<?php } ?>
<?php the_content(); ?>
Here's how I tweaked it in my child theme:
<?php the_content(); ?>
<?php if ( ( has_post_thumbnail( $post_id ) || '' != get_post_meta( $post_id, 'Thumbnail', true ) ) && 'on' == et_get_option( 'origin_thumbnails' ) ) { ?>
<div class="post-thumbnail">
<?php
if ( has_post_thumbnail( $post_id ) ) the_post_thumbnail( 'full' );
else printf( '<img src="%1$s" alt="%2$s" />', esc_attr( get_post_meta( $post_id, 'Thumbnail', true ) ), the_title_attribute( array( 'echo' => 0 ) ) );
?>
</div>
I'm not very fluent in php and all that accomplished was moving the featured image to the bottom of the post :-/. I posted to my theme's forum and was given the following code which didn't seem to do anything.
add_filter( 'the_content', insert_featured_image, 20 );
function insert_featured_image( $content ) {
$content = preg_replace( "/<\/p>/", "</p>" . get_the_post_thumbnail($post->ID, 'post-single'), $content, 1 );
return $content;
}
Can anyone point me in the right direction?
TIA!
What is the reasoning behind attempting to move the featured image into the content? The Wordpress codex gives the following as an example:
// check if the post has a Post Thumbnail assigned to it.
if ( has_post_thumbnail() ) {
the_post_thumbnail();
}
the_content();
Basically, the_post_thumbnail(); will display the image that was selected as the featured image while the_content(); is simply displaying what was inputted into the wysiwyg for that post or page.
If you're attempting to do this so that it matches a design or layout, you might want to look at applying addition markup and styles to this area. If you require text before and after the featured image you should look into custom fields.

Categories