Rename comments labels in WP admin - wordpress

Is it possible to change default comments in wordpress admin?
I`d like to rename comments into testimonials everywhere in admin.

If you want to change all WordPress uses of 'Comment', then you need to hook into the translation filter
is_admin() && add_filter('gettext', function ($translation, $text, $domain) {
if (strpos($translation, 'comment') !== FALSE) {
return str_replace('comment', 'testimonial', $translation);
}
if (strpos($translation, 'Comment') !== FALSE) {
return str_replace('Comment', 'Testimonial', $translation);
}
return $translation;
}, 10, 3);
But that changes EVERYTHING that runs through gettext.
If you just wanted to change the admin section title you would do this:
add_action('admin_head', function () {
global $wp_meta_boxes;
if (!empty($wp_meta_boxes)) {
foreach ($wp_meta_boxes as $page => &$positions) {
foreach ($positions as $context => &$priorities) {
foreach ($priorities as $priority => &$boxes) {
foreach ($boxes as $id => &$box) {
if ($id === 'commentsdiv') {
$box['title'] = 'Testimonials';
break;
}
}
}
}
}
}
});
Beyond that, you'd have to find every instance of 'Comment' and see if there was an associated hook for that situation. I'm not sure if that is feasible.

Related

Update post terms in each languages by code

who can hellp with this, i need create post from code, by wp_insert_post
function, so what is going on:
I creating post on each existing laguages, then i update all needed fields and i need to set post term depened of current language.
I have terms (shelters) https://prnt.sc/pklSXojB2jZj - i need that post set to current lang shelter while create, but after creating i got - https://prnt.sc/pz2jFEq1OAMP , 2 posts set in one lang terms. Maybe who know whats goes wrong, below i provided 2 functions who do these actions, Thanks in advance:
function add_pet($form_data, $ready_data, $update_meta = false) {
$allLang = pll_languages_list();
if ($allLang) {
$postsArr = array();
foreach ($allLang as $lang) {
//Add new pet
$post_id = wp_insert_post(array(
'post_title' => $form_data['pet_name'],
'post_status' => 'publish',
'post_author' => $form_data['user_id'],
'post_type' => 'pets',
));
//Check if post created, update all needed fields, and update post terms (shelter)
if ($post_id) {
//Get all translation of term
$shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
$update_meta['shelter'] = $shelter_id;
//In this function we update those terms
$update_success = update_pets_fields($post_id, $ready_data, $update_meta);
$postsArr[$lang] = $post_id;
pll_set_post_language($post_id, $lang);
$postDate = get_post($post_id)->post_date;
$unixDate = strtotime($postDate);
update_post_meta($post_id, 'pet_update_date', $unixDate);
}
}
//Save post translation
if ($postsArr) {
pll_save_post_translations($postsArr);
}
//Old code
// foreach ($allLang as $lang) {
// $cat_id = pll_get_term(intval($form_data['kind_of_animal']), $lang);
// $shelter_id = pll_get_term(intval($form_data['shelter']), $lang);
// $post_id = $postsArr[$lang];
// $update_meta['post_category'] = $cat_id;
// $update_meta['shelter'] = $shelter_id;
// $update_success = update_pets_fields($post_id, $ready_data, $update_meta);
// }
}
if (is_wp_error($post_id)) {
wp_send_json_error($post_id->get_error_message());
}
if ($update_success) {
wp_send_json_success('Post was created.');
} else {
wp_send_json_error('Post was not created.');
}
}
And function who update field
/Update pets fields
function update_pets_fields($post_id, $data, $update_meta = false) {
if (!$post_id) return;
//Update post meta data not acf
if (isset($update_meta) && !empty($update_meta['title'])) {
$post_update = array(
'ID' => $post_id,
'post_title' => $update_meta['title']
);
$result = wp_update_post($post_update);
if (is_wp_error($result)) {
wp_send_json_error('Fields was not updated');
}
}
if (isset($update_meta['shelter']) && !empty($update_meta['shelter']) && intval($update_meta['shelter'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'sholters');
$shelter_id = intval($update_meta['shelter']);
wp_set_post_terms($post_id, array($shelter_id), 'sholters');
if (is_wp_error($result)) {
wp_send_json_error('Term not updated');
}
}
if (isset($update_meta['post_category']) && !empty($update_meta['post_category']) && intval($update_meta['post_category'])) {
wp_remove_object_terms($post_id, 'uncategorized', 'category');
wp_set_post_categories($post_id, intval($update_meta['post_category']));
if (is_wp_error($result)) {
wp_send_json_error('Category not updated');
}
}
if (isset($update_meta['thumbnail']) && !empty($update_meta['thumbnail']) && intval($update_meta['thumbnail'])) {
set_post_thumbnail($post_id, intval($update_meta['thumbnail']));
}
if (is_null($data)) {
wp_send_json_error('No data.');
}
foreach ($data as $field) {
if ($field[3] === 'where_is') {
$field_array['field_62169d3cffb5b'] = array(
$field[2] => $field[1],
);
} else {
$field_array = array(
$field[2] => $field[1],
);
}
if (!empty($field[1])) {
$result = update_field('field_621696a7ffb4e', $field_array, $post_id);
}
}
if ($result) {
return false;
} else {
return true;
}
}
I try update it in diferent variants but it does't work, i check ids that come in args all ids is right and all posts ids is right.But on at the exit we got 2 posts in 1 term

Search for different custom post type

I want to filter my posts using search in wordpress.When i use below code
function mySearchFilter($query) {
$post_type = 'blog';
if ($query->is_search) {
if (!empty($post_type)) {
$query->set('post_type', $post_type);
}
}
return $query;
}
add_filter('pre_get_posts','mySearchFilter');
The results is showing currect.But if I use multiple custom post type how can i get different posts.My url showing post_type=kb_article.Is there any solution for this
You can use pre_get_posts hook.
For example:
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', array( 'post', 'movie' ) );
}
}
}
add_action('pre_get_posts','search_filter');
Refer

How to use filter to dynamic shortcodes?

I just create shortcodes like this:
add_shortcode( 'demo1', 'demo1_init' ) );
add_shortcode( 'demo2', 'demo2_init' ) );
function demo1_init() {
// Shortcode Def. here...
}
function demo2_init() {
// Shortcode Def. here...
}
How can I use filters to create these shortcodes dynamically? Something like this. E.g.
$a = array(
"demo1" => "demo1_init",
"demo2" => "demo2_init",
);
The following should get the job done
function demo1_init() {
// Shortcode Def. here...
return "demo1";
}
function demo2_init() {
// Shortcode Def. here...
return "demo2";
}
function register_shortcodes() {
$shortcodes = array(
"demo1" => "demo1_init",
"demo2" => "demo2_init",
);
foreach($shortcodes as $shortcode => $func) {
add_shortcode($shortcode, $func);
}
}
add_action( "init", "register_shortcodes" );

custom module slowing drupal

I have worked on a custom shipping module to match my commerce module shipping needs. I have noticed that the module is slowing drupal a lot on a lot the pages even-though I am basically my module should only be hooking to drupal commerce checkout.
Here is my module code:
function myips_commerce_shipping_method_info() {
$shipping_methods = array();
$shipping_methods['IPS'] = array(
'title' => t('IPS'),
'description' => t('Quote rates from IPS'),
);
return array($shipping_methods);
}
function myips_commerce_shipping_service_info() {
$shipping_services = array();
$shipping_services['myips_shipping_service'] = array( //arbitrary name w/ 'service' in there
'title' => t('Custom Shipping Service'), //title for the interface
'description' => t('Variable rates based on the book origin '),
'display_title' => t('IPS Shipping'),
'shipping_method' => 'IPS',
'price_component' => 'shipping', //from commerce_shipping
'callbacks' => array(
'rate' => 'myips_service_rate_order'),
);
return $shipping_services;
}
function myips_service_rate_order($shipping_service, $order) {
$order_number=$order->order_number;
$currency_code='USD';
$shipping_total=getordershipmentvalue($order_number);
$rates['myips_shipping_service']=array(
'amount' => commerce_currency_decimal_to_amount($shipping_total, $currency_code),
'currency_code' =>$currency_code,
'data' => array(),
);
return $rates[$shipping_service['name']];
}
function getcustomershippingcountry($order_id) {
$order=commerce_order_load($order_id);
$profile_id=$order->commerce_customer_shipping['und']['0']['profile_id'];
$profile=commerce_customer_profile_load($profile_id);
$country= $profile->commerce_customer_address[LANGUAGE_NONE]['0']['country'];
return $country;
}
function getordershipmentvalue($order_id) {
$order=commerce_order_load($order_id);
$total=0;
foreach($order->commerce_line_items[LANGUAGE_NONE] as $line) {
$line_item_id=$line['line_item_id'];
$total=$total+getitemshipmentvalue($line_item_id);
}
return $total;
}
function getitemshipmentvalue($line_item_id){
$line_item=commerce_line_item_load($line_item_id);
$line_quantity=$line_item->quantity;
$order_id= $line_item->order_id;
$destination= getcustomershippingcountry($order_id);
$product_id=$line_item->commerce_product[LANGUAGE_NONE]['0']['product_id'];
$product=commerce_product_load($product_id);
$product_weight=$product->field_book_weight[LANGUAGE_NONE]['0']['weight'];
$product_origin=$product->field_book_origin[LANGUAGE_NONE]['0']['value'];
$line_total=getshippingrates($destination, $product_origin, $product_weight*$line_quantity);
return $line_total;
}
function calculateshippment($shipping_type, $zone, $product_weight) {
$query=new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', $shipping_type);
$query->fieldCondition('field_up_to_weight', 'value',$product_weight,'>=');
$query->fieldCondition('field_zone_number', 'value',$zone);
$query->fieldorderby('field_up_to_weight','value','ASC');
$query->range(0,1);
$result=$query->execute();
if(!empty($result)){
$nodes=node_load_multiple(array_keys($result['node']));
foreach($nodes as $node) {
$price=$node->field_shipment_price[LANGUAGE_NONE][0]['value'];
}
}
return $price;
}
function getdestinationzone($destination, $shipping_type) {
$query=new EntityFieldQuery();
$query->entityCondition('entity_type', 'node');
$query->entityCondition('bundle', 'countries_zones');
$query->fieldCondition('field_country_abbreviation', 'value',$destination);
$result=$query->execute();
if(!empty($result)) {
$nodes=node_load_multiple(array_keys($result['node']));
foreach($nodes as $node) {
if($shipping_type=='out_us_zone_prices') {
$zone=$node->field_us_zone[LANGUAGE_NONE]['0']['value'];
}elseif($shipping_type=='mail_zone_prices') {
$zone=$node->field_mail_zone[LANGUAGE_NONE]['0']['value'];
}elseif($shipping_type=='dhl_zone_prices') {
$zone=$node->field_dhl_zone[LANGUAGE_NONE]['0']['value'];
}
}
}
return $zone;
}
function getshippingrates($destination, $product_origin, $product_weight) {
if($product_origin=='US') {
if($destination==$product_origin) {
$shipping_type='us_zone_prices';
}else {
$shipping_type='out_us_zone_prices';
}
/* End of Product Origin US */
}elseif($product_origin=='LB'){
if($destination==$product_origin) {
$shipping_type='mail_zone_prices';
}else {
$shipping_type='dhl_zone_prices';
}
}
$zone=getdestinationzone($destination,$shipping_type);
return calculateshippment($shipping_type, $zone, $product_weight);
}
Why would my module slowing drupal performance?
I think the main problem of your module is that your database queries are in a foreach-loop (in getordershipmentvalue())
Ok you maybe can't see it immediately, but if you look behind the getitemshipmentvalue()-call, you can see, that there are many other function calls there.
And over multiple corners the functions calculateshippment() and getdestinationzone() will be called. In these functions there are database-queries.
Thats the reason, why your module is so slow: Because over multiple corners you query the database in a loop. This is similar to a DOS-Attack on the database-server (A bigger problem with great arrays of "commerce_line_items").
The solution: Think about your code-design. Try to put your database-query-code outside of the foreach-loop.
I would also prefer to cache the data after the first request. (For example with variable_set())

Extending WP_List_Table / handling checkbox options in plugin administration

I'm working on a WordPress plugin, and part of that plugin requires extending WP_List_Table and storing any of the items which are checked in that table to an option. I've managed to figure out how to properly setup and display the required table, but how do I handle storing the checked options?
Here's what I've got so far...
class TDBar_List_Table extends WP_List_Table {
// Reference parent constructor
function __construct() {
global $status, $page;
// Set defaults
parent::__construct( array(
'singular' => 'theme',
'plural' => 'themes',
'ajax' => false
));
}
// Set table classes
function get_table_classes() {
return array('widefat', 'wp-list-table', 'themes');
}
// Setup default column
function column_default($item, $column_name) {
switch($column_name) {
case 'Title':
case 'URI':
case'Description':
return $item[$column_name];
default:
return print_r($item, true);
}
}
// Displaying checkboxes!
function column_cb($item) {
return sprintf(
'<input type="checkbox" name="%1$s" id="%2$s" value="checked" />',
//$this->_args['singular'],
$item['Stylesheet'] . '_status',
$item['Stylesheet'] . '_status'
);
}
// Display theme title
function column_title($item) {
return sprintf(
'<strong>%1$s</strong>',
$item['Title']
);
}
// Display theme preview
function column_preview($item) {
if (file_exists(get_theme_root() . '/' . $item['Stylesheet'] . '/screenshot.png')) {
$preview = get_theme_root_uri() . '/' . $item['Stylesheet'] . '/screenshot.png';
} else {
$preview = '';
}
return sprintf(
'<img src="%3$s" style="width: 150px;" />',
$preview,
$item['Title'],
$preview
);
}
// Display theme description
function column_description($item) {
if (isset($item['Version'])) {
$version = 'Version ' . $item['Version'];
if (isset($item['Author']) || isset($item['URI']))
$version .= ' | ';
} else {
$version = '';
}
if (isset($item['Author'])) {
$author = 'By ' . $item['Author'];
if (isset($item['URI']))
$author .= ' | ';
} else {
$author = '';
}
if (isset($item['URI'])) {
$uri = $item['URI'];
} else {
$uri = '';
}
return sprintf(
'<div class="theme-description"><p>%1$s</p></div><div class="second theme-version-author-uri">%2$s%3$s%4$s',
$item['Description'],
$version,
$author,
$uri
);
}
// Setup columns
function get_columns() {
$columns = array(
'cb' => '<input type="checkbox" />',
'title' => 'Theme',
'preview' => 'Preview',
'description' => 'Description'
);
return $columns;
}
// Make title column sortable
function get_sortable_columns() {
$sortable_columns = array(
'title' => array('Title', true)
);
return $sortable_columns;
}
// Setup bulk actions
function get_bulk_actions() {
$actions = array(
'update' => 'Update'
);
return $actions;
}
// Handle bulk actions
function process_bulk_action() {
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
if ('update' === $this->current_action()) {
foreach ($themes as $theme) {
if ($theme['Stylesheet'] . '_status' == 'checked') {
// Do stuff - here's the problem
}
}
}
}
// Handle data preparation
function prepare_items() {
// How many records per page?
$per_page = 10;
// Define column headers
$columns = $this->get_columns();
$hidden = array();
$sortable = $this->get_sortable_columns();
// Build the array
$this->_column_headers = array($columns, $hidden, $sortable);
// Pass off bulk action
$this->process_bulk_action();
// Define our data source
if (defined('WP_ALLOW_MULTISITE') && WP_ALLOW_MULTISITE == true) {
$themes = get_allowed_themes();
} else {
$themes = get_themes();
}
// Handle sorting
function usort_reorder($a,$b) {
$orderby = (!empty($_REQUEST['orderby'])) ? $_REQUEST['orderby'] : 'Title';
$order = (!empty($_REQUEST['order'])) ? $_REQUEST['order'] : 'asc';
$result = strcmp($a[$orderby], $b[$orderby]);
return ($order === 'asc') ? $result : -$result;
}
usort($themes, 'usort_reorder');
//MAIN STUFF HERE
//for ($i = 0; i < count($themes); $i++) {
//}
// Figure out the current page and how many items there are
$current_page = $this->get_pagenum();
$total_items = count($themes);
// Only show the current page
$themes = array_slice($themes,(($current_page-1)*$per_page),$per_page);
// Display sorted data
$this->items = $themes;
// Register pagination options
$this->set_pagination_args( array(
'total_items' => $total_items,
'per_page' => $per_page,
'total_pages' => ceil($total_items/$per_page)
));
}
}
Problem is, I can't get it to save properly. I select the rows I want, hit save and it just resets.
I assume you are talking about the checkboxes in your table listing, so this will be how to process bulk actions.
All you need to do is add two new methods to your class and initialize it in the prepare_items method. I use the code below in one of my plugins to delete or export, but you can just as easily run an update.
/**
* Define our bulk actions
*
* #since 1.2
* #returns array() $actions Bulk actions
*/
function get_bulk_actions() {
$actions = array(
'delete' => __( 'Delete' , 'visual-form-builder'),
'export-all' => __( 'Export All' , 'visual-form-builder'),
'export-selected' => __( 'Export Selected' , 'visual-form-builder')
);
return $actions;
}
/**
* Process our bulk actions
*
* #since 1.2
*/
function process_bulk_action() {
$entry_id = ( is_array( $_REQUEST['entry'] ) ) ? $_REQUEST['entry'] : array( $_REQUEST['entry'] );
if ( 'delete' === $this->current_action() ) {
global $wpdb;
foreach ( $entry_id as $id ) {
$id = absint( $id );
$wpdb->query( "DELETE FROM $this->entries_table_name WHERE entries_id = $id" );
}
}
}
Now, call this method inside prepare_items() like so:
function prepare_items() {
//Do other stuff in here
/* Handle our bulk actions */
$this->process_bulk_action();
}
There's a fantastic helper plugin called Custom List Table Example that makes figuring out the WP_List_Table class much easier.

Resources