php: having difficulty implementing rtrim() - trim

I've looked at several examples of the implementation of rtrim(), and I'm not able to implement it in my particular case.
Here's what I tried:
if ( $memberRoles = xprofile_get_field_data( 'AD Roles', bp_get_member_user_id() ) ) :
foreach ( $memberRoles as $memberRoles ) {
echo '<div class="roles"><h5>';
echo $memberRoles;
echo ',&nbsp</h5></div>';
}
endif;
$memberRoles = rtrim($memberRoles, ",");
I'm still very nascent when it comes to writing code, and even more so when it comes to php. Any help or advice is greatly, greatly appreciated. Thank you!

Related

Retun 1 when requiring a files on wordpress

I just want to ask a simple but really bugging problem, let's get tot the point
Why when I writing a require in an add_filter() it returning unwanted 1 integer in the end of the text? This is the code
function satufu_template( $satufu_content ){
if ( is_singular( 'satufu_projects' ) ){
$located = locate_template('satufu-template.php');
if ( !empty($located) ){
} else {
echo require plugin_dir_path(__FILE__) . 'template.php';
}
} else {
return $satufu_content;
}
}
add_filter('the_content','satufu_template');
This is the template file that I am requiring
typo<?php
echo $satufu_content;
this is the output
test
//SomeMyAwesomeContent
1
this is the output with var_dump() wrapper
test
//SomeMyAwesomeContent
int(1)
This is a simple 1 integer that ruin my life (well, I tried 2 days just for debugging this until I give up.
So thank you for the attention and really hope this awesome forum gonna kill this tiny bug :)
You don't have to use echo when you use require.
Simply change:
echo require plugin_dir_path(__FILE__) . 'template.php';
to:
require plugin_dir_path(__FILE__) . 'template.php';
Currently the "1" appears because you are echo-ing the result of the require, which is successful
(1 - true, 0 = false).
Refference: http://php.net/manual/en/function.require.php

Wrap the code to translate with wordpress/poedit?

Current I have WP code like this. I need to make it translateable by poedit. How do I wrap the code to make it work? Im not sure which method is use for this case. Some thing like:
<?php my_e( 'Total sales' ); ?> or __('Total sales', 'my')
This is the code. I need to translate ["Sales amount"], ["Number of sales"]
foreach ($results as $result) {
$date = $result->formatted_post_date;
$statistics[$date]["Sales amount"] += $wp_list_table->column_total_sales($result->ID);
$statistics[$date]["Number of sales"]++;
$statistics[$date]["date"] = $date;
$max_number_of_sales = max(array($max_number_of_sales,$statistics[$date]["Number of sales"] )); }
Thank you for help
You have to use __('string','textdomain') to assign a translated string to some variable. And _e('string','textdomain') to echo a translated string. See I18n_for_WordPress_Developers.
Two observations:
you'll not be able to translate array keys, see php.net/manual/en/language.types.array.php
what you're doing seems wrong. I'd do it like:
$sales_amount = 0;
$sales_number = 0;
foreach ($results as $result) {
$sales_amount += $wp_list_table->column_total_sales($result->ID);
$sales_number++;
$date = $result->formatted_post_date;
$statistics[$date]["sales_amount"] = $sales_amount;
$statistics[$date]["sales_number"] = $sales_number;
}
echo __( 'Sales Amount', 'my' ) . $sales_amount;

