On my wordpress page, I have the following loop, which successfully outputs an attachment's caption.
<?php
$the_query = new WP_Query(array( 'post_type' => 'attachment'));
while ( $the_query->have_posts() ) : $the_query->the_post();
$attachment_data = wp_prepare_attachment_for_js();
echo '<h2>'.$attachment_data['caption'].'</h2>'
;?>
Now, I also need to call the attachment caption outside of the loop. This is what I'm trying in functions.php:
function custom_info()
{
global $wp_query;
$query_id = $wp_query->post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $query_id );
wp_register_script( 'custom_data_info');
$info = array(
'data_query' => $attachment_data_query['caption']
);
wp_enqueue_script( 'custom_data_info' );
wp_localize_script('custom_data_info', 'info', $info);
}
if ( !is_admin() ) add_action( "wp_enqueue_scripts", "custom_info", 10 );
And then it would be called in the external javascript file like so:
return info.data_query
I know the custom_info function and javascript file are talking with each other correctly. The problem is with how I am defining $query_id
EDIT: Almost fixed. The problem was that I didn't include a foreach statement, and so the first item in the loop was being repeated over and over again.
I've adjusted below, but for some reason, now the array is empty upon output of info.data_query...
function custom_info(){
global $wp_query;
wp_register_script( 'custom_data_info');
$info = array('data_query' => array());
foreach ( $wp_query->posts as $query_id) {
$attachment_data_query = wp_prepare_attachment_for_js( $query_id );
$info['data_query'][$query_id] = $attachment_data_query['caption'];
}
Are you sure $wp_query will return the correct post ID? In my experience, it's better to use global $post instead. Pass that into wp_prepare_attachment_js() instead:
global $post;
$post_id = $post->ID;
$attachment_data_query = wp_prepare_attachment_for_js( $post_id );
Related
I am new to Stackoverflow and relatively new to WordPress as well. I have been trying to build a custom WordPress theme that also allows you to insert images for categories in the WordPress Dashboard. So far, I have been able to get the image URL saved into the database using the following code:
update_term_meta($term_id, 'custom_image_data', $image_data);
($image_data is an array with the elements: ID, and URL for the image)
However, now I would like to retrieve these two pieces of information and share them with my coresponding Javascript file. So far I have this code:
function image_uploader_js() {
wp_register_script('image_file_uploader_js', get_template_directory_uri() . '/js/image_uploader.js', array('jquery', 'media-upload'));
wp_enqueue_script('image_file_uploader_js');
wp_localize_script('image_file_uploader_js', 'customUploads', array('imageData' => get_term_meta(get_queried_object_id(), 'custom_image_data', true)) ); //**
}
add_action('admin_footer', 'image_uploader_js');
However, when I go into the Google Chrome console and type in CustomUploads it just shows an empty string. But if I were to replace the code get_queried_object_id() with a static number 1 (which corresponds to the $term_id of the category) I get CustomUploads { id: ##, URL: HTTPS://..... } which is the desired result.
My question is why doesn't the original code work and how would I be able to share the id and URL or my category image with my Javascript file?
Make sure that you are on the category page then get_queried_object_id() will return term id. in other pages you will get a different id corresponding to that page.
You can use is_category() to check whether you are on the category page.
function image_uploader_js() {
if( is_category() ){
wp_register_script('image_file_uploader_js', get_template_directory_uri() . '/js/image_uploader.js', array('jquery', 'media-upload'));
wp_enqueue_script('image_file_uploader_js');
wp_localize_script('image_file_uploader_js', 'customUploads', array('imageData' => get_term_meta(get_queried_object_id(), 'custom_image_data', true)) ); //**
}
}
add_action('admin_footer', 'image_uploader_js');
Or you can get all terms and push to an array and then you can access to js file.
function image_uploader_js() {
$category = get_terms( array(
'taxonomy' => 'category', // your custom taxonomy name
'hide_empty' => false
) );
$imageData = array();
if( !empty( $category ) ){
foreach ( $category as $key => $cat ) {
$imageData[$cat->term_id] = get_term_meta( $cat->term_id, 'custom_image_data', true );
}
}
wp_register_script( 'image_file_uploader_js', get_template_directory_uri() . '/js/image_uploader.js', array('jquery', 'media-upload') );
wp_enqueue_script( 'image_file_uploader_js');
wp_localize_script( 'image_file_uploader_js', 'customUploads', array( 'imageData' => $imageData ) ); //**
}
add_action('admin_footer', 'image_uploader_js');
I have a wordpress app locally setup in my computer. In the wordpress admin i have a Countries tab under the Posts. I'll attach an image for better understanding.
I want to write a function to get the country values for my front-end. For that i have written a function like this
public function get_destinations()
{
$bookings = get_posts(
array(
'taxonomy'=> 'country',
'numberposts' => -1,
)
);
return $bookings;
}
But for some reason this function returns all the posts in the database. I want to get only the country names.
i found the taxonomy from my local url which is
http://localhost/my_project/wp-admin/edit-tags.php?taxonomy=country
I'm very new to wordpress and dont have a clue on how to retrieve these data to my front end. What am i doing wrong here?
If you want to show the only category or taxonomy name instead of get_posts you have to use get_terms
check this code.
// Get the taxonomy's terms
$terms = get_terms(
array(
'taxonomy' => 'country',
'hide_empty' => false, // show category even if dont have any post.
)
);
// Check if any term exists
if ( ! empty( $terms ) && is_array( $terms ) ) {
// Run a loop and print them all
foreach ( $terms as $term ) { ?>
<a href="<?php echo esc_url( get_term_link( $term ) ) ?>">
<?php echo $term->name; ?>
</a><?php
}
}
I'm using wp_localize_script to send post data to ajax.
wp_localize_script( 'my-script.js', 'ajax_object', array('ajax_url' => admin_url('admin-ajax.php')) );
add_action( 'wp_ajax_load_more_posts', 'ajax_posts' );
Sending post data to ajax:
function ajax_posts(){
global $post;
$args = array('post_type'=>'post', 'posts_per_page'=> 2);
$posts_arr=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$posts_arr[] = $post;
endwhile;
wp_reset_postdata();
endif;
wp_send_json_success(array('post'=>$posts_arr));
}
In my ajax success function I'm using the following to append posts to the HTML:
success:function(response){
var post_data = response.data.post;
$.each(post_data, function(index, value) {
$("#content").append('' + value.post_title + '');
});
}
It adds 2 posts to the HTML. It works well but how can I also add the post url to the ajax_posts() php function and pass it to ajax and use?
This is the data I'm getting from ajax:
Is it possible to also add the post urls to the post arrays?
Note: I'm using ajax for loading more posts when clicking a button but simplified the code here. I cannot add php directly to the js. It must be sent from the ajax_posts() php function to ajax in my js.
You could simply do something like this:
function ajax_posts(){
global $post;
$args = array('post_type'=>'post', 'posts_per_page'=> 2);
$posts_arr=[];
$query = new WP_Query($args);
if($query->have_posts()):
while($query->have_posts()):$query->the_post();
$posts_arr[] = array(
'permalink' => get_permalink(),
'ID' => $post->ID,
'post_title' => $post->post_title,
'post_content' => $post->post_content,
'post_author' => $post->post_author,
'post_date' => $post->post_date
// Add more fields as needed here
);
endwhile;
wp_reset_postdata();
endif;
wp_send_json_success(array('post'=>$posts_arr));
}
This question already has answers here:
How to get JavaScript variable value in PHP
(10 answers)
Closed 5 years ago.
So I am helping my friend with his woocommerce WordPress site. He has some short javascript code that needs to be added to the thank you page for the site.
The javascript code takes three variables (totalCost, orderId and setProductId). I can not get to the HTML. So how do I add this code to the PHP and also, how do I access the variables from the PHP and write them into the javascript?
And where in the already existing code should I add it? Is it in the functions.php file for the theme?
I would be super thankful for help!
EDIT:
So would this work?
add_action( 'studentkortet_tracking', 'my_custom_tracking' );
function studentkortet_tracking($order_id){
?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo ($order->order_total - $order->order_shipping); ?>');
sale.setOrderID('<?php echo $order->id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
Here is some working code, answered here
<script>
var p1 = "success";
</script>
<?php
echo "<script>document.writeln(p1);</script>";
?>
Here's the correct way of accessing PHP variables within a script. It utilises the function wp_localize_script() so that PHP variables are accessible in a script file. First include this file in your functions.php file
function example_enqueue_scripts() {
if( is_checkout() ) {
$args = array( 'total_cost' => 443, 'order_id' => 4567, 'set_product_id' => 123 );
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js' );
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
}
add_action( 'wp_enqueue_scripts', 'example_enqueue_scripts' );
Then include this javascript in a file under your theme folder called checkout-script.js for example.
(function( $ ) {
'use strict';
$(function() {
var totalCost = checkout_script.total_cost;
var orderId = checkout_script.order_id;
var setProductId = checkout_script.set_product_id;
exampleFunction( totalCost, orderId, setProductId );
function exampleFunction( totalCost, orderId, setProductId ) {
//Do something in here
//alert(totalCost);
}
});
})( jQuery );
I don't know what setProductId is meant to be as a variable, but the hook you are looking for is woocommerce_thankyou. The $order_id is passed by default, which you can then use to grab the order object. Pretty much all the info related to the order can be accessed through the setter/getter methods on the order object.
/**
* Print Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id ); ?>
<script id="pap_x2s6df8d" src="http://URL_TO_PostAffiliatePro/scripts/trackjs.js" type="text/javascript">
</script>
<script type="text/javascript">
PostAffTracker.setAccountId(’xxxxxx’);
var sale = PostAffTracker.createSale();
sale.setTotalCost('<?php echo $order->get_total() - $order->get_shipping_
(); ?>');
sale.setOrderID('<?php echo $order_id; ?>');
sale.setCurrency('<?php echo $order->get_order_currency(); ?>');
PostAffTracker.register();
</script>
<?php
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
Editing to add an alternative for enqueuing the scripts as suggested by #Andrew-Schultz. Using the woocommerce_thankyou hook gets you easy access to the $order_id, which would otherwise need to be retrieved from the URL. You will still access the javascript variables as he's shown in his answer.
/**
* Enqueue Javascript on Thankyou page.
* #param int $order_id
*/
function so_47117329_thankyou( $order_id ){
$order = wc_get_order( $order_id );
$args = array(
'total_cost' => $order->get_total(),
'order_id' => $order_id,
'set_product_id' => 123
);
wp_register_script( 'checkout-script', get_stylesheet_directory_uri() . '/checkout-script.js', array(), false, true ); // Last parameter loads script in footer
wp_localize_script( 'checkout-script', 'checkout_script', $args );
wp_enqueue_script( 'checkout-script' );
}
add_action( 'woocommerce_thankyou', 'so_47117329_thankyou' );
I am using a javascript that's called 'Backstretch' to display an image on the back of my website that resizes when the viewport is getting bigger or smaller. Now I would like to combine it with the get_post_thumbnail function from WordPress so I can set a background image as featured image.
I tried the standard WP function but that doesn't work because it adds tags:
$.backstretch("<?php echo get_the_post_thumbnail( $post_id, $size, $attr ); ?>");
So I need to strip off those tags.. I'm getting close because i'm now getting an url (and image) but it's always the same one even though I set a different featured image on every page
<?php $url = wp_get_attachment_url( get_post_thumbnail_id($post_id, $size, $attr ) ); ?>
<script>$.backstretch("<?php echo $url; ?>");</script>
You get the answer to your question in this tutorial: http://sridharkatakam.com/set-featured-image-full-sized-background-posts-pages-wordpress/
Create a backstretch-set.js-file and include
jQuery(document).ready(function($) {
$("body").backstretch([BackStretchImg.src],{duration:3000,fade:750});
});
and then enqueue both js-files (backstretch.js and your backstretch-set.js) in your functions.php
//* Enqueue Backstretch script
add_action( 'wp_enqueue_scripts', 'enqueue_backstretch' );
function enqueue_backstretch() {
//* Load scripts only on single Posts, static Pages and other single pages and only if featured image is present
if ( is_singular() && has_post_thumbnail() )
wp_enqueue_script( 'backstretch', get_bloginfo( 'stylesheet_directory' ) . '/js/jquery.backstretch.min.js', array( 'jquery' ), '1.0.0' );
wp_enqueue_script( 'backstretch-set', get_bloginfo('stylesheet_directory').'/js/backstretch-set.js' , array( 'jquery', 'backstretch' ), '1.0.0' );
wp_localize_script( 'backstretch-set', 'BackStretchImg', array( 'src' => wp_get_attachment_url( get_post_thumbnail_id() ) ) );
Try using the global $post object like so:
<?php global $post; $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID, 'full' ) ); ?>
<script>$.backstretch("<?php echo $url; ?>");</script>