About using wordpress esc_html__ - wordpress

using the esc_html__ function was tiring to write text domain all the time: D so I created a function as below.
The problem is I can get the following word but it doesn't save to .pot file. If I make a direct definition of esc_html__ in the function, it works but when I use variables for dynamics, what is the reason?
// Working
function lsph_lang(){
return esc_html__( "Hello", 'lsph' );
}
lsph_lang();
// Not working.
function lsph_lang( $str ){
return esc_html__( $str, 'lsph' );
}
lsph_lang( "hello" );

Just giving you my 2cents about this translation stuff, either you are patient and keep writing the full form like this:
esc_html__( "Hello", 'lsph' )
Or you "hack it" by making that your "lsph_lang" internally generates a .php temp file which contains ALL the possible variant of your translations stuff. Doing that will ensure that tools that read the translations stuff will work as expected and you can stop writing the full form

Related

Wordpress function cannot call submit_button() as it ends with "undefinied function"

i am a real very newbie in coding and in Wordpress. Trying my first test plugin to understand basics. I am able to define plugin, register it, so I can see it in plugins, activate it.
My later goal is to be able to create custom form, save user-specific data to new DB table, and then enable reading/editing it.
I tried to follow the instructions from gmazzap placed here: https://wordpress.stackexchange.com/questions/113936/simple-form-that-saves-to-database
I just am having following error from WP in time of trying to display preview of new screen having a shortcode [userform] in it:
*Fatal error: Uncaught Error: Call to undefined function submit_button() in /data/web/virtuals/131178/virtual/www/subdom/test/system/wp-content/themes/twentytwentythree-child/functions.php:14
*
My functions.php of my theme now looks like this:
<?php
add_action('init', function() {
add_shortcode('userform', 'print_user_form');
});
function print_user_form() {
echo '<form method="POST">';
wp_nonce_field('user_info', 'user_info_nonce', true, true);
?>
All your form inputs (name, email, phone) goes here.
<?php
submit_button('Send Data');
echo '</form>';
}
add_action('template_redirect', function() {
if ( ( is_single() || is_page() ) &&
isset($_POST['user_info_nonce']) &&
wp_verify_nonce($_POST['user_info_nonce'], 'user_info')
) {
// you should do the validation before save data in db.
// I will not write the validation function, is out of scope of this answer
$pass_validation = validate_user_data($_POST);
if ( $pass_validation ) {
$data = array(
'name' => $_POST['name'],
'email' => $_POST['email'],
'phone' => $_POST['phone'],
);
global $wpdb;
// if you have followed my suggestion to name your table using wordpress prefix
$table_name = $wpdb->prefix . 'my_custom_table';
// next line will insert the data
$wpdb->insert($table_name, $data, '%s');
// if you want to retrieve the ID value for the just inserted row use
$rowid = $wpdb->insert_id;
// after we insert we have to redirect user
// I sugest you to cretae another page and title it "Thank You"
// if you do so:
$redirect_page = get_page_by_title('Thank You') ? : get_queried_object();
// previous line if page titled 'Thank You' is not found set the current page
// as the redirection page. Next line get the url of redirect page:
$redirect_url = get_permalink( $redirect_page );
// now redirect
wp_safe_redirect( $redirect_url );
// and stop php
exit();
}
}
});
Note: I have not got to DB exercise, point of my question is submit_button.
As indicated in the error, the code on line 1 points to non identified function:
submit_button('Send Data');
I understood from other discussions submit_button should be core function of WP, so I should be able to call it "directly", without the need of a definition.
I tried following:
originally had very similar code within the plugin, moved to functions.php
reinstalled core of WordPress version 6.1.1
tried several different Themes (as it looked this worked for other users, I tried "classic" and "twentytwentythree" )
And still no little step further, still having same issue with error described above. What I am doing wrong?
If someone would confirm this is WP core installation issue, I am ready to reinstall WP from scratch, just trying to save some time, if there might be other cause.
Thank you for any suggestions.

Populate Image & Image List Fields with Bolt CMS Programatically

