In wordpress how to set custom response message for CF7 - wordpress

I want to set custom response message for CF7. Once I submitted through CF7, I will get the response output from wp_remote_post method but unable to show response error message in CF7 form. I have the following code. Please guide me how can I set custom response error message.
add_filter( 'wpcf7_before_send_mail', 'create_tocken' );
function create_tocken( $contact_form ) {
global $wpdb;
if ( ! isset( $contact_form->posted_data ) && class_exists( 'WPCF7_Submission' ) ) {
$submission = WPCF7_Submission::get_instance();
if ( $submission ) {
$form_data = $submission->get_posted_data();
}
} else {
return $contact_form;
}
$body = array(
'username' => 'xxxxx',
'password' => 'xxxxxx',
'type' => 'xxxxx',
'name' => 'xxxxxx',
'phone' => 'xxxxxx',
'email' => 'xxxxxx',
'town' => 'xxxxxx',
);
$url = 'https://example.com/';
$params = array(
'headers' => array(
'Content-Type' => 'application/x-www-form-urlencoded'
),
'body' => $body
);
$response = wp_remote_post( $url, $params );
if ( is_wp_error( $response ) ) {
$error_message = $response->get_error_message();
}
}
Here I wanted to set $error_message as a custom response message.

The following solution fixed this problem.
add_action('wpcf7_before_send_mail', 'cf7_validate_api', 10, 3);
function cf7_validate_api($cf7, &$abort, $submission) {
if ($cf7->id() !== 887)
{
return;
}
$errMsg = '';
$submission = WPCF7_Submission::get_instance();
$postedData = $submission->get_posted_data();
$fields = [];
$api_username = 'xxxxxxx';
$api_key = 'xxxxxxx';
$api_url = 'xxxxxxx';
$fields['username'] = $api_username;
$fields['key'] = $api_key;
$fields['endpoint'] = 'test';
$fields['firstname'] = $postedData['firstname'];
$fields['lastname'] = $postedData['lastname'];
$fields['phone'] = $postedData['phone'];
$fields['email'] = $postedData['email'];
$params = [
'headers' => [
'Content-Type' => 'application/x-www-form-urlencoded',
],
'body' => $fields,
];
$response = wp_remote_post($api_url, $params);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
$errMsg = "Something went wrong:\n{$error_message}";
} else {
$api_result = json_decode($response['body'], true);
if ($api_result['success'] == 'false') {
$errMsg = $api_result['message'];
}
}
if ($errMsg) {
$abort = true;
$submission->set_response($cf7->message('validation_failed'));
$submission->set_response($cf7->filter_message($errMsg)); //custom msg;
}
}

Related

Refresh shipping rates on city select field

