Wordpress : ShortCode and variable - wordpress

I'm trying to get a value from a ShortCode into a variable for use it in my template file. How can i do that?
Here is my code :
In the post, the short code :
[reference_prix]1-214eddz[/reference_prix]
My plugin code :
$bl_reference_prix = "";
add_shortcode('reference_prix', 'get_blref_prix');
function get_blref_prix( $atts, $reference = null ) {
global $bl_reference_prix;
$bl_reference_prix = $reference;
}
But $bl_reference_prix is still empty.
I've try with $GLOBAL[] but i've the same issu.
What is the best practice for get a value write by the user in a wordpress post and display (or use it) in the template file?

I think the best practice is to use the atts parameter.
// Add Shortcode
function get_blref_prix( $atts ) {
// Attributes
extract( shortcode_atts(
array(
'bl_reference_prix' => '',
), $atts )
);
}
add_shortcode( 'reference_prix', 'get_blref_prix' );
The user of the shortcode will just have to do the following in the editor:
[reference_prix bl_reference_prix="some value by the user"]
And then maybe you can try using the Options API. Add and delete after use.

I've do this and it's working now as :
//Plugin
function get_blref_prix( $atts ) {
global $bl_plugin_refprix, $bl_plugin_refprix_up;
// Attributes
extract( shortcode_atts(
array(
'reference' => '',
'up' => '',
), $atts )
);
$bl_plugin_refprix = $reference;
$bl_plugin_refprix_up = $up;
}
add_shortcode( 'bl_refprix', 'get_blref_prix' );
In the template file (Important : After the function "the_content"!) :
while(have_posts()):the_post();
echo the_content();
endwhile;
echo $bl_plugin_refprix;
In the Post :
[bl_refprix reference="123" up="456"]

Related

Add different WordPress excerpt formats to different templates

I added the following code to my functions.php file in WordPress 6.1.1 to display excerpts.
function new_excerpt_length($length) {
return 100;
}
add_filter('excerpt_length', 'new_excerpt_length');
function new_excerpt_more($more) {
return '...';
}
add_filter('excerpt_more', 'new_excerpt_more');
...but I also have a use case to show the full excerpt without a read more link.
On page template 1 I add the below code to display the excerpt:
<?php echo the_excerpt(); ?>
...and it displays the excerpt as per the functions.php file but how do I create a 2nd excerpt without the read more link and apply it to page template 2?
Is there a parameter I can use within the_excerpt(parameter); or can I use something like wp_trim_excerpt https://developer.wordpress.org/reference/functions/wp_trim_excerpt/ maybe?
I came across the below code that is supposed to do what I want
function wpex_get_excerpt( $args = array() ) {
// Default arguments.
$defaults = array(
'post' => '',
'length' => 40,
'readmore' => false,
'readmore_text' => esc_html__( 'read more', 'text-domain' ),
'readmore_after' => '',
'custom_excerpts' => true,
'disable_more' => false,
);
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_defaults', $defaults );
// Parse arguments, takes the function arguments and combines them with the defaults.
$args = wp_parse_args( $args, $defaults );
// Apply filters to allow child themes mods.
$args = apply_filters( 'wpex_excerpt_args', $args );
// Extract arguments to make it easier to use below.
extract( $args );
// Get the current post.
$post = get_post( $post );
// Get the current post id.
$post_id = $post->ID;
// Check for custom excerpts.
if ( $custom_excerpts && has_excerpt( $post_id ) ) {
$output = $post->post_excerpt;
}
// No custom excerpt...so lets generate one.
else {
// Create the readmore link.
$readmore_link = '' . $readmore_text . $readmore_after . '';
// Check for more tag and return content if it exists.
if ( ! $disable_more && strpos( $post->post_content, '<!--more-->' ) ) {
$output = apply_filters( 'the_content', get_the_content( $readmore_text . $readmore_after ) );
}
// No more tag defined so generate excerpt using wp_trim_words.
else {
// Generate an excerpt from the post content.
$output = wp_trim_words( strip_shortcodes( $post->post_content ), $length );
// Add the readmore text to the excerpt if enabled.
if ( $readmore ) {
$output .= apply_filters( 'wpex_readmore_link', $readmore_link );
}
}
}
// Apply filters and return the excerpt.
return apply_filters( 'wpex_excerpt', $output );
}
Output using:
<?php echo wpex_get_excerpt ( $defaults = array(
'length' => 40,
'readmore' => true,
'readmore_text' => esc_html__( 'read more', 'wpex-boutique' ),
'custom_excerpts' => true,
) ); ?>
...but doesn't seem to workas intended. Outputs the excerpt with no link but the args don't see to work when changed. Would be perfect for my use otherwise. Maybe someone sees how to fix this code?
Thanks

Wordpress single profile page with acf gallery sharing images

