Using the Javascript API for Advanced Custom Fields - wordpress

I'm creating a new field type with the Adavanced Custom Fields, which enables the user to choose an image from the Image Library and define a point (X,Y coordinates) in this image. After defining the coordinates, the user can place an overlay video in this point. But my question is, how do I Get and Set an X and Y value in the database with the javascript API?

Okay, so #ObmerKronen suggested that I posted some code to demostrate what I'm trying to do ... makes sense:)
I've added the image in the new ACF field php file (class-tas-v5.php)
$imgID = get_field('image_url');
$img = wp_get_attachment_image( $imgID, "full", "", array( "class" => "overlay-point-img" ) );
echo '<div class="overlay-point-img-container">' . $img . '</div>';
Then I'm defining the X and Y coordinates in the input.js file
function initialize_field($field) {
var overlay_point_container = $field.context;
var img = $(overlay_point_container).find(".overlay-point-img-container");
var circle = '<div class="overlay-point-circle"></div>';
img.prepend(circle);
$(img).on("mousemove", function(event) {
var relX = event.pageX - $(this).offset().left;
var relY = event.pageY - $(this).offset().top;
$(circle).css({ left: relX, top: relY });
});
// Tried these two functions, but none of the values are saved in the database
// acf.set("posX", "123");
// $field.val("posX");
}
I've tried to save it with dummy data like this
acf.set("posX", "123");
$field.val("posX");

Related

ACF PRO and Google Maps on WordPress

I'm just looking for some help for the best way to do this and if there's any recommendations on a better way. So I have a Google map on one of the web pages, I need to add multiple marks to show store locations. I am using ACF to store the data of the stores in a repeater and am using a custom post type to call the data from ACF.
Is there a better way to do this or any further recommendations?
Maybe this can help you in the right direction. I have a website on which I use a custom field where you can enter the desired address of a location ($address) to find lat/long for the given address.
$address = get_field( 'adress' );
// Convert adress to lat/long
$findaddress = urlencode($address);
$requesturl = "http://maps.googleapis.com/maps/api/geocode/xml?address=".$address."&sensor=true";
$xml = simplexml_load_file($requesturl) or die("not found");
$status = $xml->status;
if ($status=="OK") {
$latitude = $xml->result->geometry->location->lat;
$longitude = $xml->result->geometry->location->lng;
}
The given lat/long can than be used to add a location, marker, center etc:
// Location of the given address
var location = new google.maps.LatLng(<?php print $latitude ?>,<?php print $longitude; ?>);
// Map
var map = new google.maps.Map(document.getElementById('google-maps'), {
zoom: 18,
disableDefaultUI: true,
scrollwheel: false,
styles: styles,
center: location,
mapTypeId: google.maps.MapTypeId.ROADMAP,
});
// Marker
var marker = new google.maps.Marker({
map: map,
position: location,
});

fetch the field data without post

I'm trying to get the field data from form textarea so i can store it when a user filling the textarea if he reload page or open an other page in same tab and come back to write data his previous work will be there
My code is
session_start();
$_SESSION['textarea-133'] = $_POST["textarea-133"];
?>
<script>
var a="<php echo $_SESSION['textarea-133']";
document.getElementById("business_a6").value =a ;
</script>
You could use window.sessionStorage to save a variable and check if it's there each time the page is loaded.
window.onload = function(){
var userText = sessionStorage.getItem('the_user_text');
if( userText ){
document.getElementById('the-text-area').innerHTML = userText;
}
};
It's up to you if you want to re-save the variable with each keypress or maybe after a setInterval
document.addEventListener('keypress', (event) => {
var newText = document.getElementById('the-text-area');
sessionStorage.setItem('the_user_text', newText);
});

html2canvas, upload image to wordpress library

I'm making a holiday blessing generator for client.
The final output goes to a div with an id="BRHBresults".
From that div I'm making a canvas and converting it to image,
I've managed to make the onclick function to download the image(just to make sure the result was correct), however what I need the onclick to do is,
upload the image to wordpress library and make a new post with this image as post_thumbnail.
I get an error:
"414 (Request-URI Too Large)"
So far I have come up with this:
Link to the page: [http://www.benedict.co.il/%D7%9E%D7%97%D7%95%D7%9C%D7%9C-%D7%91%D7%A8%D7%9B%D7%95%D7%AA/
]
Javascript/JQuery
$(".BRHshareToFB1").click(function(){
html2canvas([document.getElementById('BRHBresults')], {
onrendered: function (canvas) {
var data = canvas.toDataURL('image/png');
var image = new Image();
image.src = data;
var alink = data ;
//$('.BRHshareToFB2').attr('href', alink);
//$('.BRHshareToFB2').attr('download', 'filename.jpg');
//dataUrl = canvas.toDataURL("image/png");
alink = data.replace(/^data:image\/(png|jpg);base64,/, "");
$.post("/send.php?data="+alink);
}
});
});
PHP from send.php file
<?php
$dir = getcwd();
$now = date("U");
$imgstring = $_POST['data'];
$imgstring = base64_decode($imgstring);
file_put_contents("$dir/wp-content/uploads/blessing-$now.png", $imgstring);
?>
What am I missing? Please help! :)

Stop loading posts when no more exist

