Pluralize text in function - php

I'm looking to be able to pluralize "Slide" in the below function:
// Changes the default download button text
function ps_download_button($args) {
$download_text = 'Download ' . '(' . get_field('no_slides') . ' Slide)';
$args['text'] = $download_text;
return $args;
}
add_filter( 'edd_purchase_link_args', 'ps_download_button' );
This is my first stab at writing custom PHP functions. I've managed to find related code but I'm not sure how to integrate it with the above:
function plural( $amount, $singular = '', $plural = 's' ) {
if ( $amount === 1 ) {
return $singular;
}
return $plural;
}

Well you can use ternary for that.
function ps_download_button($args) {
$amount = intval(get_field('no_slides'));
$download_text = 'Download ' . '(' . $amount . ') Slide'. (($amount>1)?'s':'');
$args['text'] = $download_text;
return $args;
}
That's the simplest way, and no need for a function. If you don't understand how ternary works, take a look at this question.

Related

TYPO3 8.7.13 - MariaDB QueryBuilder FULLTEXT

SELECT name
FROM tx_snippethighlightsyntax_domain_model_snippets
WHERE (MATCH(name, description, code, comment) AGAINST ('css'));
This query works in phpMyAdmin with MariaDB. Now my "problem" is to adapt this in TYPO3 with QueryBuilder. I don't see any MATCH or AGAINST operator.
So far, my function start with this:
private $tx = 'tx_snippethighlightsyntax_domain_model_snippets';
public function ftsSearch()
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$ftsQueryBuilder = $connectionPool->getQueryBuilderForTable($this->tx);
$fts = $ftsQueryBuilder
->select($this->tx . '.name')
->from($this->tx)
->where($ftsQueryBuilder->expr()->eq(
MAGIC HAPPENS HERE ?
)
->execute()
->fetchAll();
return $fts;
}
The extension Indexed Search in the TYPO3 core uses MATCH and AGAINST in queries.
The following code taken from IndexSearchRepository should help you building up your query
$searchBoolean = '';
if ($searchData['searchBoolean']) {
$searchBoolean = ' IN BOOLEAN MODE';
}
$queryBuilder->andWhere(
'MATCH (' . $queryBuilder->quoteIdentifier($searchData['fulltextIndex']) . ')'
. ' AGAINST (' . $queryBuilder->createNamedParameter($searchData['searchString'])
. $searchBoolean
. ')'
);
private $tx = 'tx_snippethighlightsyntax_domain_model_snippets';
public function ftsSearch()
{
$connectionPool = GeneralUtility::makeInstance(ConnectionPool::class);
$ftsQueryBuilder = $connectionPool->getQueryBuilderForTable($this->tx);
$fts = $ftsQueryBuilder
->select($this->tx . '.name')
->from($this->tx)
->where('MATCH('
. $this->tx .'.name,'
. $this->tx .'.description,'
. $this->tx .'.code,'
. $this->tx .'.comment)'
. ' AGAINST(' . $ftsQueryBuilder->createNamedParameter('put_search_here')
. ')')
->execute()
->fetchAll();
return $fts;
}
This one works for me. Thank you !

Magento Sales/Order/Grid change color depending on status