Good afternoon devs, I develop a project that consists of users profiles with a record created with fields from the ACF, including the image gallery field, my problem is ... as I only use one page to display this profile, the image gallery is makes it shared even with the option of "attached to the post", as I only use one page for this, example "/profile?userid=userid".
Is there any other good practice for doing this?
I would like suggestions.
one part profile edit
function acf_profile_edit( $atts ) {
$a = shortcode_atts( array(
'field_group' => ''
), $atts );
$uid = get_current_user_id();
if ( ! empty ( $a['field_group'] ) && ! empty ( $uid ) ) {
$options = array(
'post_id' => 'user_'.$uid,
'field_groups' => array( intval( $a['field_group'] ) ),
'return' => add_query_arg( 'updated', 'true', get_permalink() )
);
ob_start();
acf_form( $options );
$form = ob_get_contents();
ob_end_clean();
}
return $form;
}
add_shortcode( 'profile_edit', 'acf_profile_edit' );
Edit...
This code resolved my problem
add_filter('ajax_query_attachments_args', 'restrict_images_to_user');
function restrict_images_to_user($query) {
$gallery_images = 'field_5e4d799b34145';
$gallery_videos = 'field_5e5597e37f2c7';
if ( isset($_POST['query']['_acfuploader'] )
&& ( isset($_POST['query']['_acfuploader']) == $gallery_images || isset($_POST['query']['_acfuploader']) == $gallery_videos ) ) {
$author = get_current_user_id();
$query['author'] = $author;
}
return $query;
}
If you are using one page, use a page template called page-profile.php, the bit after page- must match the name of the page you have assigned.
Then use the WordPress Post Loop:
if (have_posts()) :
while (have_posts()) :
the_post();
the_content();
endwhile;
endif;
You can assign a username to the posts and the posts loop will only return the stuff associate with that username.
Another way would be to get the current username, then can you make an extra acf field with the username in and then do a check.
This is an example and will be exactly correct, but may be able to help you with suggestions.
If(content && username == currentuser)
{
$content = acf content;
}
then later in your page you can echo the content where you need it and will only be the content for the current username, or you can also do it with the user id.

Use Wordpress shortcode function to render Gutenberg block, sending the attributes as parameters

I have a shortcode that generates a gallery, given the gallery ID.
function rb_scroll_gallery_shortcode( $atts, $content ) {
$a = shortcode_atts( array(
'id' => -1,
), $atts );
$gallery_ID = $a['id'];
$output = '';
if($gallery_ID != -1){
ob_start();
$gallery = new RB_Scroll_Gallery($gallery_ID);
$gallery->render();
$output = ob_get_clean();
}
return $output;
}
add_shortcode( 'rb_scroll_gallery', 'rb_scroll_gallery_shortcode' );
Now, I've made a Gutenberg block that works perfectly in the editor. You can select a gallery and it will save. However, I dont want to repeat code and have the html in the save property and in the php code.
So I was wondering if there is a way to use that same rb_scroll_gallery_shortcode function to render the block in the front end.
I've seen that you can use register_block_type and set the render_callback to rb_scroll_gallery_shortcode, but I need the ID selected in the block to send it to the function in the $atts array
//This uses the shortcode funtion, but doesn't gives the gallery ID
register_block_type( 'cgb/block-rb-scroll-gallery-block', array(
'render_callback' => 'rb_scroll_gallery_shortcode',
) );
You can try to Convert a Shortcode to a Gutenberg Block and after use in your theme,
Registering the Dynamic Block Callback in PHP
/**
* Register the GitHub Gist shortcode
*/
function gggb_init() {
add_shortcode( 'github-gist', 'gggb_render_shortcode' );
register_block_type( 'github-gist-gutenberg-block/github-gist', array(
'render_callback' => 'gggb_render_shortcode',
) );
}
add_action( 'init', 'gggb_init' );
When your block is rendered on the frontend, it will be processed by your render callback:
function gggb_render_shortcode( $atts ) {
if ( empty( $atts['url'] )
|| 'gist.github.com' !== parse_url( $atts['url'], PHP_URL_HOST ) ) {
return '';
}
return sprintf(
'<script src="%s"></script>',
esc_url( rtrim( $atts['url'], '/' ) . '.js' )
);
}
**Note:** this render callback is intentionally different than the Gutenberg block’s edit callback. Our preference is to use GitHub’s provided JavaScript embed code because this lets GitHub change the embed’s behavior at a future date without requiring a developer to make changes.
Refer link for get more information, https://pantheon.io/blog/how-convert-shortcode-gutenberg-block
I've found out the little thing that messed up my code. The problem wasn't that the render_callback() wasn't getting any attributes (though it wasn't), but it was that the editor wasn't saving them because I forgot to remove some testing data from the attribute galleryID
In the registerBlockType:
The save() method should return null.
The attribute should not have a selector data, since it is used to find the value on the markup return by the save(), wich in this case returns null. I've forgot to remove this data, thats why the attribute wasn't being saved.
attributes: {
galleryID: {
type: 'string',
//This data should only be set if the value can be found in the markup return by save().
//Since save() returns null, we let it out
/*source: 'attribute',
/*attribute: 'data-gallery-id',
/*selector: '.rb-scroll-gallery-holder',*/
},
}

How to manage selected post-formats in custom post type