I am trying to update/refresh the shipping rates on city change, so far I have managed to do so only by refreshing the page manually.
add_action( 'woocommerce_package_rates', 'check_minimum_and_city', 10, 2 );
function check_minimum_and_city($rates, $package){
$selected_city = WC()->checkout->get_value('billing_city');
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
if(WC()->session->get( 'chosen_shipping_methods' )[0] == 'local_pickup:13'){
$minimum = 0;
}else{
$minimum_thirty = 100;
$minimum_fifty = 150;
$minimum_sixty = 200;
if(in_array($selected_city, $price_thirty)){
unset( $rates['flat_rate:18']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_thirty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_thirty )
)
);
}
}elseif(in_array($selected_city, $price_fifty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:19']);
if(WC()->cart->subtotal < $minimum_fifty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_fifty )
)
);
}
}elseif(in_array($selected_city, $price_sixty)){
unset( $rates['flat_rate:9']);
unset( $rates['flat_rate:18']);
if(WC()->cart->subtotal < $minimum_sixty){
throw new Exception(
sprintf( 'סכום ההזמנה הנוכחית שלך עומד על %s, מינימום הזמנה לפני משלוח הינו %s.' ,
wc_price( WC()->cart->subtotal ),
wc_price( $minimum_sixty )
)
);
}
}
return $rates;
}
}
When I select a city field (dropdown custom list) I get the shipping cost I have made through the woocommerce settings but when I change it it does not update the rates.
add_filter( 'woocommerce_checkout_fields', 'city_dropdown_field' );
function city_dropdown_field( $fields ) {
$city_args = wp_parse_args( array(
'type' => 'select',
'options' => array(
'' => '',
'yavne' => 'יבנה',
'kfar-nagid' => 'כפר הנגיד',
'galiya' => 'גאליה',
'ben-zakai' => 'בן זכאי',
'beit-gamliel' => 'בית גמליאל',
'bnaya' => 'בניה',
'einot' => 'עינות',
'kfar-aviv' => 'כפר אביב',
'gan-shlomo' => 'גן שלמה',
'beit-oved' => 'בית עובד',
'aseret' => 'עשרת',
'givat-brener' => 'גבעת ברנר',
'irus' => 'אירוס',
'misgav-dov' => 'משגב דב',
'givton' => 'גיבתון',
'kerem-yavne' => 'כרם יבנה',
'beit-raban' => 'בית רבן',
'rehovot' => 'רחובות',
'beit-elezri' => 'בית אלעזרי',
'beit-hanan' => 'בית חנן',
'kvuzat-yavne' => 'קבוצת יבנה',
'kfar-bilu' => 'כפר בילו',
'bnei-darom' => 'בני דרום',
'nir-galim' => 'ניר גלים',
'kiryat-ekron' => 'קרית עקרון',
'gedera' => 'גדרה',
'nes-tziona' => 'נס ציונה',
'kanot' => 'כנות',
'netayim' => 'נטעים',
'gan-darom' => 'גן דרום',
'givatayim' => 'גבעתיים',
'ramat-gan' => 'רמת גן',
'tel-aviv-yafo' => 'תל אביב - יפו',
'bnei-brak' => 'בני ברק',
'ramat-hasharon' => 'רמת השרון',
'herzliya' => 'הרצליה',
'kfar-shmariyahu' => 'כפר שמריהו',
'rishpon' => 'רישפון',
'raanana' => 'רעננה',
'kfar-saba' => 'כפר סבא',
'bat-yam' => 'בת ים',
'hulon' => 'חולון',
'azur' => 'אזור',
'savion' => 'סביון',
'ganei-tikva' => 'גני תקווה',
'or-yehuda' => 'אור יהודה',
'kiryat-ono' => 'קרית אונו',
'yehud' => 'יהוד',
'petah-tikva' => 'פתח תקווה',
'rishon-letzion' => 'ראשון לציון',
'mishmar-hashiva' => 'משמר השבעה',
'gan-sorek' => 'גן שורק',
'beit-dagan' => 'בית דגן',
'ganot' => 'גנות',
'beit-hanan-irus' => 'בית חנן אירוס',
'hemed' => 'חמד',
'tsafria' => 'צפריה',
'beer-yaakov' => 'באר יעקב',
'netser-sireni' => 'נצר סירני',
'nir-tzvi' => 'ניר צבי',
'ramla' => 'רמלה',
'matsliax' => 'מצליח',
'clear' => true
),
), $fields['shipping']['shipping_city'] );
$fields['shipping']['shipping_city'] = $city_args;
$fields['billing']['billing_city'] = $city_args;
return $fields;
}
Tried using this jQuery but nothing does the work
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery( function($){
// Shipping fias code change & input events
$(document.body).on( 'change', 'select[name=billing_city]', function() {
console.log($(this).val());
});
});
</script>
<?php
endif;
}
Help is appreciated. :-)
I have Managed to resolve the issue and here is my solution, the answer was in corrected AJAX call and changing from multiple shipping rates to one and changing the rate by code.
add_action('woocommerce_checkout_update_order_review', 'refresh_shipping_methods', 10, 1 );
function refresh_shipping_methods( $post_data ){
WC()->cart->calculate_shipping();
}
add_action( 'wp_footer', 'checkout_shipping_city_refresh_display' );
function checkout_shipping_city_refresh_display() {
// On checkout
if ( is_checkout() && ! is_wc_endpoint_url() ) :
?><script type="text/javascript">
jQuery(document).on('change', 'select[name=billing_city]', function(){
var requested_city = jQuery(this).val();
ajaxurl = '<?php echo admin_url( 'admin-ajax.php' ) ?>'; // get ajaxurl
var data = {
'action': 'get_and_set_shipping_rate',
'city': requested_city
};
jQuery.ajax({
type: "POST",
url: ajaxurl, // this will point to admin-ajax.php
data: data,
async: false,
success: function (response) {
console.log(response);
setTimeout(function (){
jQuery('.shipping_method:checked').trigger('change');
});
}
});
});
</script>
<?php
endif;
}
function get_and_set_shipping_rate(){
$shipping_city = $_POST['city'];
$shipping_cost = get_shipping_cost_by_city($shipping_city);
setcookie('shipping_city_cost', $shipping_cost, time() + (86400 * 30), '/');
$_COOKIE['shipping_city_cost'] = $shipping_cost;
echo $shipping_cost;
wp_die();
}
add_action( 'wp_ajax_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
add_action( 'wp_ajax_nopriv_get_and_set_shipping_rate', 'get_and_set_shipping_rate' );
function get_shipping_cost_by_city( $city ) {
$cost = 30;
$price_thirty = array('bat-yam','hulon','azur','tel-aviv-yafo','givatayim','ramat-gan','bnei-brak','rishon-letzion','netaim','yavne','kfar-nagid','galiya','ben-zakai','beit-gamliel');
$price_fifty = array('einot','gan-shlomo','beit-oved','aseret','givat-brener','irus','misgav-dov','givton','kerem-yavne','beit-raban','rehovot','beit-elezri','beit-hanan','kvuzat-yavne','kfar-bilu','bnei-darom','nir-galim','kiryat-ekron','gedera','nes-tziona','kanot','gan-darom','netayim','mishmar-hashiva','gan-sorek','beit-dagan','ganot','beit-hanan-irus','hemed');
$price_sixty = array('savion','ganei-tikva','or-yehuda','kiryat-ono','yehud','petah-tikva','ramat-hasharon','herzliya','kfar-shmariyahu','rishpon','raanana','kfar-saba','tsafria','beer-yaakov','netser-sireni','nir-tzvi','ramla','matsliax','bnaya','kfar-aviv');
// SET HERE the default cost (when "calculated cost" is not yet defined)
if(in_array($city, $price_thirty)){
$cost = 30;
}elseif(in_array($city, $price_fifty)){
$cost = 50;
}elseif(in_array($city, $price_sixty)){
$cost = 60;
}
return $cost;
}
add_filter('woocommerce_package_rates', 'update_shipping_costs_based_on_cart_session_custom_data', 10, 2);
function update_shipping_costs_based_on_cart_session_custom_data( $rates, $package ){
$selected_city = WC()->checkout->get_value('billing_city');
$calculated_cost = get_shipping_cost_by_city($selected_city);
if ( is_admin() && ! defined( 'DOING_AJAX' ) )
return $rates;
// SET HERE the default cost (when "calculated cost" is not yet defined)
$cost = '30';
// Iterating though Shipping Methods
foreach ( $rates as $rate_key => $rate_values ) {
$method_id = $rate_values->method_id;
$rate_id = $rate_values->id;
// For "Flat rate" Shipping" Method only
if ( 'flat_rate' === $method_id ) {
if( ! empty( $calculated_cost ) ) {
$cost = $calculated_cost;
}
// Set the rate cost
$rates[$rate_id]->cost = number_format($rates[$rate_id]->cost * $cost, 2);
WC()->session->set( 'shipping_calculated_cost', $rates[$rate_id]->cost );
// Taxes rate cost (if enabled)
foreach ($rates[$rate_id]->taxes as $key => $tax){
if( $rates[$rate_id]->taxes[$key] > 0 ){ // set the new tax cost
$taxes[$key] = number_format( $rates[$rate_id]->taxes[$key] * $cost, 2 );
$has_taxes = true;
} else {
$has_taxes = false;
}
}
if( $has_taxes )
$rates[$rate_id]->taxes = $taxes;
}
}
return $rates;
}

Add links on Wordpress custom endpoint

I created a custom endpoint for specific data from a custom table in my Wordpress plugin. It get's all the data from the table with the getHelpers() function. After that it will be merged by some user data. I would like to add the profile_image as a link to the response so we can get it with the embed parameter.
What is the best way to add the link to the response? I know the $response->add_link() function but this would add it to the response and not to each contributor.
I tried to add the link as an array but this won't react on the _embed parameter.
This is my code for the custom endpoint:
class VEMS_Rest_Contributors extends WP_REST_Controller {
protected $namespace = 'vems/v2';
protected $rest_base = 'contributors';
/**
* Register the routes for coupons.
*/
public function register_routes() {
register_rest_route( $this->namespace, '/' . $this->rest_base, array(
'methods' => WP_REST_Server::READABLE,
'callback' => array( $this, 'get_items' ),
'args' => $this->get_collection_params(),
) );
}
public function get_items( WP_REST_Request $request ) {
$project_id = $request->get_param( 'project_id' );
$contributors = array();
if( !empty($project_id) ) {
$project = new VEMS_Project( $request['project_id'] );
$helpers = $project->getHelpers();
foreach($helpers as $helper) {
$contributor = array();
if( !empty($helper->contributor_id) ) {
$user = get_user_by( 'ID', $helper->contributor_id );
$user_meta = get_user_meta( $helper->contributor_id );
$contributor['ID'] = $helper->contributor_id;
$contributor['user_nicename'] = $user->data->display_name;
$contributor['user_profile_image'] = $user_meta['contributor_profile_image'][0];
} else {
$contributor['user_nicename'] = $helper->name;
$contributor['user_profile_image'] = $helper->image_id;
}
$contributor['item_total'] = $helper->item_total;
$contributor['checked'] = $helper->checked;
$contributor['helper_date'] = $helper->helper_date;
/*
$contributor['_links']['profile_image'] = array(
'href' => rest_url( '/wp/v2/media/' . $contributor['user_profile_image'] ),
'embeddable' => true
);
*/
$contributors[] = $contributor;
}
}
$response = rest_ensure_response( $contributors );
return $response;
}
public function get_collection_params() {
$params['project_id'] = array(
'description' => __( 'Limit result set to contributors assigned a specific project.', 'vems' ),
'type' => 'integer',
'sanitize_callback' => 'absint',
'validate_callback' => 'rest_validate_request_arg',
);
return $params;
}
}
to handle links on route vems/v2/contributors?_embed, the element profile_image must be an array of links and then you can do that
$contributor['_links']['profile_image'] = [
[
'href' => rest_url( '/wp/v2/media/' . $contributor['ID'] ),
'embeddable' => true,
],
];

Drupal 7: How to send HTML Email

Could someone tell me what i am missing to send an HTML email using Drupal's function? Here is my call:
try{
drupal_mail('my_module', 'forgot', $node->field_email_address['und'][0]['value'], language_default(), array('reset_key' => $key),'do-not-reply#myemailaddress.com');
}catch(Exception $e){
print_r($e->getMessage());die();
}
And here is the function:
function my_module_mail($key, &$message, $params) {
$body = '<p>Click the link below to reset your password.</p>
<p>Click this link to reset your password</p>
';
// $headers = array(
// 'MIME-Version' => '1.0',
// 'Content-Type' => 'text/html; charset=UTF-8; format=flowed',
// 'Content-Transfer-Encoding' => '8Bit',
// 'X-Mailer' => 'Drupal'
// );
// $message['headers'] = $headers;
$message['subject'] = 'Why wont this send html??';
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['body'][] = $body;
$message['from'] = 'do-not-reply#myemailaddress.com';
}
I tired just the html header and the full set that is commented out. What am I missing? The email sends fine but it's plain text. Thanks and let me know!
You can use this function
function my_module_custom_drupal_mail($target = NULL, $from = null, $subject, $message, $attachment = NULL){
$my_module = 'my_module';
$my_mail_token = microtime();
$message = array(
'id' => $my_module . '_' . $my_mail_token,
'to' => $target,
'subject' => $subject,
'body' => array($message),
'module' => $my_module,
'key' => $my_mail_token,
'from' => "$from <email#email.com>",
'headers' => array(
'From' => "$from <email#email.com>",
'Sender' => "$from <email#email.com>",
'Return-Path' => "$from <email#email.com>",
'Content-Type' => 'text/html; charset=utf-8'
),
);
if ($attachment) {
$file_content = file_get_contents($attachment[0]);
$message['params']['attachments'][] = array(
'filecontent' => $file_content,
'filename' => $attachment[1],
'filemime' => $attachment[2],
);
}
$system = drupal_mail_system($my_module, $my_mail_token);
$message = $system->format($message);
if ($system->mail($message)) {
return TRUE;
}
else {
return FALSE;
}
}
AND call it like :
$body = '<p>Click the link below to reset your password.</p>
<p>Click this link to reset your password</p>
';
$subject ='Why wont this send html??';
$from = 'myemail#email.com';
$sent = my_module_custom_drupal_mail($node->field_email_address['und'][0]['value'], $from, $subject, $body);
Customize it like you want ! :)
A few things need to be done:
/**
* Class SomeCustomModuleMailSystem Implements MailSystemInterface.
*
* Used to enable HTML email to be sent.
*/
class SomeCustomModuleMailSystem extends DefaultMailSystem {
public function format(array $message) {
$message['body'] = implode("\n\n", $message['body']);
$message['body'] = drupal_wrap_mail($message['body']);
return $message;
}
}
This to be done one time, so probably in a hook_enable or hook_update:
$current = variable_get('mail_system', ['default-system' => 'DefaultMailSystem']);
$addition = ['some_custom_module' => 'SomeCustomModuleMailSystem'];
variable_set('mail_system', array_merge($current, $addition));
Invoke hook_mail as normal, e.g.
/**
* Implements hook_mail().
*/
function some_custom_module_mail($key, &$message, $params) {
switch ($key) {
case 'some_mail_key':
$message['headers']['Content-Type'] = 'text/html; charset=UTF-8;';
$message['subject'] = $params['subject'];
$message['body'][] = $params['body'];
break;
}
}
Finally call it with something like this:
// Set variables required for the email.
$module = 'some_custom_module';
$key = 'some_mail_key';
$to = $email = 'thetoaddress#something.com';
$language = language_default();
$params['subject'] = 'Email subject';
$params['body'] = '<html><body>The HTML!</body></html>';
$from = 'thefromaddress#something.com';
$send = TRUE;
// Send the mail and log the result.
$result = drupal_mail($module, $key, $to, $language, $params, $from, $send);
if ($result['result'] === TRUE) {
watchdog('some_custom_module', 'HTML email successfully sent.', [], WATCHDOG_INFO);
}
else {
watchdog('some_custom_module', 'HTML email failed to send', [], WATCHDOG_ERROR);
}

