get_post_meta() returns empty - wordpress

I'm doing a basic shortcode for translating a text in the footer of a wordpress site, and I'm using the get_post_meta() for identifing the language in a meta tag (which I'm adding with a plug in for inserting html code in the header) but it returns empty I'm wondering if this is because the plugin and the order in which he creates the elements(first he executes my shortcode and then the plugin) or if it is something else.
function text_Footer($atts, $content=null){
extract(shortcode_atts(array(
'id' => ''
), $atts));
$ID = get_the_ID();
$lang = get_post_meta(ID,'language',true);
if($lang == 'portuguese')
{
$output='<p>Text in portuguese</p>';
}
else
{
//echo $lang."nope";
$output = '<p>Text in spanish</p>';
}
return $output;
}

get_the_ID() function must be within The Loop.
if you want to extract id from shortcode, just need to use it in write way: $lang = get_post_meta($id,'language',true);

Related

Advanced Custom Fields: Display As Bullet Points

I have a custom checkbox field created in Wordpress where the user can select various facilities available at a listed property.
I am building a page template using Elementor.
When I import the data from ACF, it displays as a comma separated list.
Is there any way I can instead get this to display as as a bulleted list?
Here is a code to get the output data from ACF as a bulleted list -
<?php
$arr = get_the_field('field_name');
$str = explode (",", $arr);
echo '<ul>';
foreach($str as $s){
echo '<li>'.$s.'</li>';
}
echo '</ul>';
?>
I hope this is what you are looking for.
You could try using a plugin that let's you create php code snippets and run them with a shortcode such as this: https://it.wordpress.org/plugins/insert-php/
Once you created the php snippet you could try to run it with a shortcode using Elementor's shortcode widget.
I'd slightly adjust Tahmid's excellent answer. In order to allow for empty lines (without a bullet) use this in you functions.php file:
/**
* create a ACF text field with bullets
* Empty lines stay empty
* #param string $field_name Name of the field to bullet
*/
function acf_bullets(string $field_name): void {
$format_acf_bullet = function(
string $value,
int $post_id,
array $form ):string {
if( empty($value) ) {
return '';
}
$lines = explode( "\n", $value );
$result = "<ul class=\"theme-ul\">\n";
foreach( $lines as $line) {
if( strlen($line)<=1 ) { // empty line, start a new list
$result .= "</ul><p/><ul class=\"theme-ul\">\n";
} else {
$result .= "<li>".$line."\n";
}
}
$result .= "</ul>\n";
return $result;
};
add_filter("acf/format_value/name=$field_name", $format_acf_bullet, 10, 3);
}
Call this with acf_bullets('your-fieldname-here');

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',*/
},
}

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"]

Use postmeta in wordpress shortcode

Trying to get my post meta from posts using shrotcodes and then displaying it on the content.This is the code that's trying to do this:
$string = '';
$custom_content = get_post_custom($post->ID);
if( $my_query->have_posts() ) {
while ($my_query->have_posts()) : $my_query->the_post();
$content = get_the_content();
$bonus = $custom_content["bonus"];
$string .= $content . $bonus . '<br>';
endwhile;
}
return $string;
It's not working as the custom content returns empty. Whats wrong? Thanks in advance
I don't think you got the shortcode idea, you should read some info about add_shortcode() also you can use get_post_meta() to retriev the metadata from the database.
Here is an example on how you can achieve this but this will only work with the main loop (as default):
<?php
//you can put this code in functions.php or you can build a plugin for it
function metadata_in_content($attr) {
//this is the function that will be triggerd when the code finds the proper shortcode in the content; $attr is the parameter passed throw the shortcode (leave null for now)
global $wpdb, $wp_query;
//we need global $wpdb to query the database and to get the curent post info
if (is_object($wp_query->post)) {
$post_id = $wp_query->post->post_id;// here we save the post id
$metadata = get_post_meta( $post_id, $key, $single ); // here we get the needed meta, make sure you place the correct $key here, also if you don't want to get an array as response pass $single as "true"
return $metadata; // this finally replaces the shortcode with it's value
}
}
add_shortcode('insert_metadata', 'metadata_in_content');
//the above code hooks the metadata_in_content function to the [insert_metadata] shortcode
?>
Now all it's left to do is to place [insert_metadata] in the post content and things should work.

FeedWordPress - Save string as Custom Field

I am using the FeedWordPress plugin http://wordpress.org/extend/plugins/feedwordpress/ to pull posts from one site to another.
I have written a filter that after some help from Stack users successfully scans the $content and extracts the image URL into $new_content
define('FWPASTOPC_AUTHOR_NAME', 'radgeek');
add_filter(
/*hook=*/ 'syndicated_item_content',
/*function=*/ 'fwp_add_source_to_content',
/*order=*/ 10,
/*arguments=*/ 2
);
function fwp_add_source_to_content ($content, $post) {
// Use SyndicatedPost::author() to get author
// data in a convenient array
$content = $post->content();
// Authored by someone else
if( preg_match( '/<img[^>]+src\s*=\s*["\']?([^"\' ]+)[^>]*>/', $content, $matches ) ) {
$new_content .= 'URL IS '.$matches[0].'';
return $new_content;
}
else
{
}
}
What I wanted to do now was save this URL into a custom field instead of just returning it. Has anyone achieved anything similar?
So as I understand it, the plugin grabs content from external RSS feeds and creates them as posts in your website.
If this is the case, using your filter you should be able to grab the post ID within the $post variable.
So all you need is the add_post_meta() function to add a custom field to the specific post.
So including your code above it should look something like:
define('FWPASTOPC_AUTHOR_NAME', 'radgeek');
add_filter(
/*hook=*/ 'syndicated_item_content',
/*function=*/ 'fwp_add_source_to_content',
/*order=*/ 10,
/*arguments=*/ 2
);
function fwp_add_source_to_content ($content, $post) {
// Use SyndicatedPost::author() to get author
// data in a convenient array
$content = $post->content();
// Authored by someone else
if( preg_match( '/<img[^>]+src\s*=\s*["\']?([^"\' ]+)[^>]*>/', $content, $matches ) ) {
$new_content .= 'URL IS '.$matches[0].'';
//Add custom field with author info to post
add_post_meta($post->ID, 'post_author', $new_content);
return $new_content;
}
}

Resources