'supports' => array('title','author','post-formats'),
Now display all types of post-formats but i want to display only selected.
like : link,audio,video
I wants to something like this:
you can do it like this :
add_theme_support( 'post-formats', array( 'link', 'audio', 'video' ) );
By default it adds all of the registered formats, but like this, you can choose which to add
You can read about the different formats, and how to add them, in the codex : Codex
EDIT :
If you are working with a child theme, and never want to use the other formats, you can call this :
add_action( 'after_setup_theme', 'childtheme_formats', 11 );
function childtheme_formats(){
add_theme_support( 'post-formats', array( 'aside', 'gallery', 'link' ) );
}
EDIT :
According to the comment, you only want this on a single post type :
Then you can do like this :
<?php add_post_type_support( $post_type, $supports ) ?>
Where $support can be a string or an array : so in your task :
So you might be able to do something like this:
function test_add_formats_support_for_cpt() {
add_post_type_support( 'yourCustomPostType', 'post-formats', array('link', 'audio', 'video') );
}
add_action( 'init', 'test_add_formats_support_for_cpt' );
This is untested, so I am not sure if it works - let me know
You can limit or manage the custom post type formats by overwriting the default post formats.
create a function that will return an array of the post formats that our post type supports like audio, gallery, image, and video.
function customposttype_allowed_formats() {
return array( 'audio', 'gallery', 'image', 'video' );
}
We will use "theme support" system and change the theme-supported format and will limit to our post types dashboard screens so that it won’t mess with other post types
add_action( 'load-post.php', 'support_customposttype_filter' );
add_action( 'load-post-new.php', 'support_customposttype_filter' );
add_action( 'load-edit.php', 'support_customposttype_filter' );
function support_customposttype_filter() {
$screen = get_current_screen();
// Return if not customposttype screen.
if ( empty( $screen->post_type ) || $screen->post_type !== 'custom_post_type' )
return;
// Check theme supports formats.
if ( current_theme_supports( 'post-formats' ) ) {
$formats = get_theme_support( 'post-formats' );
// If we have formats, add theme support for only the allowed formats.
if ( isset( $formats[0] ) ) {
$new_formats = array_intersect( $formats[0], customposttype_allowed_formats() );
// Remove post formats support.
remove_theme_support( 'post-formats' );
// If the theme supports the allowed formats, add support for them.
if ( $new_formats )
add_theme_support( 'post-formats', $new_formats );
}
}
// Filter the default post format.
add_filter( 'option_default_post_format', 'customposttype_format_filter', 95 );
}
There is a filter on the default post format at the end here we can overwrite the default post formats if it's not one of the approved formats (audio, gallery, image, and video).
function customposttype_format_filter( $format ) {
return in_array( $format, customposttype_allowed_formats() ) ? $format : 'standard';
}

Use Shortcode in Shortcode (insert post meta field value)

i have a shortcode from a plugin which i cant modify... This shortcode has some arguments ex. [some_shortcode value=""] - I tried to input the value from post meta as argument for this shortcode, but its not working - here is the code...
This is the code from shortcode i created ( it returns values from post meta )
function test_shortcode( $string ) {
extract( shortcode_atts( array(
'string' => 'string'
), $string));
// check what type user entered
switch ( $string ) {
case 'first':
return get_post_meta( get_the_ID(), 'post_meta_one', true );
break;
case 'second':
return get_post_meta( get_the_ID(), 'post_meta_two', true );
break;
}
}
add_shortcode('test', 'test_shortcode');
Now i want to insert this shortcode in the existing shortcode from the plugin on my page.
For example: [some_shortcode value='[test string="first"]']
It isnt working like this. Thanks for help!
It will not work to insert the shortcode in the existing shortcode like you provided. Your shortcode should have opportunity to process the provided shortcode as attribute.
You should to use the do_shortcode() in your shortcode. You have
[some_shortcode value='[test string="first"]']
and want to use returned value of [test string="first"] which is first in your shortcode. Your code will be:
function some_shortcode($atts){
$atts = shortcode_atts(array(
'value' => ''
), $atts);
$second_shortcode_value = do_shortcode($atts['value']);
//some code
return $something;
}
add_shortcode('some_shortcode', 'some_shortcode');
The variable $second_shortcode_value will containt the output of the [test string="first"] shortcode.
P.S. Avoid of using exctract() function just because it can make your code hard readable.
EDIT:
Here is solution dinamically add attributes to [some_shortcode] value attribute.
function my_shortcode($atts){
$atts = shortcode_atts(array(
'str' => ''
), $atts);
switch ( $atts['str'] ) {
case 'first':
$modified = get_post_meta( get_the_ID(), 'leweb_gender', true );
break;
default:
$modified = '';
}
if(!empty($modified)) {
$second_shortcode_with_value = do_shortcode("[some_shortcode value='$modified']");
}else{
$second_shortcode_with_value = do_shortcode('[some_shortcode]');
}
return $second_shortcode_with_value;
}
add_shortcode('some_shrt', 'my_shortcode');
What we are doing: instead of calling [some_shortcode value='something'] we are generating something into our shortcode and getting content like
[some_shrt str="first"]

Resources