Not displayed in the article list until you click "Update" on the dashboard

I am challenging Ajax implementation when replying by "BBPress".
However, reply posted in this manner is displayed in the dashboard, but it is not displayed in the loop of the replies list.
This will be displayed in the loop of the replies list only when you click "Update" on the dashboard.
I want to know the code that displays correctly in the loop.
This is my code:
my-reply.js
"use strict";
(function($){
$(document).on("click","#bbp_reply_submit", function() {
// get
var inputForum = '56'; //There is only one forum.
var inputTopic = $('#bbp_topic_id').val();
var inputTitle = $('#bbp-reply-form-info').text();
var inputContent = $('#bbp_reply_input').val();
var inputParent = $('#bbp_reply_to').val();
var inputIp = $('#my_reply_ip').val();
// Ajax
$.ajax({
url: MY_AJAX.api,
type: 'POST',
data: {
// action name
action: MY_AJAX.action,
// nonce
nonce: MY_AJAX.nonce,
// submit data
submitForum: inputForum,
submitTopic: inputTopic,
submitTitle: inputTitle,
submitContent: inputContent,
submitParent: inputParent,
submitIp: inputIp,
}
})
// scusess
.done(function( response ) {
alert('success'); // Actually, I will display reply instead of alerts.
})
// error
.fail(function( jqXHR, textStatus, errorThrown ) {
alert('error');
});
});
})(jQuery);
functions.php
// nonce
function my_enqueue_scripts() {
$handle = 'my-script';
$jsFile = 'path/to/myscript.js';
wp_register_script($handle, $jsFile, ['jquery']);
$acrion = 'my-ajax-action';
wp_localize_script($handle, 'MY_AJAX', [
'api' => admin_url( 'admin-ajax.php' ),
'action' => $acrion,
'nonce' => wp_create_nonce( $acrion ),
]);
wp_enqueue_script($handle);
}
add_action( 'wp_enqueue_scripts', 'my_enqueue_scripts' );
// post reply
function my_ajax_event() {
$action = 'my-ajax-action';
if( check_ajax_referer($action, 'nonce', false) ) {
$submitForum = esc_html( $_POST['submitForum'] );
$submitTopic = esc_html( $_POST['submitTopic'] );
$submitTitle = esc_html( $_POST['submitTitle'] );
$submitContent = esc_html( $_POST['submitContent'] );
$submitParent = esc_html( $_POST['submitParent'] );
$submitIp = esc_html( $_POST['submitIp'] );
$submitTopicslug = esc_html( $_POST['submitTopicslug'] );
$page = get_post( $submitTopic );
$slug = $page->post_name;
$date = 'Y-m-d H:i:s';
$my_post = array(
'post_title' => (string)wp_strip_all_tags($_POST['submitTitle']),
'post_content' => (string)$_POST['submitContent'],
'post_status' => 'publish',
'post_author' => get_current_user_id(),
'post_type' => 'reply',
'meta_input' => array(
'_bbp_forum_id' => $_POST['submitForum'],
'_bbp_topic_id' => $_POST['submitTopic'],
'_bbp_reply_to' => $_POST['submitParent'],
'_bbp_author_ip' => $_POST['submitIp'],
'_edit_last' => get_current_user_id(),
'_bbp_topic_sort_desc' => 'dft',
'_bbp_sort_desc' => 'dft',
'_bbp_topic_sort_show_lead_topic' => 'dft',
'_bbp_topic_sort_show_lead_topic_forum' => 'dft',
'_wp_old_slug' => $slug,
'_bbp_last_active_time' => $date,
'_bbp_reply_count' => '',
'_bbp_engagement' => '',
'_bbp_reply_count_hidden' => '',
'_bbp_voice_count' => '',
)
);
wp_insert_post( $my_post );
} else {
status_header( '403' );
}
die();
}
add_action( 'wp_ajax_my-ajax-action', 'my_ajax_event' );
add_action( 'wp_ajax_nopriv_my-ajax-action', 'my_ajax_event' );