I am attempting to create entries programaticaly in Bolt 4. I have managed to create basic text entries fine which covers the majority of fields I need to fill in however unsure how to go about image and image list types.
$content->setFieldValue('name', 'Test Name');
Works fine for most fields as stated but images field types looks like below in database and am unsure what the "Bolt / Symfony / Doctrine" way of generating below is:
{"media":11,"filename":"entity\/year\/month\/image.jpg","alt":"","0":""}
Which looks like some JSON formatted to contain a media ID, file path and an alt attribute. I'm guessing image lists are similar but with multiple of above but hoping there is a function I can use to generate this output as unsure how I would grab media ID etc.
Am assuming I may need to upload a file temporarily from an external URL and provide this to some function however cannot find any examples. Any help would be much appreciated.
Not quite sure on this but will answer anyway as it works and may help someone else, but would be good to clear some of the bits up.
Example of an Image:
//not sure what goes in media here but blank seemed to not work here but a 7 did as looked at example in database however worried this is wrong and should be an Id
$image = array('media' => '7', 'filename' => $filename, 'alt' => $image['Alt'], '0' => '');
$imageJSON = json_encode($image);
$content->setFieldValue('image', $image);
Example of an Image List:
$images = array();
foreach ($images as $image) {
$ImageId = $image['id'];
//images may be already on system but I had to download them here
if ($fileName = $this->downloadImage($propertyFile->{'url'}->__toString(), $ImageId)) {
//not sure what goes in media here but seemed to work blank for imagelist type and unsure what the 0 is on the end either
$image[] = array('media' => '', 'filename' => $filename, 'alt' => $image['Alt'], '0' => ''); }
}
$imageJSON = json_encode($image);
$content->setFieldValue('gallery', $image);

Headless Wordpress, Is there a way to access data in wp_options table as REST endpoint?

Wordpress has an awesome REST API interface.
https://developer.wordpress.org/rest-api/reference/
But the content in wp_options table seems to be missing REST support. Is there a way to access the content in wp_otions table as REST endpoint via plugins?. Thanks.
There is the settings endpoint, but it only contains a surprisingly limited amount of them it seems.
This is something you could very easily do yourself though. I'm not sure if any plugins do it, but I also wouldn't recommend a plugin for something that can be done with less than 20 lines of code.
You just need to register a route using register_rest_route() on the rest_api_init hook, and pass it a callback function. You can drop code like this in your functions.php file or create a Must Use Plugin and drop the code in there, either way.
add_action( 'rest_api_init', function () {
register_rest_route( 'my-custom-route/v1', '/opt/', array(
'methods' => 'GET',
'callback' => 'get_rest_option',
//'permission_callback' => function () {
// return current_user_can( 'administrator' );
//}
) );
} );
function get_rest_option( $data ) {
return get_option( $data['option_name'] );
}
The above will give you access to whatever option you want by accessing:
/wp-json/my-custom-route/v1/opt/?option_name=siteurl
I went ahead and dropped an example on a site of mine:
https://xhynk.com/content-mask/wp-json/my-custom-route/v1/opt/?option_name=blogname
https://xhynk.com/content-mask/wp-json/my-custom-route/v1/opt/?option_name=siteurl
However, this will potentially expose anything in your options table. I went ahead and commented out the permission_callback so that any person, signed in or not, can access it. However, I also added a check like this:
function get_rest_option( $data ) {
if( $data['option_name'] === 'siteurl' || $data['option_name'] === 'blogname' ){
return get_option( $data['option_name'] );
} else {
return 'Unauthorized. Use `siteurl` or `blogname`';
}
}
You can see that home will fail: https://xhynk.com/content-mask/wp-json/my-custom-route/v1/opt/?option_name=home
I would recommend adding in a valid array of options, or using the permission_callback in order to lock it down a bit. You could even have an access key instead, and keep that key secret. Either way, be aware of the security implications of exposing your entire wp_options table, and take some sort of preventative measure!

Get localized string for specific locale

