How to make an AJAX caller handler for your AJAX stuff inside a post / page

I usually create a file that handles all AJAX request, call it ajaxcall.php, place it on your theme folder

//Pull WordPress DB account
require_once( "../../../wp-config.php" );

require_once( "../../../wp-load.php" );

define('DEBUG_MODE',true); //show_errors(); } else { $wpdb->hide_errors(); }

//See functions.php for all the functions used in this file

$ac = $_REQUEST['ac'];
$ret = json_encode(array('status'=>'empty'));
switch ($ac) {

case 'pt': //Post a tip
$fbid = $_REQUEST['uid'];
$fbname = $_REQUEST['fn'];
$postdesc = $_REQUEST['pd'];
$postcat = $_REQUEST['pc'];
$ret = htmlspecialchars(json_encode( post_a_tip($fbid,$fbname,$postdesc,$postcat) ), ENT_NOQUOTES);
break;

case 'ru': //Register a user
$uid = $_REQUEST['uid'];
$fname = $_REQUEST['fn'];
$lname = $_REQUEST['ln'];
$email = $_REQUEST['em'];
$nric = $_REQUEST['ic'];
$contact = $_REQUEST['mo'];
$dob = $_REQUEST['db'];
$contestMonth = $_REQUEST['cm'];
$ret = htmlspecialchars(json_encode( register_user( $fname,$lname, $nric, $dob, $email, $contact, $contestMonth , $uid ) ), ENT_NOQUOTES);
break;

}
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT");
header("Cache-Control: no-cache, must-revalidate");
header("Pragma: no-cache");
header("Content-type: application/json");
echo $ret;

And then, here’s how you call it, inside your template


var _url = "/ajaxcall.php";
var _args = {
ac: 'ru',
uid: "",
fn : fname,
ln : lname,
db: dob,
em: email,
ic : nric,
mo : contact,
cm: contestMonth
}
$.getJSON(_url,_args,function(data) {

participationFeed();

var _html = '

Thank you for your registration!

';
$('div.contest_right_box').html(_html);

});

How create custom function for your custom tables

Here’s a couple of code that I use to pull data from a custom table, this one utilizes wordpress own DAL. ($wpdb)
You can just add these function on function.php, then use it anywhere.

 


/*
Post a user tip to specific category
*/
function post_a_tip($uid,$uname,$postdsc,$postcat) {
global $wpdb;

$sql =$wpdb->prepare("INSERT INTO tips(fbid,fbname,post_desc,post_cat,post_date) VALUES(%s , %s , %s , %d , %s)",
$uid,$uname,$postdsc,$postcat,date('Y-m-d H:i:s'));

$wpdb->query($sql);

}

 


function get_user_tips_by_category($catId) {
global $wpdb;

$sql = $wpdb->prepare( "SELECT * FROM tips WHERE post_cat = %s ORDER BY post_date DESC", $catId);

$rs = $wpdb->get_results( $sql , ARRAY_A );

if (count($rs)) {
return $rs;
} else {
return array();
}

}

How to Pull First and Second Images of a post


function pull_first_image_from_post() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [0];

// no image found display default image instead
if(empty($first_img)){
$first_img = "";//"/images/default.jpg";
}
return $first_img;
}


function pull_second_image_from_post() {
global $post, $posts;
$first_img = '';
ob_start();
ob_end_clean();
$output = preg_match_all('//i', $post->post_content, $matches);
$first_img = $matches [1] [1];

// no image found display default image instead
if(empty($first_img)){
$first_img = "";//"/images/default.jpg";
}
return $first_img;
}

How to pull posts of a specific category inside the loop

if ( in_category( array(‘throughthelens-video’) ) ) {

$catId = get_category_id(‘throughthelens-video’);

query_posts(‘cat=’.$catId);

if ( have_posts() ) : while ( have_posts() ) : the_post();

get_template_part(‘content’,'carousel_video’);

endwhile; endif;
wp_reset_query();

} //end if ?>

Here’s what inside the template part :

<?php the_title(); ?><br />
<?php
$postId = get_the_ID();
$vid = get_post_custom_values(‘videoid’, $postId); ?>

<a href=”<?php echo get_permalink($postId);?>”>

<img src=”http://img.youtube.com/vi/<?php echo $vid[0];?>/2.jpg” />

</a>

Here’s what’s inside the function.php

function get_category_id($slug) {

$category = get_category_by_slug($slug);
return $category->term_id;
}

Remove First Image of the post

Methods :

1. echo preg_replace("/\< *[img][^\>]*[.]*\>/i","",get_the_content(),1);

 

2.  put the following add_filter before the_content in any file you want to remove image

add_filter('the_content', 'remove_image_content');

the_content();

 

3. put filter on functions.php to remove first image from all the_content

function remove_image_content($content) {

return preg_replace("/\< *[img][^\>]*[.]*\>/i","",$content,1);
}

add_filter('the_content', 'remove_image_content');

 

 

How to use WPDB class for DB access

require_once ‘../../../wp-load.php’;

function insertDB($name,$contact,$email,$evtName) {
global $wpdb;
$wpdb->custom_table = “custom_table_name”;

//$wpdb->show_errors();

$ok = $wpdb->insert($wpdb->custom_table, array(
‘name’ => $name,
‘contact’ => $contact,
‘email’ => $email,
‘event_name’ => $evtName
));

if ($ok) {
echo json_encode(array( ‘ok’ => true , ‘status’ => ‘success in DB insert’ ));
}else {
//$wpdb->print_error();
echo json_encode(array( ‘ok’ => false , ‘status’ => ‘failed on DB insert’ ));
}

}

insertDB($name,$contact,$email,$evtName);

How to use WP phpmailer on separate php file.


/* Send Mail */

require_once '../../../wp-includes/class-phpmailer.php';

//Gmail settings
define('GUSER', 'sender@gmail.com'); // Gmail username
define('GPWD', 'xxxxx'); // Gmail password

//Host settings
define('SMTPUSER', 'xerxis@domain.com'); // sec. smtp username
define('SMTPPWD', '12314'); // sec. password
define('SMTPSERVER', 'mail.domain.com'); // sec. smtp server

function smtpmailer($to, $from, $from_name, $subject, $body, $is_gmail = true) {
global $error;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->SMTPAuth = true;
if ($is_gmail) {
$mail->SMTPSecure = 'ssl';
$mail->Host = 'smtp.gmail.com';
$mail->Port = 465;
$mail->Username = GUSER;
$mail->Password = GPWD;
} else {
$mail->Host = SMTPSERVER;
$mail->Username = SMTPUSER;
$mail->Password = SMTPPWD;
}
$mail->SetFrom($from, $from_name);
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress($to);
if(!$mail->Send()) {
$error = 'Mail error: '.$mail->ErrorInfo;
return false;
} else {
$error = 'Message sent!';
return true;
}
}

$msg = 'Hello World';
$subj = 'test mail message';
$to = 'kaixersoft@gmail.com';
$from = 'from@mail.com';
$name = 'test email';

//try using gmail
if (smtpmailer($to, $from, $name, $subj, $msg)) {
echo json_encode(array('status' => 'message send via Gmail'));
//try host settings
} else {
if (!smtpmailer($to, $from, $name, $subj, $msg, false)) {
if (!empty($error)) echo $error;
} else {
echo json_encode(array('status' => 'message send via Host Settings'));
}
}