WordPress - Get Current Post Author ID Outside The Loop And Inside A Plugin

I am trying to modify a plugin. I need the author id of the current post to accomplish what I am doing. I have tried every other method I have found over internet that claims to get the post author id outside the loop but its not working inside the plugin. I guess its because the plugins might be loaded before the loop variables or something? Please pardon me as I am not a Pro.
Here is what I have tried so far.
1.
$author_id=$post->post_author;
2.
global $post;
$author_id=$post->post_author;
3.
$post_tmp = get_post($post_id);
$author_id = $post_tmp->post_author;
4.
$author_id = $posts[0]->post_author;
But nothing works in the plugin's directory. Can anyone help?
Detailed Explanation:
I am trying to modify woodiscuz plugin. The problem with this plugin is that it held comments of even seller for moderation. So if I am the seller and I reply to some buyer in comment, I will have to approve my own comment.
Now to overcome this problem, I am putting a condition that if the author of the post (seller) is commenting, then don't put the comment for moderation.
Here is the function of the plugin that is controlling comments.
public function comment_submit_via_ajax() {
$message_array = array();
$comment_post_ID = intval(filter_input(INPUT_POST, 'comment_post_ID'));
$comment_parent = intval(filter_input(INPUT_POST, 'comment_parent'));
if (!$this->wpc_options->wpc_options_serialized->wpc_captcha_show_hide) {
if (!is_user_logged_in()) {
$sess_captcha = $_SESSION['wpc_captcha'][$comment_post_ID . '-' . $comment_parent];
$captcha = filter_input(INPUT_POST, 'captcha');
if (md5(strtolower($captcha)) !== $sess_captcha) {
$message_array['code'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_captcha'];
echo json_encode($message_array);
exit;
}
}
}
$comment = filter_input(INPUT_POST, 'comment');
if (is_user_logged_in()) {
$user_id = get_current_user_id();
$user = get_userdata($user_id);
$name = $user->display_name;
$email = $user->user_email;
$user_url = $user->user_url;
} else {
$name = filter_input(INPUT_POST, 'name');
$email = filter_input(INPUT_POST, 'email');
$user_id = 0;
$user_url = '';
}
$comment = wp_kses($comment, array(
'br' => array(),
'a' => array('href' => array(), 'title' => array()),
'i' => array(),
'b' => array(),
'u' => array(),
'strong' => array(),
'p' => array(),
'img' => array('src' => array(), 'width' => array(), 'height' => array(), 'alt' => array())
));
$comment = $this->wpc_helper->make_clickable($comment);
if ($name && filter_var($email, FILTER_VALIDATE_EMAIL) && $comment && filter_var($comment_post_ID)) {
$held_moderate = 1;
if ($this->wpc_options->wpc_options_serialized->wpc_held_comment_to_moderate) {
$held_moderate = 0;
}
// $held_moderate = 1 -> No moderation
/*This is the part where I need to put the custom condition*/
if($post_author_id == get_current_user_id())
{
$held_moderate = 1;
}
$new_commentdata = array(
'user_id' => $user_id,
'comment_post_ID' => $comment_post_ID,
'comment_parent' => $comment_parent,
'comment_author' => $name,
'comment_author_email' => $email,
'comment_content' => $comment,
'comment_author_url' => $user_url,
'comment_type' => 'woodiscuz',
'comment_approved' => $held_moderate
);
$new_comment_id = wp_insert_comment($new_commentdata);
$new_comment = new WPC_Comment(get_comment($new_comment_id, OBJECT));
if (!$held_moderate) {
$message_array['code'] = -2;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_held_for_moderate'];
} else {
$message_array['code'] = 1;
$message_array['message'] = $this->comment_tpl_builder->get_comment_template($new_comment);
}
$message_array['wpc_new_comment_id'] = $new_comment_id;
} else {
$message_array['code'] = -1;
$message_array['wpc_new_comment_id'] = -1;
$message_array['message'] = $this->wpc_options->wpc_options_serialized->wpc_phrases['wpc_invalid_field'];
}
echo json_encode($message_array);
exit;
}

Resources