I'm trying to display the username when an AJAX request is successful.
The problem that I'm running into is that the name remains blank.
Simplified code (removed if statements, checks, and other unrelated code)
wp_localize_script('follow-me-ajax', 'ajax_setting', array(
'ajax_url' => admin_url('admin-ajax.php'),
'ajax_nonce' => wp_create_nonce('km-ajax-create-nonce'),
'ajax_follow_success' => $this->follow_me_success(),
));
AJAX Call
var user_to_follow = $('.km-author-follow a.km-meta-badge').attr('id');
$.ajax( {
url : ajax_setting.ajax_url,
type : 'post',
data: {
action : 'theme_ajax_follow_me',
security : ajax_setting.ajax_nonce,
'data-follow-user' : user_to_follow,
},
success: function( data ) {
$('.km-follow-me').html( ajax_setting.ajax_follow_success ).hide().fadeIn( 'slow' );
console.log( user_to_follow );
},
} )
Inside the wp ajax function I use this
public function theme_addon_ajax_follow_me() {
...
$target_user = isset( $_POST['data-follow-user'] ) ? $_POST['data-follow-user'] : false;
if( ! empty( $_POST['data-follow-user'] ) ) {
$this->kiwi_follow_user( $current_user, $target_user );
}
wp_die();
}
Up next; this function sends the $target_user ID to km_follow_me_author_name
public function kiwi_follow_user( $current_user = 0, $user_to_follow = 0 ) {
...
$args = array(
'user_id' => $current_user,
'follow_to' => $user_to_follow
);
$response_success = $this->km_follow_me_author_name( $args );
}
Function to grab display name based on AJAX's $_POST['data-follow-user']
public function km_follow_me_author_name( $args = array() ) {
$author_info = get_userdata( $args['follow_to'] );
$author = $author_info->display_name;
return $author;
}
The success message and where it goes wrong. $name remains blank.
public function follow_me_success() {
$name = $this->km_follow_me_author_name();
$content = sprintf( esc_html__( 'You\'re now following %s.', 'theme' ), $name );
return $content;
}
Any help is much appreciated.
First I removed this line from wp_localize_script
'ajax_follow_success' => $this->follow_me_success(),
Then changed the success function from AJAX to:
$('.km-follow-me').html(data).hide().fadeIn( 'slow' );
Then inside public function kiwi_follow_user I used:
if ( ! empty( $response ) && $response !== FALSE ) {
$this->km_follow_me_success( $user_to_follow );
}
And inside the follow_me_success function, I replaced return with echo instead.
public function follow_me_success( $target_user = 0 ) {
$name = $this->km_follow_me_author_name( $target_user );
$content = sprintf( esc_html__( 'You\'re now following %s.', 'theme' ), $name );
echo $content;
}
Minor changes, big difference. :)
Related
i'm using WP User Frontend Pro plugin
i want to echo the pack title using a shortcode to put it in bakery visual.
all what i know is : this is the title $pack->post_title;
$pack is coming from here :
public function current_pack() {
global $pack;
$pack = $this->pack;
if ( ! isset( $this->pack['pack_id'] ) ) {
$pack_page = get_permalink( wpuf_get_option( 'subscription_page', 'wpuf_payment' ) );
return new WP_Error( 'no-pack', sprintf( __( 'You must purchase a subscription package before posting', 'wp-user-frontend'), $pack_page ) );
}
// seems like the user has a pack, now check expiration
if ( $this->expired() ) {
return new WP_Error( 'expired', __( 'The subscription pack has expired. Please buy a pack.', 'wp-user-frontend' ) );
}
return $pack;
}
i try to do something like this :
function wpc_shortcode_pack_title() {
global $pack;
return $pack->post_title;
}
add_shortcode( 'sub_name', 'wpc_shortcode_pack_title' );
to explain more
the slected code in line 5 is working correctly in the plugin pages
but i want it as a shortcode
but it didn't work
any help please ?
The callback function of add_shortcode() should return the content, not print it.
Meaning, you have to return $pack->post_title instead of echo $pack->post_title.
Like so:
function wpc_shortcode_pack_title() {
global $pack;
return $pack->post_title;
}
add_shortcode( 'sub_name', 'wpc_shortcode_pack_title' );
Edit: After taking a look at the source of “WP User Frontend Pro”:
$pack seems to be getting its value from WPUF_Subscription::get_subscription() passing the subscription id, which basically gets the post with that id.
The subscription id seems to be getting its value from WPUF_Subscription::get_user_pack() passing the user id.
So, I guess you could call get_current_user_id() and try something like this:
function wpc_shortcode_pack_title() {
$user_id = get_current_user_id();
if ( ! class_exists( 'WPUF_Subscription' ) ) {
return 'WP User Frontend Pro is not installed/activated';
}
$user_sub = WPUF_Subscription::get_user_pack( $user_id );
$pack = WPUF_Subscription::get_subscription( $user_sub['pack_id'] );
return $pack->post_title;
}
add_shortcode( 'sub_name', 'wpc_shortcode_pack_title' );
Edit #2: To get the expire date as well, you would do something similar:
function wpc_shortcode_pack_title() {
$user_id = get_current_user_id();
if ( ! class_exists( 'WPUF_Subscription' ) ) {
return 'WP User Frontend Pro is not installed/activated';
}
// Get WPUF subscription/pack
$user_sub = WPUF_Subscription::get_user_pack( $user_id );
$pack = WPUF_Subscription::get_subscription( $user_sub['pack_id'] );
// Get expiration date
$expire = ( $user_sub['expire'] == 'unlimited' ) ? ucfirst( 'unlimited' ) : wpuf_date2mysql( $user_sub['expire'] );
return sprintf(
'Subscription name: %1$s | Expire date: %2$s',
$pack->post_title,
wpuf_get_date( $expire )
);
}
add_shortcode( 'sub_name', 'wpc_shortcode_pack_title' );
hello im doing save for later feature in my website
but i get admin-ajax bad request when i click the button
functions.php
function zumra_scripts() {
wp_register_script( 'remove-prodduct-from-list', get_template_directory_uri() . '/js/remove-product.js', array('jquery'), false, true );
wp_localize_script( 'remove-prodduct-from-list', 'sfl_ajax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )) );
if ( is_page('savelist') ) {
wp_enqueue_script( 'remove-prodduct-from-list' );
}
}
add_action( 'wp_enqueue_scripts', 'zumra_scripts' );
save-for-later.php
<?php
add_action( 'wp_ajax_my_action', 'my_action' );
function my_action() {
$user = $_POST['user'];
$post_id = $_POST['post_id'];
$response = $_POST['saveForLater'];
$response .= ''. __( 'Browse Savelist', 'zumra' ) .'';
add_user_meta( $user, 'product_id', $post_id);
echo $response;
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_remove_product_from_list', 'remove_product_from_list' );
function remove_product_from_list() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_move_to_cart', 'move_to_cart' );
function move_to_cart() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
// do_action( 'woocommerce_ajax_added_to_cart', $product );
// wc_add_to_cart_message( $product );
wp_die(); // this is required to terminate immediately and return a proper response
}
save-for-later.js
jQuery(document).ready(function($) {
$('.ajax-form').on('submit',function(e){
e.preventDefault();
var data = {
'action': 'my_action',
'saveForLater': sfl_ajax.response,
'user': sfl_ajax.user,
'post_id': sfl_ajax.post_id,
'product_id': sfl_ajax.user_product,
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(sfl_ajax.ajaxurl, data, function(response) {
$('.save-for-later').html(response);
});
});
});
i don't know what im doing wrong
i get error admin-ajax.php 400 every time i click add to save for later button
Try with below code. I am assuming that you have include this file in the functions.php of your active theme.
Or
You can add this code in your functionctions.php directly.
As is described in the Wordpress AJAX documentation, you have two different hooks - wp_ajax_(action), and wp_ajax_nopriv_(action). The difference between these is:
wp_ajax_(action): This is fired if the ajax call is made from inside
the admin panel.
wp_ajax_nopriv_(action): This is fired if the ajax
call is made from the front end of the website.
add_action( 'wp_ajax_my_action', 'my_action' );
add_action("wp_ajax_nopriv_my_action","remove_product_from_list");
function my_action() {
$user = $_POST['user'];
$post_id = $_POST['post_id'];
$response = $_POST['saveForLater'];
$response .= ''. __( 'Browse Savelist', 'zumra' ) .'';
add_user_meta( $user, 'product_id', $post_id);
echo $response;
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_remove_product_from_list', 'remove_product_from_list' );
add_action("wp_ajax_nopriv_remove_product_from_list","remove_product_from_list");
function remove_product_from_list() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
wp_die(); // this is required to terminate immediately and return a proper response
}
add_action( 'wp_ajax_move_to_cart', 'move_to_cart' );
add_action("wp_ajax_nopriv_move_to_cart","GetEditForm");
function move_to_cart() {
$user = intval( $_POST['user'] );
$product = intval( $_POST['product'] );
delete_user_meta( $user, 'product_id', $product);
// do_action( 'woocommerce_ajax_added_to_cart', $product );
// wc_add_to_cart_message( $product );
wp_die(); // this is required to terminate immediately and return a proper response
}
I have a function to set up metaboxes. This creates them when a class is instantiated with a custom name.
Now the init() execute two add_action functions. One to add the metabox and one to save the metabox.
Creating the metabox works fine. However saving doesn't
It only saves the last created metabox to the database.
class metaBox {
final public function init() {
add_action( 'add_meta_boxes', [ $this, 'add' ] );
add_action( 'save_post', [ $this, 'save' ] );
}
public $CMB_Name;// for custom name
public function setName( $CMB_Name ) {
$this->CMB_Name = $CMB_Name;
}
public function add() { // to add the metabox
add_meta_box(
$this->CMB_Name,
__( $this->CMB_Name, 'plugin' ),
[ $this, 'display' ],
'page',
'normal',
'high'
);
}
public function save( $post_id ) {// to save the metabox
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST['nonce_check_value'] ) && wp_verify_nonce( $_POST['nonce_check_value'], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || ! $is_valid_nonce ) {
return;
}
if ( isset( $_POST[ $this->CMB_Name . '-text' ] ) ) {
update_post_meta( $post_id, $this->CMB_Name . '-text', sanitize_text_field( $_POST[ $this->CMB_Name . '-text' ] ) );
}
}
}
What I don't understand is that it doesn't save both values while there are unique nonces and names to the metaboxes .
The objects are created like this:
function mbe_start() {
$plugin = new testForm();
$plugin->setName( "OOP Plugin name" );
$plugin->init();
$plugin1 = new anotherForm();
$plugin1->setName( "whaat" );
$plugin1->init();
}
mbe_start();
Why doesn't the save function work? I mean it's principle is exactly like the one that adds the metabox.
If I disable the isset() function it throws me a notice about an Undefined index for the first metabox. Not really sure why and/or how to fill it.
OMG.....
Got it working. The reason is that the name given contains spaces and capital letters. This caused the problem.
Fixed it by replacing the name with
strtolower(preg_replace('/-+/', '-', preg_replace('/[^\wáéíóú]/', '-', $this->CMB_Name)));
I am trying to load a new page template when a query var is appended at the end of my page url:
Original url: example.com/testpage/
with variable added to the end: example.com/testpage/amp
Then it would load up a custom php template.
This seems like a straight forward operation, but I cannot get it to work.
The url loads with the /amp variable at the end, but the template does not load. If I remove the condition "get_query_var('amp')" then it loads up the template no problem. What am I missing? Thanks :)
Here is my working code:
add_filter( 'query_vars', 'register_query_var' );
function register_query_var( $vars ) {
$vars[] = 'amp';
return $vars;
}
add_rewrite_endpoint( 'amp', EP_PAGES );
add_filter( 'template_include', 'use_amp_template', 99 );
function use_amp_template( $template ) {
global $wp_query;
if ( get_query_var( 'amp' ) && is_page() ) {
$new_template = locate_template( array( 'amptemplate.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
return $template;
}
Found a good fix on my own. Here is the code if it would help anyone.
Adding 'amp' after a page or post will load up different templates for amp versions of the page.
example.com/samplepage/amp
or
example.com/samplepost/amp
add_filter( 'query_vars', 'register_query_var' );
function register_query_var( $vars ) {
$vars[] = 'amp';
return $vars;
}
add_rewrite_endpoint( 'amp', EP_PAGES | EP_PERMALINK );
add_filter( 'template_include', 'use_amp_template', 99 );
function use_amp_template( $template ) {
global $wp_query;
if(isset( $wp_query->query['amp'] ) && is_page()){
$new_template = locate_template( array( 'amppagetemplate.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
if(isset( $wp_query->query['amp'] ) && is_single()){
$new_template = locate_template( array( 'ampposttemplate.php' ) );
if ( '' != $new_template ) {
return $new_template;
}
}
return $template;
}
I have to create an option page using array in my wordpress theme. after submitting all fill up information removed while i am using
var_dump( $this->options) show blank array(){}
I want when submitting option page form submit information show in the input box and i will get_option value in some variable so that i have to display the information in my theme.
<?php
class MySettingsPage
{
private $options;
public function __construct()
{
add_action( 'admin_menu', array( $this, 'bguru_register_options_page' ) );
add_action( 'admin_init', array( $this, 'bguru_register_settings' ) );
}
public function bguru_register_options_page()
{
// This page will be under "Settings"
add_theme_page('Business Guru Options',
'Theme Customizer',
'edit_theme_options',
'bguru-options',
array( $this, 'bguru_options_page')
);
}
public function bguru_options_page()
{
// Set class property
$bguru_logo = is_array( get_option( 'bguru_logo' ) ) ? get_option( 'bguru_logo' ) : array();
$bguru_vimeo = is_array( get_option( 'bguru_vimeo' ) ) ? get_option( 'bguru_vimeo' ) : array();
$this->options = array_merge( $bguru_logo, $bguru_vimeo);
var_dump($this->options);
?>
<div class="wrap">
<?php screen_icon(); ?>
<h1>Business Guru Options</h1>
<form method="post" action="options.php">
<?php
// This prints out all hidden setting fields
settings_fields( 'defaultbg' );
do_settings_sections( 'defaultbg' );
submit_button();
?>
</form>
</div>
<?php
}
public function bguru_register_settings()
{
register_setting('defaultbg','bguru_logo', array( $this, 'sanitize' ) );
register_setting('defaultbg', 'bguru_vimeo', array( $this, 'sanitize' ));
add_settings_section(
'setting_section_id', // ID
'General',
array( $this, 'print_section_info' ), // Callback
'defaultbg' // Page
);
add_settings_field(
'bguru_logo', // ID
'Logo', // Title
array($this,'logo_callback' ), // Callback
'defaultbg', // Page
'setting_section_id' // Section
);
add_settings_field(
'bguru_vimeo', // ID
'Vimeo', // Vimeo
array( $this, 'socialv_callback' ), // Callback
'defaultbg', // Page
'setting_section_id' // Section
);
}
public function sanitize( $input )
{
$new_input = array();
if( isset( $input['bguru_logo'] ) )
$new_input['bguru_logo'] = sanitize_text_field( $input['bguru_logo'] );
if( isset( $input['bguru_vimeo'] ) )
$new_input['bguru_vimeo'] = sanitize_text_field( $input['bguru_vimeo'] );
return $new_input;
}
public function print_section_info()
{
print 'Enter your settings below:';
}
public function logo_callback()
{
printf('<input type="text" id="bguru_logo" size="50" name="bguru_logo" value="%s" />',
isset( $this->options['bguru_logo'] ) ? esc_attr( $this->options['bguru_logo']) : ''
);
}
public function socialv_callback()
{
printf('<input type="text" id="bguru_vimeo" size="50" name="bguru_vimeo" value="%s" />',
isset( $this->options['bguru_vimeo'] ) ? esc_attr( $this->options['bguru_vimeo']) : ''
);
}
}
if( is_admin() )
$my_settings_page = new MySettingsPage();