How can I use the localization mechanism in WordPress to get access to an existing but not-current language string?
Background: I have a custom theme where I use locale 'en_US' as the default locale and translate through a PO file to locale 'es_ES' (Spanish).
Let us say I use the construction
__('Introduction', 'my_domain');
in my code, and that I have translated 'Introduction' to the Spanish 'Introducción´ in my PO file. All this works fine.
Now to the problem: I want to insert n records in my database with all existing translations of the string 'Introduction' - one for each language; so, n = 2 in my example.
Ideally, I would write something like this:
$site_id = 123;
// Get an array of all defined locales: ['en_US', 'es_ES']
$locales = util::get_all_locales();
// Add one new record in table details for each locale with the translated target string
foreach ($locales as $locale) {
db::insert_details($site_id, 'intro',
__('Introduction', 'my_domain', $locale), $locale);
}
Only, that the 3rd parameter in __() above is pure fantasy on my part. You can only validly write
__('Introduction', 'my_domain');
to get either 'Introduction' or 'Introducción' depending on the current locale.
The outcome of the code above would ideally be that I end up with two records in my table:
SITE_ID CAT TEXT LOCALE
123 intro Introduction en_US
123 intro Introducción es_ES
I am aware that I want something that requires loading all the MO files, where normally, only the MO file for the current language is required. Maybe use of the WordPress function load_textdomain is necessary - I was just hoping there already exists a solution.
Expanding on the question by including the plugin PolyLang: is it possible to use Custom Strings to achieve the above functionality? E.g. conceptually:
pll_('Introduction', $locale)
Old question I know, but here goes -
Starting with a simple example where you know exactly what locales to load and exactly where the MO files are, you could use the MO loader directly:
<?php
$locales = array( 'en_US', 'es_ES' );
foreach( $locales as $tmp_locale ){
$mo = new MO;
$mofile = get_template_directory().'/languages/'.$tmp_locale.'.mo';
$mo->import_from_file( $mofile );
// get what you need directly
$translation = $mo->translate('Introduction');
}
This assumes your MO files are all under the theme. If you wanted to put more of this logic through the WordPress's environment you could, but it's a bit nasty. Example:
<?php
global $locale;
// pull list of installed language codes
$locales = get_available_languages();
$locales[] = 'en_US';
// we need to know the Text Domain and path of what we're translating
$domain = 'my_domain';
$mopath = get_template_directory() . '/languages';
// iterate over locales, finally restoring the original en_US
foreach( $locales as $switch_locale ){
// hack the global locale variable (better to use a filter though)
$locale = $switch_locale;
// critical to unload domain before loading another
unload_textdomain( $domain );
// call the domain loader - here using the specific theme utility
load_theme_textdomain( $domain, $mopath );
// Use translation functions as normal
$translation = __('Introduction', $domain );
}
This method is nastier because it hacks globals and requires restoring your original locale afterwards, but it has the advantage of using WordPress's internal logic for loading your theme's translations. That would be useful if they were in different locations, or if their locations were subject to filters.
I also used get_available_languages in this example, but note that you'll need the core language packs to be installed for this. It won't pick up Spanish in your theme unless you've also installed the core Spanish files.

WP Settings API save to multiple options

In the Wordpress Settings API, creating a new options page usually starts out with
register_setting('sample_options', 'my_option');
add_settings_section('section', 'Sample Options', 'callback1', 'page');
add_settings_field('name', 'Label', 'callback2', 'page', 'section');
In this simplified example, the data gets saved in the option my_option making the value of name accessible through
$option = get_option('my_option');
$name = $option['name']; // Got it
But what if the value of the name field is there not to place a new value but to update an already existing option that's not my_option like for example this_other_option? I guess what I'm really looking for is is it possible for one field to save to multiple options (my_option and this_other_option) while using the Settings API?
I suppose you could use a callback in register_setting. It would look something like the following:
<?php
register_setting('sample_options', 'my_option', 'my_sanitize_callback');
function my_sanitize_callback($value, $option) {
$value = mysql_real_escape_string($value);
update_option('my_other_option', $value);
return $value;
}
?>
You may have to tweak that a bit. I haven't tested it.

Resources