Getting shortcode with multiple attributes - php

I want to create shortcode with multiple attributes.
But I am only able to do with single not multiple attributes.
I am able only this :
add_shortcode('test','get_shortcode');
But I want to create shortcode like this :
add_shortcode('test id=1 title=test','get_shortcode');
and I would like to call this shortcode in my page like this.
do_shortcode('[test id="1" title="test"]');

Hello add in your functions $atts like that
function bartag_func( $atts ) {
$atts = shortcode_atts(
array(
'foo' => 'no foo',
'bar' => 'default bar',
), $atts, 'bartag' );
return 'bartag: ' . $atts['foo'] . ' ' . $atts['bar'];
}
add_shortcode( 'bartag', 'bartag_func' );
It's display result like [bartag foo="koala" bar="bears"]

Related

How to append a custom meta field as a shortcode argument value in WooCommerce

I have created a custom checkbox field _is_group and i would like to be able to use this in the [products...] shortcode.
The currently used workaround is that I create the query with wc_get_products() first and then pass the returned IDs to the standard shortcode, with implode() function:
$group = wc_get_products([
'post_type' => 'product',
'meta_key' => '_is_group',
'meta_value' => 'yes',
'meta_compare' => 'IN',
'return' => 'ids'
]);
echo do_shortcode('[products ids="' . implode(',', $group) . '"]');
Sure it works, but it looks ugly, making unnecessarily two db queries instead of one. I think there is a better way to deal with it, something like that:
[products columns="3" is_group="yes"]
So I decided to ask how to append a custom meta field as a shortcode argument value in Woocommerce . Maybe the solution is to use woocommerce_shortcode_products_query or something else?
Note: I've seen other similar questions and solutions like using custom shortcode inside another shortcode, but that doesn't solve the problem. I care about optimization
You need two parts:
Support your own attribute for the [products] shortcode.
https://developer.wordpress.org/reference/hooks/shortcode_atts_shortcode/
// Add your own attribute
function filter_shortcode_atts_products( $out, $pairs, $atts, $shortcode ) {
// Isset and equal to yes
if ( isset ( $atts['is_group'] ) && $atts['is_group'] == 'yes' ) {
$out['is_group'] = true;
} else {
$out['is_group'] = false;
}
return $out;
}
add_filter( 'shortcode_atts_products', 'filter_shortcode_atts_products', 10, 4 );
Modify the query to use your $query_args
// Modify the query args
function filter_woocommerce_shortcode_products_query( $query_args, $atts, $type ) {
// Target
if ( $type == 'products' && $atts['is_group'] ) {
// Meta query
$query_args['meta_query'] = array(
array(
'key' => '_is_group',
'value' => 'yes',
'compare' => 'IN',
)
);
}
return $query_args;
}
add_filter( 'woocommerce_shortcode_products_query', 'filter_woocommerce_shortcode_products_query', 10, 3 );
SHORTCODE USAGE
In an existing page:
[products columns="3" is_group="yes"]
Or in PHP:
echo do_shortcode('[products columns="3" is_group="yes"]');

If a post belongs to a many categories and I want to show a primary category in Genesis post_meta

On https://broadly.vice.com/en_us they show a single, primary category, if their post belongs to many categories.
How can you choose, on a post by post basis, what primary category to show in the post_meta in a Genesis Child theme?
Here is simple solution.
Use SEO Yoast free plugin https://wordpress.org/plugins/wordpress-seo/ . Which help you make any category primary when there are multiple categories assigned to a post.
See Plugin's interface for Primary cat selection:
Then in your WP theme have following function in functions file and then you can use to echo the category name anywhere as: <?php echo taxo_primary_term_name; ?>
// wp seo yoast get primary category name
function taxo_primary_term_name($taxo){
$wpseo_primary_term = new WPSEO_Primary_Term($taxo, get_the_ID());
$wpseo_primary_term = $wpseo_primary_term->get_primary_term();
return $wpseo_primary_term = get_term($wpseo_primary_term)->name;
}
As of this post date, install the Trunk version of CMB2 (not the plugin).
See See Gist for a backup of this answer.
Put the following inside your functions.php or, better, your functions plugin. Don't add the opening php. Change yourprefix_ in many locations.
<?php
//don't add
/**
*
* Create Metabox and Primary Category Select Field
* Requires CMB2 TRUNK branch NOT the plugin from the repo
* Install CMB2-trunk.zip via plugin interface or incorporate in your theme, read their docs
* https://github.com/WebDevStudios/CMB2/branches
*
*/
function yourprefix_primary_category_selection() {
$prefix = 'yourprefix_';
$cmb_demo = new_cmb2_box( array(
'id' => $prefix . 'metabox',
'title' => esc_html__( 'Primary Category', 'yourtextdomain' ),
'object_types' => array( 'post', ),
'context' => 'side',
'priority' => 'low',
'show_names' => false,
) );
$cmb_demo->add_field( array(
'name' => esc_html__( 'Choose Primary Category', 'yourtextdomain' ),
'desc' => esc_html__( 'Choose primary category for display in post_meta', 'yourtextdomain' ),
'id' => $prefix . 'category_list',
'taxonomy' => 'category',
'type' => 'taxonomy_select',
) );
}
add_action( 'cmb2_admin_init', 'yourprefix_primary_category_selection' );
/**
*
* Add Primary to [post_categories] shortcode replacing the genesis shortcode of the same name
*
*/
function yourprefix_post_primary_category_shortcode( $atts ) {
//* get our CMB2 field and category stuff
$prefix = 'yourprefix_';
$primary_cat = get_post_meta( get_the_ID(), $prefix . 'category_list', true );
$category_id = get_cat_ID( $primary_cat );
$category_link = get_category_link( $category_id );
$category_name = get_cat_name( $category_id );
$defaults = array(
'sep' => ', ',
'before' => __( 'Filed Under: ', 'yourtextdomain' ),
'after' => '',
);
$atts = shortcode_atts( $defaults, $atts, 'post_categories' );
//* fallback to the standard array if the choice in the primary metabox is not set
if( empty( $primary_cat ) ) {
$cats = get_the_category_list( trim( $atts['sep'] ) . ' ' );
} else {
$cats = '' . $category_name . '';
}
//* Do nothing if no cats
if ( ! $cats ) {
return '';
}
if ( genesis_html5() )
$output = sprintf( '<span %s>', genesis_attr( 'entry-categories' ) ) . $atts['before'] . $cats . $atts['after'] . '</span>';
else
$output = '<span class="categories">' . $atts['before'] . $cats . $atts['after'] . '</span>';
return apply_filters( 'genesis_post_categories_shortcode', $output, $atts );
}
add_shortcode( 'post_categories', 'yourprefix_post_primary_category_shortcode' );