Parse Error escape PHP inside Jquery and PHP [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
Parse error: syntax error, unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in ...
This is the error that I'm getting
<?php
function my_custom_js() {
echo " <script>" ;
echo " jQuery(document).ready(function(){
jQuery('#secondary-front .first h3').addClass('
<?php $options = get_option('mytheme_theme_options');
if(!empty($options['first_widget_icon'])) echo $options['first_widget_icon']?> ');
jQuery('#secondary-front .second h3').addClass('<?php $options = get_option('mytheme_theme_options');
if (!empty($options['second_widget_icon'])) echo $options['second_widget_icon'];?>');
jQuery('#secondary-front .third h3').addClass('<?php $options = get_option('mytheme_theme_options');
if (!empty($options['third_widget_icon'])) echo $options['third_widget_icon'];?>');
});
";
echo "</script> ";
}
add_action('wp_head', 'my_custom_js');
?>
I cannot get this code to escape correctly, i have php > jquery > php
The problem is your quotes (") don't weigh up on both sides. That said, when I've gone to investigate the problem, I've noticed worse things with your code, so I've rewritten it entirely for you:
<?php
function my_custom_js() {
$options = get_option('mytheme_theme_options');
echo "<script>
jQuery(document).ready(function(){
jQuery('#secondary-front .first h3').addClass('" . ($options['first_widget_icon'] ?: NULL) . "');
jQuery('#secondary-front .second h3').addClass('" . ($options['second_widget_icon'] ?: NULL) . "');
jQuery('#secondary-front .third h3').addClass('" . ($options['third_widget_icon'] ?: NULL) . "');
});
</script>";
}
add_action('wp_head', 'my_custom_js');
?>
One thing I've done is moved $options = get_option('mytheme_theme_options'); to the top. I've also removed the repeated calls to this. Also, that's had the knock-on effect that the echo can be made all in 1 statement, with clever use of the ternary operator.
echo ($something ?: NULL); means if $something exists, echo it, else echo nothing.
Using the ternary operator with the ?: shorthand requires PHP >= 5.3.0
For versions below this, simply fill in the middle part, i.e.:
// PHP >= 5.3.0
($options['first_widget_icon'] ?: NULL)
// PHP < 5.3.0
($options['first_widget_icon'] ? $options['first_widget_icon'] : NULL)
Of course, the code might need tweaking to your liking, but it should be a basis for improvement.

get_categories order by meta key issue?

I'm trying to search for a way to order categories by meta value. From what I read, it seems like I can use:
get_categories('child_of=92&hide_empty=false&orderby=meta_value&meta_key=date&order=ASC');
However, this does not work at all, the categories are still not in the order I want. I wonder how I can:
correct this to make it work
print out the sql to see what is really going on inside?
Thank you very much in advance.
First of all, I must mention that I'm using the module custom category fields, and second of all I'm a complete WP newbie
Anyhow, after learning that this cannot be done by default, I looked into the get_categories functions and finally came up with a solution
function category_custom_field_get_terms_orderby( $orderby, $args ){
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
return 'cv.field_value';
return $orderby;
}
function category_custom_field_get_terms_fields( $selects, $args ){
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
$selects[] = 'cv.*';
return $selects;
}
function category_custom_field_terms_clauses($pieces, $taxonomies, $args){
global $wpdb;
if($args['orderby'] == 'category_custom_field' && isset($args['category_custom_field']))
$pieces['join'] .= " LEFT JOIN $wpdb->prefix" . "ccf_Value cv ON cv.term_id = tt.term_id AND cv.field_name = '".$args['category_custom_field']."'";
return $pieces;
}
add_filter('get_terms_orderby', 'category_custom_field_get_terms_orderby',1,2);
add_filter('get_terms_fields', 'category_custom_field_get_terms_fields',1,2);
add_filter('terms_clauses', 'category_custom_field_terms_clauses',1,3);
(The code above can be put into the theme functions.php file)
then the code to get categories is:
get_categories('child_of=92&hide_empty=false&orderby=category_custom_field&category_custom_field=date&order=DESC');
Any correction is greatly appreciated!
You can also give the get_categories new meta and sort using usort.
$subcategories = get_categories();
foreach ($subcategories as $subcategory) {
$subcategory->your_meta_key = your_meta_value;
}
foreach ($subcategories as $subcategory) {
blah blah blah
}
function my_cmp($a, $b) {
if ($a->ordering == $b->ordering) {
return 0;
}
return ($a->ordering < $b->ordering) ? -1 : 1;
}
usort($subcategories, "my_cmp");

Drupal module_invoke() and i18n

I am tasked with i18n-ing our current CMS setup in Drupal.
The problem that I am facing is with use of module_invoke() to place blocks within nodes.
I have managed to string translate blocks, and that is working when a block is placed in a region (block content is successfully translated) using the UI.
However, when a block is injected into a node like such:
$block = module_invoke('block', 'block', 'view', 22); print $block['content'];
It is not getting translated, or even worse, not showing at all.
I have also tried this variation using t(). e.g.:
$block = module_invoke('block', 'block', 'view', 22); print t($block['content']);
to no avail.
Generally speaking I've having a bit of trouble with blocks for i18n. Does anyone have a recommended approach for dealing with blocks in drupal with regards to translating them? I would prefer not to create different blocks for each language.
So .. After digging around in the bowels of Drupal - and much hair pulling .. I've come up with an almost decent solution.
Basically, with this function, I can extract a translated version of a block:
function render_i18n_block($block_id, $region = "hidden"){
if ($list = block_list($region)) {
foreach ($list as $key => $block) {
// $key == <i>module</i>_<i>delta</i>
$key_str = "block_".$block_id;
if ($key_str == $key){
return theme('block', $block);
}
}
}
}
Then, in my node, I simple call:
<?php echo render_i18n_block(<block_id>,<region>); ?>
There can be some issues where your blocks might not be displaying in a region (and therefore you can't pass a region into block_list). For this case, I simply created a region called "hidden" which is not rendered anywhere in my template, but can be used to call block_list.
Finally (and this is the part that I still need to find a good solution for), I discovered that block_list() in: includes/blocks/block.inc has a bit of an issue.
It appears that $theme_key is not reliably set unless block_list() is being called from the theme() function (in includes/themes.inc) .. this causes the SQL to return an empty results set. The SQL looks like this:
$result = db_query(db_rewrite_sql("SELECT DISTINCT b.* FROM {blocks} b LEFT JOIN {blocks_roles} r ON b.module = r.module AND b.delta = r.delta WHERE b.theme = '%s' AND b.status = 1 AND (r.rid IN (". db_placeholders($rids) .") OR r.rid IS NULL) ORDER BY b.region, b.weight, b.module", 'b', 'bid'), array_merge(array($theme_key), $rids));
As you can see, if theme_key is not set, then it will just return an empty result.
For now I am bypassing this by simply adding:
if (!isset($theme_key)){$theme_key="<my_theme_name>";}
in modules/blocks/block.inc::block_list() around line 429 .. I still need to work out a better way to do this.
10 for anyone with suggestions on how I could ensure that $theme_key is set before calling block_list :)
I had exactly the same problem as you, since I was using
$block = module_invoke('block', 'block_view', 'block_id');
print render($block['content']);
to inject the block into my nodes. However, looking up module_invoke in the Drupal reference, I found a comment titled "to render blocks in Drupal 7 better to use Block API", with this code:
function block_render($module, $block_id) {
$block = block_load($module, $block_id);
$block_content = _block_render_blocks(array($block));
$build = _block_get_renderable_array($block_content);
$block_rendered = drupal_render($build);
return $block_rendered;
}
I just un-functioned it to use directly, like so:
$block = block_load('block', 'block_id');
$block_content = _block_render_blocks(array($block));
$build = _block_get_renderable_array($block_content);
print render($build);
And for me it works like a charm. Be aware however that this method prints the block title as well, so maybe you'll want to set it to 'none' in the original language.
Create a function like this
<?php
function stg_allcontent2($allC, $level
= "1") {
global $language; $lang = $language->language;
foreach ($allC as $acKey => $ac) {
if($ac['link']['options']['langcode']
== $lang){ if ($level == "1")
$toR .= "";
if (is_array($ac['below']))
$class="expanded"; else
$class="leaf";
$toR .= "<li class=\"".$class."\">" . l($ac['link']['link_title'], $ac['link']['link_path']) . "</li>";
if ($level != "1") $toR .= ""; if (is_array($ac['below'])) $toR .= "<ul class=\"menu\">".stg_allcontent2($ac['below'], "2")."</ul>"; if ($level == "1") $toR .= ""; }
}
return $toR; } ?>
call like this
<?php echo '<ul class="menu">'; echo stg_allcontent2(menu_tree_all_data($menu_name
= 'menu-header', $item = NULL)); echo '</ul>'; ?>
This may help you: http://drupal-translation.com/content/translating-block-contents#
UPDATE: the t() function allows you to pass in the language code to use.

Resources