get_field() of ACF plugin wordpress assign to javascript value - wordpress

Im having a problem of assigning data of get_field() to a javascript variable
<?php $event_message = get_field('event_message');?>
<script>
var event_message = '<?php echo $event_message; ?>';
console.log(event_message);
</script>
it gave me empty value. Am I missing something?

Your code looks fine. However, be sure to be inside the Wordpress loop or else you would have to pass the $post_id parameter to your get_field() call, like this :
<?php $event_message = get_field('event_message', $post_id); ?>
If that doesn't do the trick, we're gonna need more code to find what's wrong !

You can probably just assign the Javascript variable directly from the ACF field. So try changing your code to:
<script>
var event_message = '<?php the_field("event_message"); ?>';
console.log(event_message);
</script>
That should work, hopefully!

Related

I need help generating a custom URL based on the user ID

I need help on how generate a unique URL based on a users ID for example
var htmlstring = "https://www.google.com" + "?" + <?php get_userdata( $userid ); ?>
This is the JS I have that creates a hyperlink in the html:
Click <script type="text/javascript">
function zs_open_window(url, height, width){var leftPos = 0;var topPos = 0;if(screen){leftPos = (screen.width - width) / 2;topPos = (screen.height - height) / 2;window.open(url, null, 'width='+width+',height='+height+',left='+leftPos+',top='+topPos+', toolbar=0, location=0, status=1, scrollbars=1, resizable=1');}}</script>HERE
I need to get the Wordpress username as a JS variable so I can modify the href to be href="https://survey.zohopublic.com/zs/NbB3YM?USERNAME".
I know how to modify the href, I just don't know how push a username into a JS variable?
Ben
You could setup a global variable on all pages that holds that information by adding this to your header.php file just above the <?php wp_head(); ?> line.
<?php
// Gets the current user.
$current_user = wp_get_current_user();
// Checks if the visitor is logged in.
if ( $current_user->ID !== 0 ) {
// Output JS
?>
<script type="text/javascript">
var htmlstring = "https://survey.zohopublic.com/zs/NbB3YM?username=<?php echo $current_user->user_login ?>";
</script>
<?php
} // End if
?>
You can then use htmlstring in any of your other JS functions or code. I also added the username= parameter as you might need that so you can pass it to something else. If you don't, just remove it.

How to add a nonce to an inline script in WordPress

I'm trying to add a nonce to the inline scripts inserted in WordPress by wp_add_inline_script and wp_localize_script, but I can't figure out how to do it. It looks there are no WordPress filters for that. My goal is to have a nonce for inline scripts, so I can define a Content Security Policy that would not break common plugins that insert inline scripts. At the end the result should be something that looks like:
<script type="text/javascript" nonce="xxxxxxxxxx">....</script>
where xxxxxxxx is the nonce.
Do you have any ideas?
As the HTML for inline scripts are generated by the WordPress code
sprintf( "<script type='text/javascript'>\n%s\n</script>\n", ... )
you cannot add an attribute to the HTML script element using wp_add_inline_script() as <script type='text/javascript'> is hard coded.
However, the filter 'script_loader_tag' will allow you to change the HTML for script elements just before it is outputted by WordPress.
Note that the filter 'script_loader_tag' will not be applied to script elements added by calling wp_localize_script() since these are outputted by the WordPress code:
echo "<script type='text/javascript'>\n"; // CDATA and type='text/javascript' is not needed for HTML 5
echo "/* <![CDATA[ */\n";
echo "$output\n";
echo "/* ]]> */\n";
echo "</script>\n";
Since these are echoed and <script type='text/javascript'> is hard coded you cannot add an attribute to the HTML script elements of wp_localize_script().
Try to use wp_enqueue_scripts hook
function my_special_inline_script() {
?>
<script>
// your JS code
</script>
<?php
}
add_action( 'wp_enqueue_scripts', 'my_special_inline_script', 1, 1 );
or
function theme_prefix_enqueue_script() {
wp_add_inline_script( 'jquery', 'jQuery(document).ready(function(){});' );
}
add_action( 'wp_enqueue_scripts', 'theme_prefix_enqueue_script' );
Bit late to the party but I just faced this exact problem for the same reasons.
I solved it for wp_add_inline_script by a bit of simple str_replace action.
add_filter( 'script_loader_tag', 'add_nonce_to_script_tag', 10, 3 );
function add_nonce_to_script_tag( $tag, $handle, $src ) {
// Check the $handle and respond accordingly
if ( $handle === 'my-script' ) {
$nonce_value = wp_create_nonce('my__script__nonce'); // or ref to an existing nonce
$replace = sprintf("javascript' nonce='%s'>", $nonce_value );
$tag = str_replace( "javascript'>", $replace, $tag);
}
return $tag;
}
// Then... $data is the inline JS from wherever
wp_add_inline_script('my-script', $data, 'before');
Once the inline script loads, I am seeing the script tag output with a nonce attribute. This is working fine with my Content-Security-Policy.
Check this out
"WordPress 5.7 adds a handful of new functions that enables passing attributes, such as async or nonce"