WordPress Shortcode - Very puzzling issue?

I am trying to create a 'Pie Chart' shortcode to use in WP. All works fine apart from the percentage number. If it is entered into the array it works fine, but if I remove that number (ie; 100 - as seen in the code below), any number that is entered on the front-end by the user returns empty?? Quite puzzling?
function piechart_inner_shortcode( $atts ) {
extract( shortcode_atts( array(
'data_percentage' => '100',
'title' => 'Title',
), $atts ) );
$output = '<div class="chart"><div class="percentage" data-percent="'. $data_percentage .'"><span>'.$data_percentage.'%</span></div><div class="label"><strong>'.$title.'</strong></div></div>';
return $output;
}
add_shortcode( 'piechart_inner', 'piechart_inner_shortcode' );
And this is the shortcode that needs to be entered on the front-end -
[piechart_inner data-percent="45" title="WordPress"][/piechart_inner]
Which outputs nothing for the data-percent, whatever value is entered?
Many thanks
You are using the wrong variable. You are giving data-percent when you have variable data_percentage
Your shortcode should look like this:
[piechart_inner data_percentage="45" title="WordPress"][/piechart_inner]
Or change the function to following:
function piechart_inner_shortcode( $atts ) {
extract( shortcode_atts( array(
'data-percent' => '100',
'title' => 'Title',
), $atts ) );
$output = '<div class="chart"><div class="percentage" data-percent="'. $data-percent .'"><span>'.$data-percent.'%</span></div><div class="label"><strong>'.$title.'</strong></div></div>';
return $output;
}
add_shortcode( 'piechart_inner', 'piechart_inner_shortcode' );

WordPress: Use shortcode_atts in other function

Is it possible to use variables from shortcode_atts in another function? Here is my idea:
Posting
[gallery ids="1,2,3,...n"]
Function get_gallery_ids()
//get the gallery-ID's from post
function get_gallery_ids($atts) {
extract(shortcode_atts(array(
'ids' => ''
), $atts));
return $ids;
}
Function explode_ids()
//example function with ids
function explode_ids($ids) {
$ids = explode(',' $ids);
}
How do I implement it? The return just echos.
Update
The code above is a part of my own new gallery_shortcode.
remove_shortcode('gallery', 'gallery_shortcode');
add_shortcode('gallery', 'get_gallery_ids');
I have an Idea:
I use examples from the WordPress Codex
http://codex.wordpress.org/Shortcode_API
function bartag_func( $atts ) {
global $post; // this is new
extract( shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts ) );
update_post_meta($post->ID, "gallery_used_atts", $atts); // this is new
return "foo = {$foo}";
}
add_shortcode( 'bartag', 'bartag_func' );
now you are able to get the $atts you are using on a specific post or page by
$att_values = get_post_meta( $post_id, "gallery_used_atts", true );
and then you can use them for whatever you want.

Shortcode Attributes not being passed to handler function

Not sure what but the attributes from the shortcode aren't being passed to the handler function.
Shortcode in Wordpress Post
[k_recipe recipe="snack"]Here is some content[/k_recipe]
Shortcode Function
add_shortcode("k_recipe", "recipe_shortcode");
function recipe_shortcode($attributes, $content){
return "Hi " . $attributes["recipe"] . " Hi " . $content;
}
Shortcode Output
Hi Hi Here is some content
Why isnt the snack value being passed?? Any clue??
here is how to use shortcode with attributes
function bartag_func( $atts ) {
extract( shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts ) );
return "foo = {$foo}";
}
add_shortcode( 'myshortcode', 'bartag_func' );
[myshortcode foo="bar" bar="bing"]
you are missing extract thing
Maybe you need to use the extract function like documentation says:
// [bartag foo="foo-value"]
function bartag_func( $atts ) {
extract( shortcode_atts( array(
'foo' => 'something',
'bar' => 'something else',
), $atts ) );
return "foo = {$foo}";
}
add_shortcode( 'bartag', 'bartag_func' );
http://codex.wordpress.org/Shortcode_API

Categories