I am trying to insert post id on publish to custom table but it is not adding correct id but 0
here is my function
//get post id on publish
function get_publishing_id($post_id) {
$post= get_post($post_id);
if ($post->post_type == 'post'
&& $post->post_status == 'publish') {
// insert data on publish
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'banner_views',
array(
'postid' => $post,
'view_count' => 12,
)
);
} // end if
} // end function
add_action('save_post','get_publishing_id');
Please help to solve this. Thanks a lot...
It's solved.
The mistake was not passing ID with $post like $post->ID
//get post id on publish
function get_publishing_id($post_id) {
$post= get_post($post_id);
if ($post->post_type == 'post'
&& $post->post_status == 'publish') {
// insert data on publish
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'banner_views',
array(
'postid' => $post->ID,// here was the mistake
'view_count' => 12,
)
);
} // end if
} // end function
add_action('save_post','get_publishing_id');
So above code works for me.
Thanks a lot
Related
Can we set conditions in xml response. Like there is status fields in database that is in numeric like 0,1,2,3 and we want to show it like below
0 for => Complete
2 for => Cancelled
2 for => Return
5 for => Refund.
How can we add a new fields in xml response if the fields does not exist in database ?
Lets suppose you are fetching the sales report from Sales table in Cakephp 3.0 Using rest API.
If you want to customize, rename, add few fields in response of Rest API You can do it like below
REST API URL will be something like below
https://example.com/api/index.json?fromdate_utc=2016-10-03&todate_utc=2016-10-03
And functino in controller be something like below:-
public function index($fromdate = null, $todate = null)
{
//set date range for
if(!empty($_GET['fromdate_utc']) && !empty($_GET['todate_utc'])){
// if from amd to date are same add +1 day in to date to get result
$to_date = date('Y-m-d', strtotime($_GET['todate_utc'] . ' +1 day'));
$dateRage = array('Sales.SalesDate >= ' => $_GET['fromdate_utc'], 'Sales.SalesDate <=' => $to_date);
}else{
$dateRage = array();
}
$conditions = array(
'and' => array($dateRage),
);
//$this->Auth->allow();
$sales = $this->Sales->find('all', array(
'conditions' => $conditions
))
->select(['SalesNo', 'SalesDate', 'TotalValue', 'TotalDiscount', 'NetTotal', 'PaymentMode', 'Status'])
->where(['StoreId' => '8','Status !=' => '2','Status !=' => '4'])->andWhere(['Status !=' => 1])->andWhere(['Status !=' => 4]);
//->limit(3);
$salesResponse = array();
//echo '<br/>Count no of output => '.$sales->count();
if($sales->count() >0 ){
foreach($sales as $key=>$salesData){
//re generate the array as per your requirements
$salesResponse[$key]['SalesNo'] = $salesData->SalesNo;
$salesResponse[$key]['SalesDate'] = $salesData->SalesDate;
$salesResponse[$key]['TotalValue'] = $salesData->TotalValue;
$salesResponse[$key]['TotalDiscount'] = $salesData->TotalDiscount;
$salesResponse[$key]['NetTotal'] = $salesData->NetTotal;
$salesResponse[$key]['SaleTax'] = 0; // add new fields that does not exist in database
$salesResponse[$key]['PaymentMode'] = $salesData->PaymentMode;
// change the status from numeric to character and pass it to response
if($salesData->Status == 5){
$salesResponse[$key]['Status'] = 'Refund';
}elseif($salesData->Status == 3){
$salesResponse[$key]['Status'] = 'Return';
}elseif($salesData->Status == 2){
$salesResponse[$key]['Status'] = 'Cancelled';
}elseif($salesData->Status == 0){
$salesResponse[$key]['Status'] = 'Complete';
}
}
}else{
$salesResponse = array('Error ! sorry not found any record.');
}
$this->set([
'sales' => $salesResponse,
'_serialize' => ['sales']
]);
}
If you're okay with having a slightly different name for the status in the XML, you could create a virtual field called, for example, status_text. Add a protected function _getStatusText in your Sale entity class which returns the desired text based on the status integer, and also add protected $_virtual = ['status_text']; to the Sale class, and you should start getting the status text in your XML.
I created a new table(new_table) in the Database.
I need, when I am adding a new post, id this post will save to my table(new_table.p_id).
How can do it?
Use the wpdb class's insert method.
First parameter is the table you want to insert data into. The second is an array containing the data in key value pairs.
Hook this into save_post.
function wpse_add_new_post_id_to_table( $post_id ) {
global $wpdb;
$post_status = get_post_status( $post_id );
if ( 'publish' != $post_status )
return false;
$wpdb->insert( 'new_table', array( 'p_id' => $post_id ) );
}
add_action( 'wp_insert_post', 'wpse_add_new_post_id_to_table' );
Further reading:
http://codex.wordpress.org/Plugin_API/Action_Reference/wp_insert_post
http://codex.wordpress.org/Class_Reference/wpdb
You use something like this action
function insert_id_to_db() {
global $post;
$postid = $post->id;
$wpdb->query("INSERT INTO table(id) VALUES('{$postid }')");
}
add_action('save_post', 'insert_id_to_db');
This function adds custom post 'event' data into a Salesforce db. I've tested the function outside of Wordpress and it works flawlessly. When I test it inside Wordpress by adding a new event, no error is generated and a the data is not inserted into the SF db. I've also tested this by printing out the $_POST and saw that the data is being collected. How can I get this display some errors so that I can trouble shoot this?
function add_campaign_to_SF( $post_id) {
global $SF_USERNAME;
global $SF_PASSWORD;
if ('event' == $_POST['post-type']) {
try {
$mySforceConnection = new SforceEnterpriseClient();
$mySoapClient = $mySforceConnection->createConnection(CD_PLUGIN_PATH . 'Toolkit/soapclient/enterprise.wsdl.xml');
$mySFlogin = $mySforceConnection->login($SF_USERNAME, $SF_PASSWORD);
$sObject = new stdclass();
$sObject->Name = get_the_title( $post_id );
$sObject->StartDate = date("Y-m-d", strtotime($_POST["events_startdate"]));
$sObject->EndDate = date("Y-m-d", strtotime($_POST["events_enddate"]));
$sObject->IsActive = '1';
$createResponse = $mySforceConnection->create(array($sObject), 'Campaign');
$ids = array();
foreach ($createResponse as $createResult) {
error_log($createResult);
array_push($ids, $createResult->id);
}
} catch (Exception $e) {
error_log($mySforceConnection->getLastRequest());
error_log($e->faultstring);
die;
}
}
}
add_action( 'save_post', 'add_campaign_to_SF');
I would use get_post_type() to check for "event" posts. Use error_log() to write to the PHP error log for additional debugging - check the status of your Salesforce login, etc.
Keep in mind that save_post will run every time a post is saved - created or updated - so you might want to do some additional checking (like setting a meta value) before creating a new Campaign in Salesforce, otherwise you will end up with duplicates.
function add_campaign_to_SF( $post_id ) {
$debug = true;
if ($debug) error_log("Running save_post function add_campaign_to_SF( $post_id )");
if ( 'event' == get_post_type( $post_id ) ){
if ($debug) error_log("The post type is 'event'");
if ( false === get_post_meta( $post_id, 'sfdc_id', true ) ){
if ($debug) error_log("There is no meta value for 'sfdc_id'");
// add to Salesforce, get back the ID of the new Campaign object
if ($debug) error_log("The new object ID is $sfdc_id");
update_post_meta( $post_id, 'sfdc_id', $sfdc_id );
}
}
}
add_action( 'save_post', 'add_campaign_to_SF' );
My question is how can I refresh my view "search.ctp" to take into account the record I just deleted. The problem is the following.
My controller code
public function search() {
if ($this->request->is('post')) {
$this->set("isPost", TRUE);
$query = $this->data;
$output = $this->Question->find("all", array("conditions"=>array("Question.lectureId"=>$query["Lecture"]["Lecture"],
"Question.type"=>$query["Lecture"]["status"])));
$this->set("questions", $output);
} else {
$this->LoadModel("Lecture");
$outputL = array();
$for = $this->Lecture->find("all", array("fields" => array("_id", "title")));
foreach ($for as $key => $value) {
$outputL[$value["Lecture"]["_id"]] = $value["Lecture"]["title"];
}
$this->set("lectures",$outputL);
//
$statuses = array(
"" => "Select a question type",
"anonymousQuestion" => "anonymousQuestion",
"handUp" => "handUp",
"userQuestion" => "userQuestion"
);
$this->set("statuses", $statuses);
}
}
So the following happens;
I open the view "search.ctp" ("my admin interface"), set the 2 search params,
and use the submit button to post that data. Then my IF statement recognizes that as POSt and gives me back my query results. The problem is when i delete a record...
It redirects me back to my search action to enter the query params again... How do i just refresh the page with the same query params and NOT leave my view.
o forgot my delete function code:
public function delete($id = null) {
if (!$this->request->is('post')) {
throw new MethodNotAllowedException();
}
$this->Question->id = $id;
if (!$this->Question->exists()) {
throw new NotFoundException(__('Invalid configuration'));
}
if ($this->Question->delete()) {
$this->Session->setFlash(__('Question deleted'));
return $this->redirect(array("action"=>"search"));
}
$this->Session->setFlash(__('Question was not deleted'));
$this->redirect(array('action' => 'search'));
}
As a workaround i made another function that does the same thing with GET request that my search function does with a POST request. Basically returns the data with the query params. And i used the Session helper to carry the query over to my other function. Dont know how smart that was, but it does the trick for me...
Still would be nice to know if someone has a solution where i dont have to make another function/view
I'm having some issues trying to save an article that has 4 pictures. The thing is that i need to use the article id in order to name the pictures like article_id."-"$i
Since I have only 4 pictures per article this $i should be from 1 to 4 or from 0 to three.
Now the problem is that in order to achieve this i need to create and save Article model so i can have an id to use, but then after performing all the scripting to make the thumbs and form the names, when I go Article->saveAssociated() i have two times the article record created!! i tried to set the id to "-1" before saving but nothing...
Any suggestion will be very much appreciated !!!
Code:
public function add() {
if ($this->request->is ( 'ajax' )) {
$this->layout = 'ajax';
} else {
$this->layout = 'default';
}
if ($this->request->is ( 'post' )) {
$this->Article->create ();
$this->request->data ['Article'] ['time_stamp'] = date ( 'Y-m-d H:i:s', time () );
if ($this->Article->save($this->request->data) ) {
for ($i=0; $i<4; $i++){
$img_path = "./images/";
$extension[$i] = end(explode('.', $this->request->data['Image'][$i]['image']['name']));
$this->request->data['Image'][$i]['image'] = array('name'=>$this->Article->id."-".$i, 'tmp_name' => $this->request->data['Image'][$i]['image']['tmp_name']);
// $this->request->data['Image'][$i]['name'] = $this->Article->id."-".$i;
$this->request->data['Image'][$i]['ext']= $extension[$i];
$target_path[$i] = $img_path . basename($this->request->data['Image'][$i]['image']['name'].".".$extension[$i]);
if(!move_uploaded_file($this->request->data['Image'][$i]['image']['tmp_name'], $target_path[$i])) {
die(__ ( 'Fatal error, we are all going to die.' ));
}else{
$this->Resize->img($target_path[$i]);
$this->Resize->setNewImage($img_path.basename($this->request->data['Image'][$i]['image']['name']."t.".$extension[$i]));
$this->Resize->setProportionalFlag('H');
$this->Resize->setProportional(1);
$this->Resize->setNewSize(90, 90);
$this->Resize->make();
}
}
$this->Article->id;
pr($this->Article->id);
$this->Article->saveAssociated($this->request->data, array('deep' => true));
//$this->redirect ( array ('action' => 'view', $this->Article->id ) );
pr($this->Article->id);
exit;
$this->Session->setFlash ( __ ( 'Article "' . $this->request->data ["Article"] ["name"] . '" has been saved' ) );
} else {
$this->Session->setFlash ( __ ( 'The article could not be saved. Please, try again.' ) );
}
}
$items = $this->Article->Item->find ( 'list' );
$payments = $this->Article->Payment->find ( 'list' );
$shippings = $this->Article->Shipping->find ( 'list' );
$this->set ( compact ( 'items', 'payments', 'shippings' ) );
}
Instead of
$this->Article->saveAssociated();
which would save the Article AGAIN, just save the images separately using something like this:
foreach($this->request->data['Image'] as &$image) {
$image['name'] = 'whatever_you_want' . $this->Article->id;
$image['article_id'] = $this->Article->id;
}
$this->Article->Image->save($this->request->data['Image']);
Another option (not necessarily better - just another option) would just be to append the newly-created Article's id to the existing Article array, then saveAssociated(). If the Article has an id in it's data, it will update instead of create. I would suggest the first answer above, but - just brainstorming other options in case this helps for someone's scenario:
// 1) save the Article and get it's id
// 2) append the `id` into the Article array
// 3) do your image-name manipulation using the id
// 4) saveAssociated(), which updates the Article and creates the Images