Wordpress: Load custom field in ajax - wordpress

On wordpress I want to make a post template where if a user clicks on a link it will load the custom field value via ajax. I found a plugin here How to load the custom field values of the post via ajax in wordpress but the download link seems to be dead so I'm unable to download :( can anyone help me code? I'm not a programmer so tell me the easiest solution

In functions.php file
<?php
add_action('wp_ajax_load_custom_field_data','load_custom_field_data');
add_action('wp_ajax_nopriv_load_custom_field_data','load_custom_field_data');
function load_custom_fields_data(){
$postid=$_POST['postid'];
$metakey= $_POST['metakey'];
echo get_post_meta($postid,$metakey,true);
die();
?>
In your template where you will have your link like below(remember to have postid and metakey attributes in the links with class get_meta_val)
<a class="get_meta_val" postid="<?php echo $post->ID?>" metakey ="your_meta_key">Get Custom Value</a>
//get postid in any way you want and put you customfield name in your_meta_key
<script type="text/javascript">
jQuery(document).ready(function(e) {
jQuery(document).one('click','.get_meta_val',function(e){
e.preventDefault();
var pid = jQuery(this).attr('postid');
var metakey = jQuery(this).attr('metakey');
var data = {
'action': 'load_custom_field_data',
'postid': pid,
'metakey':metakey
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
alert('Custom Field Value is: ' + response);
//Here you can do whatever you want with your returned value
});
});
});
</script>

Related

Detect users input values from any wordpress form

I'm trying to develop a wordpress plugin, I need to get users input data from any form in a specific page (not knowing its action) I come up so far with this solution which is to get values using javascript and then passing it to php:
jQuery(function ($) {
$(document).ready(function(){
$( "form" ).submit(function( event ) {
if($( "form" ).valid()){
var inputs = $( "form input" );
var inputValues = [];
inputs.each(function(index){
if($(this).attr('type') !== 'submit')
inputValues.push($(this).val());
});
}
event.preventDefault();
});
});
});
I tried to pass the Javascript variable inputValues to my plugin using Ajax
$.ajax({
type: 'POST',
url: '../wp-content/plugins/myplugin/myplugin.php',
data: {'variable': inputValues},
});
But I get problems with the url for some pages and I couldn't use $_POST['variable'] in myplugin.php file.
Is there a way to accomplish what I'm trying to do, or do you know an alternative solution?
Thanks in advance.
in terms of how to implement AJAX calls using WordPress, please check out the WordPress Codex. You're not doing it correctly.
JavaScript seems like a round about way of doing this. I would suggest to hook into one of hooks that are being called almost every single time like template_redirect (https://codex.wordpress.org/Plugin_API/Action_Reference/template_redirect).
Then you can check what's in the $_POST variable and do what you need to do with it. This would even Capture AJAX forms as long as the URL links to a proper AJAX WordPress endpoint.
Hope this helps

Make changes to the Edit Account Details page

Currently the Edit Account Details page have these fields: First Name, Last Name, Email address, Current Password & New Password. Now I need to overwrite the 'Save Changes' button which basically submits the form to update the user details. Before the form is being submitted, I want to do a javascript-based validation which checks the user's new password. How can I do this?
Btw I'm using WooCommerce, if that matters here.
You can use woocommerce_edit_account_form_end action to inject your custom JS snippet and do your validation.
like this
function add_my_account_edit_script() { ?>
<script type="text/javascript">
(function($){
$(document).ready(function(){
$("form.edit-account").submit(function(){
var old_pass = $("#password_1").val();
var new_pass = $("#password_2").val();
if( old_pass != new_pass ) {
// Show your validation message here
// return false to prevent the form submitting
return false;
}
// no validation error so allow the form to be submitted.
return false;
});
});
})(jQuery);
</script>
<?php
}
add_action( 'woocommerce_edit_account_form_end', 'add_my_account_edit_script' );

Disqus count not refreshing immediately

I registered to Disqus 2 days ago, and I put the script on my website (not a CMS). Basically, it's working, comments are displayed and it's pretty easy.
BUT, the count system is totally screwed up. I get an unique identifier for each post (slug-id):
var disqus_config = function () {
//this.page.url = '/<?= $datas['slug'].'-'.$datas['id']; ?>/'; // Replace PAGE_URL with your page's canonical URL variable
this.page.identifier = '<?= $datas['slug'].'-'.$datas['id']; ?>'; // Replace PAGE_IDENTIFIER with your page's unique identifier variable
};
(function() { // DON'T EDIT BELOW THIS LINE
var d = document, s = d.createElement('script');
s.src = '//my-shortname.disqus.com/embed.js'; // It's the real one, i juste modified it for the post
s.setAttribute('data-timestamp', +new Date());
(d.head || d.body).appendChild(s);
})();
The count.js script is right before the </body> tag
And the code for the count is :
<a href="/<?= $datas['slug'].'-'.$datas['id']; ?>/#disqus_thread"
data-disqus-identifier="<?= $datas['slug'].'-'.$datas['id']; ?>">
</a>
It's working yes, but I need few minutes/hours before refresh. Look at the screenshot, I posted a comment, and the count hasn't been refreshed even if I clear my cache etc. I have to wait some minutes/hours and it'll be refreshed automatically.
Screenshot from my website
Why? How to fix it?

firebase read .on('value') not working

This script is not working for me.
I know the problem is in the .on('value') function but I don't know what it is.
This is my script:
$(document).ready(function(){
//dynamic content switching inside the content section
function writeContent(page){
//setting post to default error message
var post = "Sorry, This page is undergoing maintenance.";
//firebase data reference for the clicked link's content
var dataRef = new Firebase("https://cityartist.firebaseio.com/"+page);
//inserting the available content to the 'post' variable
dataRef.on("value",function(snapshot){
if(snapshot.val() != null){
post = snapshot.val();
alert("post="+post);
}
});
//showing content in the content section and changing the page's title
$("#content").append("<article class='post'><p>"+post+"</p></article>");
$("title").text("CityArtist.org - "+page);
}
//switching pages using the navigation bar
$(".menu_link").click(function(){
writeContent($(this).attr("name"));
});
});
Callbacks in Firebase are often fired asynchronously, since Firebase has to wait for the data to arrive. So your on('value') callback code is being called /after/ the "//showing content in ..." code. You could try this instead:
dataRef.on("value",function(snapshot){
if(snapshot.val() != null){
post = snapshot.val();
alert("post="+post);
}
//showing content in the content section.
$("#content").append("<article class='post'><p>"+post+"</p></article>");
});
You need to perform the DOM changes inside the callback (e.g. after Firebase has returned data). Here it is in context:
$(document).ready(function(){
//dynamic content switching inside the content section
function writeContent(page){
//setting post to default error message
var post = "Sorry, This page is undergoing maintenance.";
//firebase data reference for the clicked link's content
var dataRef = new Firebase("https://cityartist.firebaseio.com/"+page);
//inserting the available content to the 'post' variable
dataRef.on("value",function(snapshot){
if(snapshot.val() != null){
post = snapshot.val();
alert("post="+post);
//showing content in the content section and changing the page's title
$("#content").append("<article class='post'><p>"+post+"</p></article>");
$("title").text("CityArtist.org - "+page);
}
});
}
//switching pages using the navigation bar
$(".menu_link").click(function(){
writeContent($(this).attr("name"));
});
});

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