Visual Composer Grid with do_action shortcode is not working

I have visual composer which is packed with total theme. When I put the following grid short code in my page in the editor it works correctly.
[vc_basic_grid post_type="post_type" max_items="10" item="masonryGrid_SlideFromLeft" grid_id="vc_gid:1458178666639-80ebf3775500c87d35de078c3422fe96-10" taxonomies="555"]
However, when I call the exact same code using do_action it gives the following javascript error. I checked the html output and it is the same using do_action like putting the short code in editor.
Error: Syntax error, unrecognized expression: {'status':'Nothing found'}
s
Any help is greatly appreciated.
Well, you can't output contents directly in your templates by using core shortcodes of VC like that.
1. Problem:
For security, besides nonce, VC uses page_id and shortcode_id to check AJAX request/respond data.
The shortcode_id is automatically generated by VC, you can not harcode it.
For example, this is the shortcode you see on admin editor screen:
[vc_basic_grid post_type="post_type" max_items="10" item="masonryGrid_SlideFromLeft" grid_id="vc_gid:1458178666639-80ebf3775500c87d35de078c3422fe96-10" taxonomies="555"]
Let say the page ID is 4269, this is the generated HTML code on front-end:
<!-- vc_grid start -->
<div class="vc_grid-container-wrapper vc_clearfix">
<div class="vc_grid-container vc_clearfix wpb_content_element vc_masonry_grid" data-initial-loading-animation="zoomIn" data-vc-grid-settings="{"page_id":4269,"style":"all-masonry","action":"vc_get_vc_grid_data","shortcode_id":"1458178666639-80ebf3775500c87d35de078c3422fe96-10","tag":"vc_masonry_grid"}" data-vc-request="http://example.com/wp-admin/admin-ajax.php" data-vc-post-id="4269" data-vc-public-nonce="0641473b09">
</div>
</div>
<!-- vc_grid end -->
Now, if page_id and shortcode_id don't match each other, {'status':'Nothing found - $shorcode_id'} will be throw out and no contents will be displayed.
You can find out more inside vc_grid.min.js file.
2. Solution:
Generate a fake page with VC, then copy generated html code to your template file.
Create a template with VC directly.
Use Shorcode Mapper to create your own shorcode.
First you build a new page and add a grid post on it,
then we get
_vc_post_settings
post meta , and try to build a new one
then update post meta data
now we can by pass VC Ajax security check
in the following code "1513628284966-37b8c3ca-d8ec-1" is VC generated guid
you should change it to yours .
$meta = get_post_meta(1365,'_vc_post_settings');
$settings = array();
#$settings['vc_grid_id'] = $meta[0]['vc_grid_id'];
$key = random_int(1513628284966,9513628284966);
$settings['vc_grid_id']['shortcodes'][''.$key.'-37b8c3ca-d8ec-1'] = $meta[0]['vc_grid_id']['shortcodes']['1513628284966-37b8c3ca-d8ec-1'];
$settings['vc_grid_id']['shortcodes'][''.$key.'-37b8c3ca-d8ec-1']['atts']['custom_query'] = "tag=shop";
$settings['vc_grid_id']['shortcodes'][''.$key.'-37b8c3ca-d8ec-1']['atts']['grid_id'] = ''.$key.'-37b8c3ca-d8ec-1';
$n = add_post_meta(1365,'_vc_post_settings',$settings);
return do_shortcode("[vc_basic_grid post_type=\"custom\" show_filter=\"yes\" filter_style=\"dropdown\" item=\"5959\" grid_id=\"vc_gid:".$key."-37b8c3ca-d8ec-1\" filter_source=\"post_tag\" custom_query='tag=".$tag."']");
I've solved.
I had the same problems, with the Visual Composer Editor offered by WpBakery
https://wpbakery.com/
and after understanding the connection between the IDs of the block, and the ID of the Post, I put more attention to the settings of the Block.
There is infact one field called "Element ID", and here we have to put our ID of the Post we are editing.
In my case the Block was a block containing some Posts.
After saving, and viewing the page without the Editor, I was finally able to see the block, and not the message
{"status":"Nothing found"}
I found a solution to this problem.
I modified the woocommerce category template and linked to the woocommerce_archive_description hook to add additional descriptions from some pages, for this I got their id, and then display the content.
echo do_shortcode($post->post_content);
The gallery(media grid) didn't work because there was a mismatch between the page id and the shortcode id. Therefore, the logical solution was to redefine the global variable $post to the $post of the page from which I get the content.
global $post;
$post = get_post( $id );
And it turns out that the post id matches.
After that, don't forget to return the normal $post value;
wp_reset_postdata();
By the way - use this option to load custom styles for wpbakery elements.
echo '<style type="text/css" data-type="vc_shortcodes-custom-css">' . get_post_meta( $id, '_wpb_shortcodes_custom_css', true ) . '</style>';
The whole code
function extra_product_category_desc(){
if( is_product_category() ){
$id = get_term_meta (get_queried_object()->term_id, 'pageId', true);
if($id !== ''){
global $post;
$post = get_post( $id );
echo do_shortcode($post->post_content);
echo '<style type="text/css" data-type="vc_shortcodes-custom-css">' . get_post_meta( $id, '_wpb_shortcodes_custom_css', true ) . '</style>';
wp_reset_postdata();
}
}
}
add_action( 'woocommerce_archive_description', 'extra_product_category_desc', 11 );
You may also try with do_shortcode('');
Like
do_shortcode('[vc_basic_grid post_type="post_type" max_items="10" item="masonryGrid_SlideFromLeft" grid_id="vc_gid:1458178666639-80ebf3775500c87d35de078c3422fe96-10" taxonomies="555"]');
Best Regards,

