In WooCommerce, I would like to enable Ajax on my custom add to card buttons. You can check it on my website here. Any help is appreciated.
Here is my code that create product links from a product category with a shortcode:
function woo_category_design_caa1( $atts ) {
$category_id = $atts['category'];
if(class_exists('WooCommerce')){
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'field' => 'term_id', //This is optional, as it defaults to 'term_id'
'terms' => $category_id,
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
)
)
);
if( $term = get_term_by('id', $category_id, 'product_cat')){
$cat_name = $term->name;
}
$products_list = new WP_Query($args);
if($products_list->have_posts()){
$tableHtml = '';
$tableHtml .= '<div class="menu1">';
$tableHtml .= "<div class='heading-menu' id='a" . $category_id . "'>".$cat_name."</div>";
$tableHtml .= '<ul>';
while($products_list->have_posts()){
$products_list->the_post();
$_product = wc_get_product(get_the_ID());
if($_product->is_type( 'variable' )){
$args = array(
'post_type' => 'product_variation',
'post_status' => array( 'private', 'publish' ),
'numberposts' => -1,
'orderby' => 'menu_order',
'order' => 'asc',
'post_parent' => get_the_ID() // $post->ID
);
$variations = get_posts( $args );
$price ='';
$var_title = '';
$link_1 = '';
foreach($variations as $variation){
$var_title = $var_title . "/" . $variation->post_title;
//$price = $price . "/" . get_post_meta($variation->ID, '_regular_price', true);
$price = $price . '<a class="btn-link-atc" href="/order-online/?add-to-cart='.get_the_ID().'&variation_id='.$variation->ID.'"> ' . $variation->post_title .' ₹ '. get_post_meta($variation->ID, '_regular_price', true) . ' </a>';
}
}else{
$price = '<a class="btn-link-atc" href="/order-online/?add-to-cart='.get_the_ID().'">Add To Cart ₹ '.get_post_meta(get_the_ID(), '_regular_price', true).'</a>';
//$price = get_post_meta(get_the_ID(), '_regular_price', true);
}
$tableHtml .= '<li>
<div class="title">'.get_the_title().'</div><span>'.$price.'</span></li>';
}
$tableHtml .= '</ul>';
$tableHtml .= '</div>';
return $tableHtml;
//return ' ';
}
else {
return "Nothing Found.";
}
}
else {
return "Problem fetching data !";
}
}
add_shortcode('woo_products_from_category_type1', 'woo_category_design_caa1');
Updated… Your code has a lot of little mistakes and I have completely revisited it to enable Ajax add to cart functionality even on product variations (which is not so simple).
I have renamed your Shortcode from [woo_category_design_caa1] to [products_from_cat]… Your function name stays unchanged.
Here is the correct functional code with Ajax add to cart enabled:
if( ! function_exists('woo_category_design_caa1') && class_exists('WooCommerce') ) {
function woo_category_design_caa1( $atts ) {
// Shortcode attributes
$atts = shortcode_atts( array(
'category' => '', // <= Set the default product category ID
), $atts, 'products_from_cat' );
$products = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => -1,
'tax_query' => array( array(
'taxonomy' => 'product_cat',
'field' => 'term_id',
'terms' => $atts['category'],
'operator' => 'IN',
) )
) );
if($products->have_posts()):
$term_name = get_term( $atts['category'], 'product_cat')->name; // The product category Name
$output = '<div class="menu1">
<div class="heading-menu" id="a' . $atts["category"] . '">'.$term_name.'</div>
<ul>';
while( $products->have_posts() ): $products->the_post();
$product = wc_get_product($products->post->ID); // The WC_Product object (instance)
$type = $product->get_type();
if( $product->is_type( 'variable' ) && $product->is_in_stock() ){
$variations_ids = $product->get_visible_children(); // Get the variations IDs
$class = 'btn-link-atc';
$buttons = array();
foreach( $variations_ids as $variation_id ){
$variation = wc_get_product($variation_id); // The WC_Product_Variation object (instance)
// Get the variation attributes
$variation_attributes = $variation->get_attributes();
$attributes = array();
foreach( $variation_attributes as $taxonomy => $term_slug ){
$attributes[] = get_term_by( 'slug', $term_slug, $taxonomy )->name;
}
$attributes = ' - ' . implode( ' - ', $attributes );
// Get the correct button classes
$class = implode( ' ', array_filter( array(
'btn-link-atc',
'button',
'product_type_' . $variation->get_type(),
$product->is_purchasable() && $variation->is_in_stock() ? 'add_to_cart_button' : '',
$variation->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );
$price = $variation->get_price();
if($variation->is_in_stock()){
$buttons[] = sprintf( '<a rel="nofollow" href="%s" data-quantity="1" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
esc_url( $variation->add_to_cart_url() ),
esc_attr( $variation->get_id() ),
esc_attr( empty( $variation->get_sku() ) ? $product->get_sku() : $variation->get_sku() ),
esc_attr( isset( $class ) ? $class : 'btn-link-atc button' ),
esc_html( $variation->add_to_cart_text() ) . $attributes . ' - ' . wc_price($price)
);
}
}
$add_to_cart = implode(' <br />', $buttons);
} elseif( ! $product->is_type( 'variable' ) && $product->is_in_stock() ){
$class = implode( ' ', array_filter( array(
'btn-link-atc',
'button',
'product_type_' . $product->get_type(),
$product->is_purchasable() && $product->is_in_stock() ? 'add_to_cart_button' : '',
$product->supports( 'ajax_add_to_cart' ) ? 'ajax_add_to_cart' : '',
) ) );
$price = $product->get_price();
$add_to_cart = sprintf( '<a rel="nofollow" href="%s" data-quantity="1" data-product_id="%s" data-product_sku="%s" class="%s">%s</a>',
esc_url( $product->add_to_cart_url() ),
esc_attr( $product->get_id() ),
esc_attr( $product->get_sku() ),
esc_attr( isset( $class ) ? $class : 'btn-link-atc button' ),
esc_html( $product->add_to_cart_text() ) . ' - ' . wc_price($price)
);
}
$output .= '<li><div class="title">'.$product->get_title().'</div><span>'.$add_to_cart.'</span></li>';
endwhile;
$output .= '</ul>
</div>';
wp_reset_postdata();
wp_reset_query();
return $output;
else:
return "Nothing Found.";
endif;
}
add_shortcode('products_from_cat', 'woo_category_design_caa1');
}
This code goes on function.php file of your active child theme (or theme). Tested and works.
Each time a product will be added to cart, it will make appear a "view cart" button… You can hide it with the following CSS rule:
a.added_to_cart.wc-forward {
display:none;
}
Related
So I'm using wordpress and ACF. I created a CPT called products and a custom taxonomy named product_types. I have a loop that displays all product_type sections and each section contains products tied to it. So I'm looking for ways to easily filter new products or popular products thats why I come up with adding a dedicated category for it but I dont want it to exclude it from my post loop. pls see img attached
enter image description here
Here's the code I'm working with atm
<?php
$cpt_name = 'products';
$taxonomy_name = 'product_type';
// Retrieve the terms in the above taxonomy.
$terms = get_terms( $taxonomy_name );
if ( empty( $terms ) || is_wp_error( $terms ) ) {
return;
}
echo '<div class="products-group">';
foreach( $terms as $term ) {
echo '<div class="products-category">';
echo '<h2 class="title-category">' . $term->name . '</h2>';
$args = array(
'post_type' => $cpt_name,
'tax_query' => array(
array(
'taxonomy' => $taxonomy_name,
'field' => 'slug',
'terms' => array( $term->slug ),
),
),
'posts_per_page' => -1,
'category__not_in' => array( 30 ),
);
$query = new WP_Query( $args );
echo '<div class="products-list">';
while ( $query->have_posts() ) {
$query->the_post();
$attachment_id = get_field('header_bg_image');
$size = "wide-thumbnail"; // (thumbnail, medium, large, full or custom size)
$image = wp_get_attachment_image_src( $attachment_id, $size );
if ( ! empty( $image ) ) {
$image_html = esc_url( $image[0] );
} else {
$image_html = 'https://rasons.ltd/wp-content/uploads/2020/02/interior-exterior-finish-800x400.jpg';
}
printf( '%s', get_the_permalink(), esc_attr( the_title_attribute( 'echo=0' ) ), get_the_title() );
}
echo '</ul>';
wp_reset_query();
echo '</div></div>';
} // end foreach.
echo '</div>';
?>
I am trying to add a widget to Woocommerce to Filter Products by Quantity with a slider. I got this far by changing the open source code of woocommerce for the price filter slider. It print no errors once it's on the website but it does not filter the results. The output on the URL is also as expected. The slider does not work but it's fine if I cannot fix it. As of now it has two type-in fields: max and min stock quantity. Please help. I am sure others will benefit from this. I need it because the website is for wholesale and if a product is not available is a min quantity that a client wants, they can filter it out.
// Register and load the widget
function my_stock_widget() {
register_widget( 'WC_Widget_Stock_Filter' );
}
add_action( 'widgets_init', 'my_stock_widget' );
class WC_Widget_Stock_Filter extends WC_Widget {
/**
* Constructor.
*/
public function __construct() {
$this->widget_cssclass = 'woocommerce widget_stock_filter';
$this->widget_description = __( 'Shows a stock filter slider in a widget which lets you narrow down the list of shown products when viewing product categories.', 'woocommerce' );
$this->widget_id = 'woocommerce_stock_filter';
$this->widget_name = __( 'WooCommerce stock filter', 'woocommerce' );
$this->settings = array(
'title' => array(
'type' => 'text',
'std' => __( 'Filter by stock', 'woocommerce' ),
'label' => __( 'Title', 'woocommerce' ),
),
);
$suffix = defined( 'SCRIPT_DEBUG' ) && SCRIPT_DEBUG ? '' : '.min';
wp_register_script( 'accounting', WC()->plugin_url() . '/assets/js/accounting/accounting' . $suffix . '.js', array( 'jquery' ), '0.4.2' );
wp_register_script( 'wc-jquery-ui-touchpunch', WC()->plugin_url() . '/assets/js/jquery-ui-touch-punch/jquery-ui-touch-punch' . $suffix . '.js', array( 'jquery-ui-slider' ), WC_VERSION, true );
wp_register_script( 'wc-stock-slider', WC()->plugin_url() . '/assets/js/frontend/price-slider' . $suffix . '.js', array( 'jquery-ui-slider', 'wc-jquery-ui-touchpunch', 'accounting' ), WC_VERSION, true );
wp_localize_script( 'wc-stock-slider', 'woocommerce_stock_slider_params', array(
'min_stock' => isset( $_GET['min_stock'] ) ? esc_attr( $_GET['min_stock'] ) : '',
'max_stock' => isset( $_GET['max_stock'] ) ? esc_attr( $_GET['max_stock'] ) : '',
'currency_format_num_decimals' => 0,
// 'currency_format_symbol' => get_woocommerce_currency_symbol(),
'currency_format_decimal_sep' => esc_attr( wc_get_price_decimal_separator() ),
'currency_format_thousand_sep' => esc_attr( wc_get_price_thousand_separator() ),
// 'currency_format' => esc_attr( str_replace( array( '%1$s', '%2$s' ), array( '%s', '%v' ), get_woocommerce_stock_format() ) ),
) );
parent::__construct();
}
/**
* Output widget.
*
* #see WP_Widget
*
* #param array $args
* #param array $instance
*/
public function widget( $args, $instance ) {
global $wp, $wp_the_query;
if ( ! is_post_type_archive( 'product' ) && ! is_tax( get_object_taxonomies( 'product' ) ) ) {
return;
}
if ( ! $wp_the_query->post_count ) {
return;
}
$min_stock = isset( $_GET['min_stock'] ) ? esc_attr( $_GET['min_stock'] ) : '';
$max_stock = isset( $_GET['max_stock'] ) ? esc_attr( $_GET['max_stock'] ) : '';
wp_enqueue_script( 'wc-stock-slider' );
// Find min and max stock in current result set
$stocks = $this->get_filtered_stock();
$min = floor( $stocks->min_stock );
$max = ceil( $stocks->max_stock );
if ( $min === $max ) {
return;
}
$this->widget_start( $args, $instance );
if ( '' === get_option( 'permalink_structure' ) ) {
$form_action = remove_query_arg( array( 'page', 'paged' ), add_query_arg( $wp->query_string, '', home_url( $wp->request ) ) );
} else {
$form_action = preg_replace( '%\/page/[0-9]+%', '', home_url( trailingslashit( $wp->request ) ) );
}
/**
* Adjust max if the store taxes are not displayed how they are stored.
* Min is left alone because the product may not be taxable.
* Kicks in when stocks excluding tax are displayed including tax.
*
if ( wc_tax_enabled() && 'incl' === get_option( 'woocommerce_tax_display_shop' ) && ! wc_stocks_include_tax() ) {
$tax_classes = array_merge( array( '' ), WC_Tax::get_tax_classes() );
$class_max = $max;
foreach ( $tax_classes as $tax_class ) {
if ( $tax_rates = WC_Tax::get_rates( $tax_class ) ) {
$class_max = $max + WC_Tax::get_tax_total( WC_Tax::calc_exclusive_tax( $max, $tax_rates ) );
}
}
$max = $class_max;
}*/
echo '<form method="get" action="' . esc_url( $form_action ) . '">
<div class="stock_slider_wrapper">
<div class="stock_slider" style="display:none;"></div>
<div class="stock_slider_amount">
<input type="text" id="min_stock" name="min_stock" value="' . esc_attr( $min_stock ) . '" data-min="' . esc_attr( apply_filters( 'woocommerce_stock_filter_widget_min_amount', $min ) ) . '" placeholder="' . esc_attr__( 'Min stock', 'woocommerce' ) . '" />
<input type="text" id="max_stock" name="max_stock" value="' . esc_attr( $max_stock ) . '" data-max="' . esc_attr( apply_filters( 'woocommerce_stock_filter_widget_max_amount', $max ) ) . '" placeholder="' . esc_attr__( 'Max stock', 'woocommerce' ) . '" />
<button type="submit" class="button">' . esc_html__( 'Filter', 'woocommerce' ) . '</button>
<div class="stock_label" style="display:none;">
' . esc_html__( 'Stock:', 'woocommerce' ) . ' <span class="from"></span> — <span class="to"></span>
</div>
' . wc_query_string_form_fields( null, array( 'min_stock', 'max_stock' ), '', true ) . '
<div class="clear"></div>
</div>
</div>
</form>';
$this->widget_end( $args );
}
/**
* Get filtered min stock for current products.
* #return int
*/
protected function get_filtered_stock() {
global $wpdb, $wp_the_query;
$args = $wp_the_query->query_vars;
$tax_query = isset( $args['tax_query'] ) ? $args['tax_query'] : array();
$meta_query = isset( $args['meta_query'] ) ? $args['meta_query'] : array();
if ( ! is_post_type_archive( 'product' ) && ! empty( $args['taxonomy'] ) && ! empty( $args['term'] ) ) {
$tax_query[] = array(
'taxonomy' => $args['taxonomy'],
'terms' => array( $args['term'] ),
'field' => 'slug',
);
}
foreach ( $meta_query + $tax_query as $key => $query ) {
if ( ! empty( $query['stock_filter'] ) || ! empty( $query['rating_filter'] ) ) {
unset( $meta_query[ $key ] );
}
}
$meta_query = new WP_Meta_Query( $meta_query );
$tax_query = new WP_Tax_Query( $tax_query );
$meta_query_sql = $meta_query->get_sql( 'post', $wpdb->posts, 'ID' );
$tax_query_sql = $tax_query->get_sql( $wpdb->posts, 'ID' );
$sql = "SELECT min( FLOOR( stock_meta.meta_value ) ) as min_stock, max( CEILING( stock_meta.meta_value ) ) as max_stock FROM {$wpdb->posts} ";
$sql .= " LEFT JOIN {$wpdb->postmeta} as stock_meta ON {$wpdb->posts}.ID = stock_meta.post_id " . $tax_query_sql['join'] . $meta_query_sql['join'];
$sql .= " WHERE {$wpdb->posts}.post_type IN ('" . implode( "','", array_map( 'esc_sql', apply_filters( 'woocommerce_stock_filter_meta_keys', array( 'product' ) ) ) ) . "')
AND {$wpdb->posts}.post_status = 'publish'
AND stock_meta.meta_key IN ('" . implode( "','", array_map( 'esc_sql', apply_filters( 'woocommerce_stock_filter_meta_keys', array( '_stock' ) ) ) ) . "')
AND stock_meta.meta_value > '' ";
$sql .= $tax_query_sql['where'] . $meta_query_sql['where'];
if ( $search = WC_Query::get_main_search_query_sql() ) {
$sql .= ' AND ' . $search;
}
return $wpdb->get_row( $sql );
}
I have created a custom page using woocommerce short code for product categories. At the moment, it's pretty sparse as I've only just started on the new site.
I just need the default 'sort by' drop down element adding but have no idea how to do it.
I found some code here >>Woocommerce, sort dropdown on shortcode based product lists
and it certainly placed the drop down I need on the site (although I'd like it aligned left).
The only problem now, is that it's displaying the products with enormous images and all in a single vertical column.
I'm not a PHP programmer and am wondering if I've deleted some important code in the php file I modified. (thank god I took a copy of the original!).
Can anyone help? Is there a better way to add the sort by drop down onto my custom pages?
This is one of the pages I've created >> http://www.sdmtest1.co.uk/notebooks-journals/
Here is the code I added.
/**
* List products in a category shortcode
*
* #param array $atts
* #return string
*/
public static function product_category( $atts ) {
$atts = shortcode_atts( array(
'per_page' => '12',
'columns' => '4',
'orderby' => 'title',
'order' => 'desc',
'category' => '', // Slugs
'operator' => 'IN' // Possible values are 'IN', 'NOT IN', 'AND'.
), $atts );
if ( ! $atts['category'] ) {
return '';
}
// Default ordering args
$ordering_args = WC()->query->get_catalog_ordering_args( $atts['orderby'],
$atts['order'] );
$orderby = 'title';
$order = 'asc';
if ( isset( $_GET['orderby'] ) ) {
$getorderby = $_GET['orderby'];
}
if ($getorderby == 'popularity') {
$orderby = 'meta_value_num';
$order = 'desc';
$meta_key = 'total_sales';
} elseif ($getorderby == 'rating') {
$fields .= ", AVG( $wpdb->commentmeta.meta_value ) as average_rating ";
$where .= " AND ( $wpdb->commentmeta.meta_key = 'rating' OR $wpdb->commentmeta.meta_key IS null ) ";
$join .= "
LEFT OUTER JOIN $wpdb->comments ON($wpdb->posts.ID = $wpdb->comments.comment_post_ID)
LEFT JOIN $wpdb->commentmeta ON($wpdb->comments.comment_ID = $wpdb->commentmeta.comment_id)
";
$orderby = "average_rating DESC, $wpdb->posts.post_date DESC";
$groupby = "$wpdb->posts.ID";
} elseif ($getorderby == 'date') {
$orderby = 'date';
$order = 'desc';
} elseif ($getorderby == 'price') {
$orderby = 'meta_value_num';
$order = 'asc';
$meta_key = '_price';
} elseif ($getorderby == 'price-desc') {
$orderby = 'meta_value_num';
$order = 'desc';
$meta_key = '_price';
}
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'ignore_sticky_posts' => 1,
'orderby' => $orderby, // $ordering_args['orderby'],
'order' => $order, // $ordering_args['order'],
'meta_key' => $meta_key,
'fields' => $fields,
'where' => $where,
'join' => $join,
'groupby' => $groupby,
'posts_per_page' => $per_page,
'meta_query' => array(
array(
'key' => '_visibility',
'value' => array('catalog', 'visible'),
'compare' => 'IN'
)
),
'tax_query' => array(
array(
'taxonomy' => 'product_cat',
'terms' => array( esc_attr( $category ) ),
'field' => 'slug',
'operator' => $operator
)
)
);
if ( isset( $ordering_args['meta_key'] ) ) {
$args['meta_key'] = $ordering_args['meta_key'];
}
ob_start();
$products = new WP_Query( apply_filters( 'woocommerce_shortcode_products_query', $args, $atts ) );
$woocommerce_loop['columns'] = $columns;
if ( $products->have_posts() ) : ?>
<div style="width:100%;">
<div style="float:right">
<form class="woocommerce-ordering" method="get">
<select name="orderby" class="orderby">
<?php
$catalog_orderby = apply_filters( 'woocommerce_catalog_orderby', array(
'menu_order' => __( 'Default sorting', 'woocommerce' ),
'popularity' => __( 'Sort by popularity', 'woocommerce' ),
'rating' => __( 'Sort by average rating', 'woocommerce' ),
'date' => __( 'Sort by newness', 'woocommerce' ),
'price' => __( 'Sort by price: low to high', 'woocommerce' ),
'price-desc' => __( 'Sort by price: high to low', 'woocommerce' )
) );
if ( get_option( 'woocommerce_enable_review_rating' ) === 'no' )
unset( $catalog_orderby['rating'] );
foreach ( $catalog_orderby as $id => $name )
echo '<option value="' . esc_attr( $id ) . '" ' . selected( $getorderby, $id, false ) . '>' . esc_attr( $name ) . '</option>';
?>
</select>
<?php
// Keep query string vars intact
foreach ( $_GET as $key => $val ) {
if ( 'orderby' === $key || 'submit' === $key )
continue;
if ( is_array( $val ) ) {
foreach( $val as $innerVal ) {
echo '<input type="hidden" name="' . esc_attr( $key ) . '[]" value="' . esc_attr( $innerVal ) . '" />';
}
} else {
echo '<input type="hidden" name="' . esc_attr( $key ) . '" value="' . esc_attr( $val ) . '" />';
}
}
?>
</form>
</div>
</div>
<div style="clear:both;"></div>
<?php woocommerce_product_loop_start(); ?>
<?php while ( $products->have_posts() ) : $products->the_post(); ?>
<?php wc_get_template_part( 'content', 'product' ); ?>
<?php endwhile; // end of the loop. ?>
<?php woocommerce_product_loop_end(); ?>
<?php endif;
woocommerce_reset_loop();
wp_reset_postdata();
return '<div class="woocommerce columns-' . $columns . '">' . ob_get_clean() . '</div>';
}
I edited in dreamweaver and it flagged a syntax error. I wasn't sure where the code I pasted was to begin and end and I kinda lost this bit in the process.
// Remove ordering query arguments
WC()->query->remove_ordering_args();
return $return;
}
Thanks,
Loren
If you add the paginate="true" attribute to your [products] shortcode, then the shortcode, then the Sort by dropdown menu will appear on the page.
I have created a custom page using woocommerce short code for product categories.
You say you're using shortcodes, but you don't provide an example. So I'll make one up.
If you were using this to display all of the products in the "boots" category:
[product_category category="boots"]
Then change it to this:
[product_category category="boots" paginate="true"]
i have a shortcode that posts recent blog entries from a certain category on one of my web pages, however i want to display a static link at the end of everypost, is there anyway to do this?
the following code is used to display the posts:
<?php echo do_shortcode('[display-posts category="competitions" posts_per_page="4" include_excerpt="true" image_size="thumbnail" wrapper="ul"]');
Thanks in advance.
<?php
// Create the shortcode
add_shortcode( 'display-posts', 'be_display_posts_shortcode' );
function be_display_posts_shortcode( $atts ) {
// Original Attributes, for filters
$original_atts = $atts;
// Pull in shortcode attributes and set defaults
$atts = shortcode_atts( array(
'title' => '',
'author' => '',
'category' => '',
'date_format' => '(n/j/Y)',
'display_posts_off' => false,
'exclude_current' => false,
'id' => false,
'ignore_sticky_posts' => false,
'image_size' => false,
'include_title' => true,
'include_author' => false,
'include_content' => false,
'include_date' => false,
'include_excerpt' => false,
'meta_key' => '',
'meta_value' => '',
'no_posts_message' => '',
'offset' => 0,
'order' => 'DESC',
'orderby' => 'date',
'post_parent' => false,
'post_status' => 'publish',
'post_type' => 'post',
'posts_per_page' => '10',
'tag' => '',
'tax_operator' => 'IN',
'tax_term' => false,
'taxonomy' => false,
'wrapper' => 'ul',
'wrapper_class' => 'display-posts-listing',
'wrapper_id' => false,
), $atts, 'display-posts' );
// End early if shortcode should be turned off
if( $atts['display_posts_off'] )
return;
$shortcode_title = sanitize_text_field( $atts['title'] );
$author = sanitize_text_field( $atts['author'] );
$category = sanitize_text_field( $atts['category'] );
$date_format = sanitize_text_field( $atts['date_format'] );
$exclude_current = be_display_posts_bool( $atts['exclude_current'] );
$id = $atts['id']; // Sanitized later as an array of integers
$ignore_sticky_posts = be_display_posts_bool( $atts['ignore_sticky_posts'] );
$image_size = sanitize_key( $atts['image_size'] );
$include_title = be_display_posts_bool( $atts['include_title'] );
$include_author = be_display_posts_bool( $atts['include_author'] );
$include_content = be_display_posts_bool( $atts['include_content'] );
$include_date = be_display_posts_bool( $atts['include_date'] );
$include_excerpt = be_display_posts_bool( $atts['include_excerpt'] );
$meta_key = sanitize_text_field( $atts['meta_key'] );
$meta_value = sanitize_text_field( $atts['meta_value'] );
$no_posts_message = sanitize_text_field( $atts['no_posts_message'] );
$offset = intval( $atts['offset'] );
$order = sanitize_key( $atts['order'] );
$orderby = sanitize_key( $atts['orderby'] );
$post_parent = $atts['post_parent']; // Validated later, after check for 'current'
$post_status = $atts['post_status']; // Validated later as one of a few values
$post_type = sanitize_text_field( $atts['post_type'] );
$posts_per_page = intval( $atts['posts_per_page'] );
$tag = sanitize_text_field( $atts['tag'] );
$tax_operator = $atts['tax_operator']; // Validated later as one of a few values
$tax_term = sanitize_text_field( $atts['tax_term'] );
$taxonomy = sanitize_key( $atts['taxonomy'] );
$wrapper = sanitize_text_field( $atts['wrapper'] );
$wrapper_class = sanitize_html_class( $atts['wrapper_class'] );
if( !empty( $wrapper_class ) )
$wrapper_class = ' class="' . $wrapper_class . '"';
$wrapper_id = sanitize_html_class( $atts['wrapper_id'] );
if( !empty( $wrapper_id ) )
$wrapper_id = ' id="' . $wrapper_id . '"';
// Set up initial query for post
$args = array(
'category_name' => $category,
'order' => $order,
'orderby' => $orderby,
'post_type' => explode( ',', $post_type ),
'posts_per_page' => $posts_per_page,
'tag' => $tag,
);
// Ignore Sticky Posts
if( $ignore_sticky_posts )
$args['ignore_sticky_posts'] = true;
// Meta key (for ordering)
if( !empty( $meta_key ) )
$args['meta_key'] = $meta_key;
// Meta value (for simple meta queries)
if( !empty( $meta_value ) )
$args['meta_value'] = $meta_value;
// If Post IDs
if( $id ) {
$posts_in = array_map( 'intval', explode( ',', $id ) );
$args['post__in'] = $posts_in;
}
// If Exclude Current
if( $exclude_current )
$args['post__not_in'] = array( get_the_ID() );
// Post Author
if( !empty( $author ) )
$args['author_name'] = $author;
// Offset
if( !empty( $offset ) )
$args['offset'] = $offset;
// Post Status
$post_status = explode( ', ', $post_status );
$validated = array();
$available = array( 'publish', 'pending', 'draft', 'auto-draft', 'future', 'private', 'inherit', 'trash', 'any' );
foreach ( $post_status as $unvalidated )
if ( in_array( $unvalidated, $available ) )
$validated[] = $unvalidated;
if( !empty( $validated ) )
$args['post_status'] = $validated;
// If taxonomy attributes, create a taxonomy query
if ( !empty( $taxonomy ) && !empty( $tax_term ) ) {
// Term string to array
$tax_term = explode( ', ', $tax_term );
// Validate operator
if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) )
$tax_operator = 'IN';
$tax_args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $tax_term,
'operator' => $tax_operator
)
)
);
// Check for multiple taxonomy queries
$count = 2;
$more_tax_queries = false;
while(
isset( $original_atts['taxonomy_' . $count] ) && !empty( $original_atts['taxonomy_' . $count] ) &&
isset( $original_atts['tax_' . $count . '_term'] ) && !empty( $original_atts['tax_' . $count . '_term'] )
):
// Sanitize values
$more_tax_queries = true;
$taxonomy = sanitize_key( $original_atts['taxonomy_' . $count] );
$terms = explode( ', ', sanitize_text_field( $original_atts['tax_' . $count . '_term'] ) );
$tax_operator = isset( $original_atts['tax_' . $count . '_operator'] ) ? $original_atts['tax_' . $count . '_operator'] : 'IN';
$tax_operator = in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) ? $tax_operator : 'IN';
$tax_args['tax_query'][] = array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $terms,
'operator' => $tax_operator
);
$count++;
endwhile;
if( $more_tax_queries ):
$tax_relation = 'AND';
if( isset( $original_atts['tax_relation'] ) && in_array( $original_atts['tax_relation'], array( 'AND', 'OR' ) ) )
$tax_relation = $original_atts['tax_relation'];
$args['tax_query']['relation'] = $tax_relation;
endif;
$args = array_merge( $args, $tax_args );
}
// If post parent attribute, set up parent
if( $post_parent ) {
if( 'current' == $post_parent ) {
global $post;
$post_parent = get_the_ID();
}
$args['post_parent'] = intval( $post_parent );
}
// Set up html elements used to wrap the posts.
// Default is ul/li, but can also be ol/li and div/div
$wrapper_options = array( 'ul', 'ol', 'div' );
if( ! in_array( $wrapper, $wrapper_options ) )
$wrapper = 'ul';
$inner_wrapper = 'div' == $wrapper ? 'div' : 'li';
$listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $original_atts ) );
if ( ! $listing->have_posts() )
return apply_filters( 'display_posts_shortcode_no_results', wpautop( $no_posts_message ) );
$inner = '';
while ( $listing->have_posts() ): $listing->the_post(); global $post;
$image = $date = $author = $excerpt = $content = '';
if ( $include_title )
$title = '<a class="title" href="' . apply_filters( 'the_permalink', get_permalink() ) . '">' . get_the_title() . '</a>';
if ( $image_size && has_post_thumbnail() )
$image = '<a class="image" href="' . get_permalink() . '">' . get_the_post_thumbnail( get_the_ID(), $image_size ) . '</a> ';
if ( $include_date )
$date = ' <span class="date">' . get_the_date( $date_format ) . '</span>';
if( $include_author )
$author = apply_filters( 'display_posts_shortcode_author', ' <span class="author">by ' . get_the_author() . '</span>' );
if ( $include_excerpt )
$excerpt = ' <span class="excerpt-dash">-</span> <span class="excerpt">' . get_the_excerpt() . '</span>';
if( $include_content ) {
add_filter( 'shortcode_atts_display-posts', 'be_display_posts_off', 10, 3 );
$content = '<div class="content">' . apply_filters( 'the_content', get_the_content() ) . '</div>';
remove_filter( 'shortcode_atts_display-posts', 'be_display_posts_off', 10, 3 );
}
$class = array( 'listing-item' );
$class = sanitize_html_class( apply_filters( 'display_posts_shortcode_post_class', $class, $post, $listing, $original_atts ) );
$output = '<' . $inner_wrapper . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $excerpt . $content . '</' . $inner_wrapper . '>';
// If post is set to private, only show to logged in users
if( 'private' == get_post_status( get_the_ID() ) && !current_user_can( 'read_private_posts' ) )
$output = '';
$inner .= apply_filters( 'display_posts_shortcode_output', $output, $original_atts, $image, $title, $date, $excerpt, $inner_wrapper, $content, $class );
endwhile; wp_reset_postdata();
$open = apply_filters( 'display_posts_shortcode_wrapper_open', '<' . $wrapper . $wrapper_class . $wrapper_id . '>', $original_atts );
$close = apply_filters( 'display_posts_shortcode_wrapper_close', '</' . $wrapper . '>', $original_atts );
$return = $open;
if( $shortcode_title ) {
$title_tag = apply_filters( 'display_posts_shortcode_title_tag', 'h2', $original_atts );
$return .= '<' . $title_tag . ' class="display-posts-title">' . $shortcode_title . '</' . $title_tag . '>' . "\n";
}
$return .= $inner . $close;
return $return;
}
/**
* Turn off display posts shortcode
* If display full post content, any uses of [display-posts] are disabled
*
* #param array $out, returned shortcode values
* #param array $pairs, list of supported attributes and their defaults
* #param array $atts, original shortcode attributes
* #return array $out
*/
function be_display_posts_off( $out, $pairs, $atts ) {
$out['display_posts_off'] = true;
return $out;
}
/**
* Convert string to boolean
* because (bool) "false" == true
*
*/
function be_display_posts_bool( $value ) {
return !empty( $value ) && 'true' == $value ? true : false;
}
You'll want to edit you $output variable which is on line 243 on the code you've given above.
A simple amendment to add a static url will do fine, something like this:
$static_link = 'http://www.test.com/test';
$output = '<' . $inner_wrapper . ' class="' . implode( ' ', $class ) . '">' . $image . $title . $date . $author . $excerpt . $content . 'Read more' . '</' . $inner_wrapper . '>';
Amend this to your requirements, say adding a proper link from the database.
Hope this helps.
I've been reading a lot of how to customize excerpt function in WordPress but I have no idea how to proceed with this.
The theme that I am using already have 4 pre-customized excerpt functions and the one that I will show here is closest to my desired but still needs to improve.
My question is how to stop erasing HTML formating from my content (line breaks, paragraphs, font variants, etc)?
add_shortcode('display_news_s5', 'be_display_posts_shortcode5');
function be_display_posts_shortcode5($atts) {
// Pull in shortcode attributes and set defaults
extract( shortcode_atts( array(
'post_type' => 'post',
'post_parent' => false,
'id' => false,
'tag' => '',
'category' => '',
'offset' => 0,
'posts_per_page' => '1',
'order' => 'DESC',
'orderby' => 'date',
'include_date' => false,
'include_excerpt' => false,
'excerpt_l' => 8,
'taxonomy' => false,
'tax_term' => true,
'tax_operator' => 'IN'
), $atts ) );
// Set up initial query for post
$args = array(
'post_type' => explode( ',', $post_type ),
'tag' => $tag,
'category_name' => $category,
'p' => $id,
'posts_per_page' => $posts_per_page,
'order' => $order,
'orderby' => $orderby,
'offset' => $offset
);
// If Post IDs
if( $id ) {
$posts_in = explode( ',', $id );
$args['post__in'] = $posts_in;
}
// If taxonomy attributes, create a taxonomy query
if ( !empty( $taxonomy ) && !empty( $tax_term ) ) {
// Term string to array
$tax_term = explode( ', ', $tax_term );
// Validate operator
if( !in_array( $tax_operator, array( 'IN', 'NOT IN', 'AND' ) ) )
$tax_operator = 'IN';
$tax_args = array(
'tax_query' => array(
array(
'taxonomy' => $taxonomy,
'field' => 'slug',
'terms' => $tax_term,
'operator' => $tax_operator
)
)
);
$args = array_merge( $args, $tax_args );
}
// If post parent attribute, set up parent
if( $post_parent ) {
if( 'current' == $post_parent ) {
global $post;
$post_parent = $post->ID;
}
$args['post_parent'] = $post_parent;
}
$listing = new WP_Query( apply_filters( 'display_posts_shortcode_args', $args, $atts ) );
$count = 0;
if ( !$listing->have_posts() )
return apply_filters ('display_posts_shortcode_no_results', false );
$inner = '';
while ( $listing->have_posts() ): $listing->the_post(); global $post;
$count++;
if( $count == 1 ){
$style = ' news-main-post';
} else {
$style = ' news-list-posts';
}
$title = '<div class="news-listing-title"><a class="title" href="'. get_permalink() .'">'. get_the_title() .'</a></div>';
if ($include_date == 'true') $date = ' <div class="news-listing-meta"><span class="news-listing-date">'. get_the_date() . '</span><span class="news-listing-comment">('. get_comments_number() .')</span></div>';
else $date = '';
if ($include_excerpt == 'true') $excerpt = '<span>' .excerpt($excerpt_l) . '</span>';
else $excerpt = '';
$output = '<div class="news-listing' . $style . '"><div class="news-listing-item">'. $title . $excerpt . $date . '</div></div>';
$inner .= apply_filters( 'display_posts_shortcode_output', $output, $atts, $title, $excerpt, $date );
endwhile; wp_reset_query();
$open = apply_filters( 'display_posts_shortcode_wrapper_open', '<div class="news-listing-wrapper-s3">' );
$close = apply_filters( 'display_posts_shortcode_wrapper_close', '<div class="clear"></div></div>' );
$return = $open . $inner . $close;
return $return;
}
Have a look here: LINK looks like its doing what you want to acchieve.