I am overriding on my module the sales grid to get different reports and i was trying to set a different color if order status is "complete" etc.
Here is my approach , it is not giving errors but doesn't seem to work.
class Mycustom_Salesorderitemgrid_Block_Adminhtml_Order_Items_Grid_Renderer_Order
extends Mage_Adminhtml_Block_Widget_Grid_Column_Renderer_Abstract
{
public function render(Varien_Object $row)
{
$value = $row->getData($this->getColumn()->getIndex());
$html ='<a href="' . $this->getUrl('adminhtml/sales_order/view', array('order_id' => $row->getData('order_id'), 'key' => $this->getCacheKey())) . '" target="_blank" title="' . $value . '" >' . $row->getData($this->getColumn()->getIndex()) . '</a>';
return $html;
// here i am trying to add the color to mass status, after finding solution i will add seperate colors based on status
$truncateLength = 255;
// stringLength() is for legacy purposes
if ($this->getColumn()->getStringLimit()) {
$truncateLength = $this->getColumn()->getStringLimit();
}
if ($this->getColumn()->getTruncate()) {
$truncateLength = $this->getColumn()->getTruncate();
}
$text = Mage::helper('core/string')->truncate(parent::_getValue($row), $truncateLength);
if ($this->getColumn()->getEscape()) {
$text = $this->escapeHtml($text);
}
if ($this->getColumn()->getNl2br()) {
$text = nl2br($text);
}
if ($this->getColumn()->getStatusLabel() == array('processing', 'waiting', 'pending', 'almost', 'telephone')) {
$yesterday = strtotime("-24 hours", Mage::getModel('core/date')->gmtTimestamp());
$yesterday = Mage::getModel('core/date')->date(null, $yesterday);
if ($row->getCreatedAt() > $yesterday) {
$text = '<span style="color: red !important; font-weight: bold;">' . $text . '</span>';
};
}
return $text;
}
}
You need to add the method below to your Mage_Adminhtml_Block_Sales_Order_Grid class (or to the class which overrides it):
public function getRowClass($order)
{
if ($order->getStatus() == 'canceled') {
return 'red-row';
}
}
This code will add class="red-row" for every row where the order status is "canceled".
Hope that this will help

Insert PHP code In WordPress Page and Post

I want to know the visitor country using PHP and display it in on a WordPress Page. But when I add PHP code to a WordPress page or post it gives me an error.
How can we add PHP code on WordPress pages and posts?
<?PHP
try
{
function visitor_country()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
$result = "Unknown";
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
$ip_data = #json_decode(file_get_contents("http://www.geoplugin.net/json.gp?ip=" . $ip));
if($ip_data && $ip_data->geoplugin_countryName != null)
{
$result = array('ip' => $ip,
'continentCode' => $ip_data->geoplugin_continentCode,
'countryCode' => $ip_data->geoplugin_countryCode,
'countryName' => $ip_data->geoplugin_countryName,
);
}
return $result;
}
$visitor_details = visitor_country(); // Output Country name [Ex: United States]
$country = $visitor_details['countryName'];
WordPress does not execute PHP in post/page content by default unless it has a shortcode.
The quickest and easiest way to do this is to use a plugin that allows you to run PHP embedded in post content.
There are two other "quick and easy" ways to accomplish it without a plugin:
Make it a shortcode (put it in functions.php and have it echo the country name) which is very easy - see here: Shortcode API at WP Codex
Put it in a template file - make a custom template for that page based on your default page template and add the PHP into the template file rather than the post content: Custom Page Templates
You can't use PHP in the WordPress back-end Page editor. Maybe with a plugin you can, but not out of the box.
The easiest solution for this is creating a shortcode. Then you can use something like this
function input_func( $atts ) {
extract( shortcode_atts( array(
'type' => 'text',
'name' => '',
), $atts ) );
return '<input name="' . $name . '" id="' . $name . '" value="' . (isset($_GET\['from'\]) && $_GET\['from'\] ? $_GET\['from'\] : '') . '" type="' . $type . '" />';
}
add_shortcode( 'input', 'input_func' );
See the Shortcode_API.
Description:
there are 3 steps to run PHP code inside post or page.
In functions.php file (in your theme) add new function
In functions.php file (in your theme) register new shortcode which call your function:
add_shortcode( 'SHORCODE_NAME', 'FUNCTION_NAME' );
use your new shortcode
Example #1: just display text.
In functions:
function simple_function_1() {
return "Hello World!";
}
add_shortcode( 'own_shortcode1', 'simple_function_1' );
In post/page:
[own_shortcode1]
Effect:
Hello World!
Example #2: use for loop.
In functions:
function simple_function_2() {
$output = "";
for ($number = 1; $number < 10; $number++) {
// Append numbers to the string
$output .= "$number<br>";
}
return "$output";
}
add_shortcode( 'own_shortcode2', 'simple_function_2' );
In post/page:
[own_shortcode2]
Effect:
1
2
3
4
5
6
7
8
9
Example #3: use shortcode with arguments
In functions:
function simple_function_3($name) {
return "Hello $name";
}
add_shortcode( 'own_shortcode3', 'simple_function_3' );
In post/page:
[own_shortcode3 name="John"]
Effect:
Hello John
Example #3 - without passing arguments
In post/page:
[own_shortcode3]
Effect:
Hello
When I was trying to accomplish something very similar, I ended up doing something along these lines:
wp-content/themes/resources/functions.php
add_action('init', 'my_php_function');
function my_php_function() {
if (stripos($_SERVER['REQUEST_URI'], 'page-with-custom-php') !== false) {
// add desired php code here
}
}