It is possible to add php to this script in Wordpress?

I use this script to filter posts from single category. I based on tags which generate also a class. It is possible to generate this script by WordPress with all tags from my site?
For example below 2 scripts (now I have 12 scripts of this type):
$(document).ready(function(){
$('tr').show();
$("#aipa").click(function(){
$("tr").show();
$('tr:not(:first)').not(".aipa").slideToggle('fast');
});
});
$(document).ready(function(){
$('tr').show();
$("#ris").click(function(){
$("tr").show();
$('tr:not(:first)').not(".ris").slideToggle('fast');
});
});
Now when I add new tags I must manually add another script:
$(document).ready(function(){
$('tr').show();
$("#next-tag").click(function(){
$("tr").show();
$('tr:not(:first)').not("#next-tag").slideToggle('fast');
});
});
Here's a way to do this. This assumes that you're using the standard blog tag system, and that your variable you're using as your ID and class is the tag's slug. Alter it as needed for your needs.
<?php $tags = get_tags(); ?>
<script>
$(document).ready(function(){
<?php foreach ( $tags as $tag ) { ?>
$('tr').show();
$("#<?php echo $tag->slug; ?>").click(function(){
$("tr").show();
$('tr:not(:first)').not(".<?php echo $tag->slug; ?>").slideToggle('fast');
});
<?php } ?>
});
</script>
This will create a single document ready function, and then generate multiple click functions.

Is there a concise Wordpress function for building a page link from an ID?

I'm currently building links like this:
<?php echo get_the_title(111); ?>
I was building links like this using the WPML plugin (but steering away from it due to various reasons):
<?php icl_link_to_element(111); ?>
This builds a link similar to my first example.
So my question is is there a native Wordpress function that does this? I'm sure there must be, but cannot find the solution anywhere. I'm looking to reduce my markup...
Thanks!
EDITED WITH ANSWER
This is how I built my custom function:
function build_pretty_link($id,$link_title='') {
if($link_title=='') {
$link_title = get_the_title($id);
}
$link_url = get_permalink($id);
echo "{$link_title}";
}
WordPress give a function that print an anchor tag with the title and the url, but you have to be in a the loop (http://codex.wordpress.org/Function_Reference/permalink_anchor).
I suggest you to create your own function (the functions.php file in your theme is here for that).
You can do someting like that :
function vp_link_to($post_id) {
echo '<?php echo get_the_title($post_id); ?>';
}
get_permalink(x);
Where the ID of the page is x and wrap this in whatever you need, so
$id = 10;
$link = get_permalink($id);
echo 'Linked text';

Resources