I'm using the following to load posts into a index page of a wordpress site. The problem is when it gets to the last page and there are no more posts to load. Its just keeps reloading the last page.
Any ideas of how I might stop this from happening? Thanks.
var $content = '#content';
var $nav_wrap = '.navigation';
var $anchor = '.navigation a.next';
var $text = 'Load More';
var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts
$($nav_wrap).html('<a id="almc-load-more" href="' + $next_href + '">' + $text + '</a>');
$('#almc-load-more').click(function(e) {
e.preventDefault();
$.get($(this).attr('href'), '', function(data) {
var $timestamp = new Date().getTime();
var $new_content = $($content, data).wrapInner('<div class="almc-loaded" id="almc-' + $timestamp + '" />').html(); // Grab just the content
$next_href = $($anchor, data).attr('href'); // Get the new href
$('html,body').animate({scrollTop: $($nav_wrap).position().top}, 'slow'); // Animate scroll
$($nav_wrap).before($new_content); // Append the new content
$('#almc-' + $timestamp).hide().fadeIn('slow'); // Animate load
$('#almc-load-more').attr('href', $next_href); // Change the next URL
$('.almc-loaded ' + $nav_wrap).remove(); // Remove the original navigation
});
});
Above code taken from here: http://kaspars.net/blog/wordpress/jquery-script-for-loading-more-posts
You could add some code to check if the new href is different than the current href, and then only try to add a new post if they're different. Then, if they aren't, you could have a message saying there are no more posts.
var lastLink;
$('#almc-load-more').click(function(e) {
if ( $anchor == $('.navigation a.next').last() ) {
lastLink = 1;
}
if (lastLink == 1) {return} else {
...
}
...
After the comment from Mr. Mayers (Thanks) I gave up on the code and used this tutorial:
http://www.problogdesign.com/wordpress/load-next-wordpress-posts-with-ajax/
Has / does everything I needed.

Attaching media to post type without editor support

I'm trying to add attachments to a custom post type that hasn't editor support (only excerpt).
I've managed to show the Media Manager dialog box, but I can only see the "Insert into post" button (that does nothing anyway) and when uploading images, they don't get attached to the post.
To implement what I did so far, I've added a very simple meta box to the post type:
function add_gallery_post_media_meta_box()
{
add_meta_box(
'gallery_post_media',
'Gallery Media',
'gallery_post_media',
'gallery',
'side',
'high'
);
} // add_file_meta_box
add_action('add_meta_boxes', 'add_gallery_post_media_meta_box');
function gallery_post_media()
{
echo '' . __('Add media') .'';
} // end post_media
function register_admin_scripts() {
wp_enqueue_media();
wp_register_script( 'gallery_post_media_admin_script', get_template_directory_uri() . '/library/cpt/gallery.js' );
wp_enqueue_script( 'gallery_post_media_admin_script' );
} // end register_scripts
add_action( 'admin_enqueue_scripts', 'register_admin_scripts' );
And the script:
jQuery(document).ready(function ($) {
$('#gallery-add-media').click(function (e) {
var send_attachment_bkp = wp.media.editor.send.attachment;
var button = $(this);
var id = button.attr('id').replace('_button', '');
wp.media.editor.send.attachment = function (props, attachment) {
$("#" + id).val(attachment.url);
wp.media.editor.send.attachment = send_attachment_bkp;
}
wp.media.editor.open(button);
event.preventDefault();
return false;
});
});
If I would able to find some documentation about wp.media.editor.send.attachment, I'd probably manage to get what I want, but I can't find anything useful.
The only solutions I've found all relies on custom fields, instead I want to simply attach these images to the post, without inserting them in the post content, as I would do with normal posts.
As a side question: is it possible to tell the Media Manager to only accept images?
This is the JavaScript I use for media fields. Once you hit insert you can do whatever you want with the data from the image's selected
jQuery(document).ready(function() {
//uploading files variable
var custom_file_frame;
jQuery(document).on('click', '.meida-manager', function(event) {
event.preventDefault();
$this = jQuery(this);
//If the frame already exists, reopen it
if (typeof(custom_file_frame)!=="undefined") {
custom_file_frame.close();
}
//Create WP media frame.
custom_file_frame = wp.media.frames.customHeader = wp.media({
//Title of media manager frame
title: "Sample title of WP Media Uploader Frame",
library: {
type: 'image'
},
button: {
//Button text
text: "insert text"
},
//Do not allow multiple files, if you want multiple, set true
multiple: false
});
//callback for selected image
custom_file_frame.on('select', function() {
var attachment = custom_file_frame.state().get('selection').first().toJSON();
//do something with attachment variable, for example attachment.filename
//Object:
//attachment.alt - image alt
//attachment.author - author id
//attachment.caption
//attachment.dateFormatted - date of image uploaded
//attachment.description
//attachment.editLink - edit link of media
//attachment.filename
//attachment.height
//attachment.icon - don't know WTF?))
//attachment.id - id of attachment
//attachment.link - public link of attachment, for example ""http://site.com/?attachment_id=115""
//attachment.menuOrder
//attachment.mime - mime type, for example image/jpeg"
//attachment.name - name of attachment file, for example "my-image"
//attachment.status - usual is "inherit"
//attachment.subtype - "jpeg" if is "jpg"
//attachment.title
//attachment.type - "image"
//attachment.uploadedTo
//attachment.url - http url of image, for example "http://site.com/wp-content/uploads/2012/12/my-image.jpg"
//attachment.width
$this.val(attachment.url);
$this.siblings('img').attr('src',attachment.url);
});
//Open modal
custom_file_frame.open();
});
});

Resources