php Object of class Closure could not be converted to string

I'm creating a search-function for my PHP-based file manager. I'm getting this error: 'Catchable fatal error: Object of class Closure could not be converted to string' on the following line:
if ($data->input_ext)
{
$data_ext = ($begun ? ($data->input_logic ? ' OR ' : ' AND ') :
function ()
{
$begun = true;
return "";
}) . 'ext = "' . $data->input_ext . '"';
$data_string.= $data_ext;
}
That's part of what builds the SQL query. $begun_files simply determines whether or not to put 'OR' or 'AND' at the beginning based on whether or not the user input a name or anything that comes before this to match. I have a feeling that I'm not allowed to include anonymous functions in ternary expressions but what should I do instead?
Thanks!
You can't use anonymous functions for inline flow control; just use a regular if statement and don't shun writing things on multiple lines:
if ($data->input_size) {
if ($begun_files) {
$str .= $data->input_logic ? ' OR ' : ' AND ';
$begun_files = true;
}
$str .= sprintf('size %s "%f"',
$data->input_size_op ? '<=' : '>=',
$data->input_size * pow(1024,$data->input_size_unit)
);
}
Building off of the previous answer I ended up going with this:
if ($data->input_ext) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_ext = $logic.'ext = "'.$data->input_ext.'"'; $data_string .= $data_ext;
}
if ($data->input_size) {
if ($begun) { $logic = $data->input_logic ? ' OR ' : ' AND '; } else { $logic = ""; $begun = true; }
$data_size = $logic.'size '.($data->input_size_op ? '<=' : '>=').' '.($data->input_size * pow(1024,$data->input_size_unit)); $data_string .= $data_size;
}
Thanks!

How to use array in function to get only value I want

I am trying to work this function in wordpress theme the way where I can get value only what I want and not all to gather. I am not much familiar with using array in function so I need you expert help to make it works and I would really appreciate that.
Here is my code
function gallery_artist($arg=null, $arg2=null, $arg3=null){
global $png_gallery_meta;
$png_gallery_meta->the_meta();
$gallery = get_post_meta(get_the_ID(), $png_gallery_meta->get_the_id(), TRUE);
$gallery_value = $gallery['image_artist'];
$artist_info = $gallery_value;
$string = $artist_info;
$artist = substr($string, 0, stripos($string, "/") );
// getting first name and last name from user id
$author_first_name = get_userdata(basename($string))->first_name;
$author_last_name = get_userdata(basename($string))->last_name;
$author_full_name = $author_first_name . ' ' . $author_last_name;
$user_id = '<a href=" ' . get_author_posts_url(basename($string)) . ' " title="more submissions of ' . $author_first_name .' '. $author_last_name . ' " >' . $artist . '</a>';
$arg = $author_first_name;
echo $arg;
$arg2 = $author_last_name;
echo $arg2;
$arg3 = $user_id;
echo $arg3;
}
After than I want to use this function to get any value I want and not unnecessary to render all three to gather. Means if I want only first name than I pass value only for that and it will render only first name so on..
Here how I want to use something. but you can suggest any code and type of function I have no issue.
<?php call_user_func_array('gallery_artist', array('first_name','last_name','artist_id') ) ?>
Big Big thanks to you all..
Try replacing the bottom section with this:
if(!is_null($arg))
{
$arg = $author_first_name;
echo $arg;
}
if(!is_null($arg2))
{
$arg2 = $author_last_name;
echo $arg2;
}
if(!is_null($arg3))
{
$arg3 = $user_id;
echo $arg3;
}

Categories