WordPress SDL Translation for shortcodes - wordpress

I have some sort of sort of shortcodes like [wp-text text="Lorem Impsum etc" button_text="Read More"][/wp-text].
I want to extract this shortcode from post content field and then send these two attributes: text and button_text for translation to SDL World Server.
After getting response from SDL, I want to replace that shortcode accordingly.
Any Suggestion or Help?

Here is a suggestion about your approach:
Parse the shortcode attributes
Having the content you can parse the variable and extract all short code attributes with the provided Wordpress function shortcode_parse_atts
For each parsed value make a API call to the provided SDL World Server REST API (Or for better performance you can group all the translations and translate them with one complex API call if supported from the API)
After getting the response replace the original strings with the translated strings.
Here is example pseudo code in PHP:
$shotcode_attributes = shortcode_parse_atts( $post->post_content );
foreach ( $shortcode_attributes as $attribute => $value ) {
// Make SDL World Server API call refer to the API documentation for the exact way
$translated_value = $sdlApiClient->translate( $value );
// Replace the translated value.
// You can be more precise here ensuring that the value is inside the shortcode
$post->post_content = str_replace(
"{$attribute}=\"{$value}\"",
"{$attribute}=\"{$translated_value}\"",
$post->post_content
);
}
You can also research and examine the provided SDL WordPress Connector

Related

Specific filter for URL popover in post editor

I'm using WP 5.3 with the default (Gutenberg) editor along with the Polylang 2.7.2 plugin for making the site multilingual. Using Polylang, each post consists of one translation post per language (Polylang groups translation posts together).
Now I have the following problem: When a user is writing a post and tries to link to another already existing post, the search drop down for linking text (Ctrl+K) shows posts in all available languages. If the post title isn't language-specific (e.g., "Smart Home") but the "Smart Home" post exists in two languages, it's trial and error for the user to select the one matching the language of the currently edited post:
I wanted this URL popover drop down to either only list posts of the same language as the current post, or modifying the results in the drop down to show the specific language (by flag, or "[en]" before the title).
First, I tried using the admin menu bar "Filter content by language" drop down to limit it to English posts - didn't affect the drop down at all.
Next, I tried using a filter to tamper with the query results for this drop down. Using pre_get_posts and setting the language hard-coded to English worked:
add_filter('pre_get_posts', [self::class, 'filterQueryLanguage']);
}
public static function filterQueryLanguage($query) {
$query->set('lang', 'en'); // this limits the drop down results to English posts
return $query;
}
The search drop down then only listed English posts. Unfortunately, this limits all queries and it's impossible in the filter function to know for sure if this query originated from an AJAX request by this popover drop down.. also, I didn't manage to detect the language of the currently edited post (pll_current_language() returned false in this case).
Therefore, I need a way to post-filter the results only for this popover drop down and prepend the language to the post name in some way. But I have no idea if there even is a filter for this. get_posts doesn't seem to fire and even if it did, I don't want to affect all queries.
Are there any more specific filters for this purpose?
Okay, found a solution myself. The problem is: this URL popover does a REST API query for search=phrase. This search query also has a lang= argument that is already set to the appropriate post language - however, when assembling the REST response this lang argument is ignored.
I post-filtered the REST result like so:
add_filter('rest_pre_echo_response', [self::class, 'filterRESTResponse'], 10, 3);
}
public static function filterRESTResponse($result, $server, $request) {
$params = $request->get_params();
if (!empty($params['search']) && !empty($params['lang'])) {
$filtered = [];
$lang = $params['lang'];
foreach ($result as $post) {
$post_lang = pll_get_post_language($post['id']);
if ($post_lang === $lang) {
$filtered []= $post;
}
}
$result = $filtered;
}
return $result;
}
This solution is a bit awkward as it might've been possible to make the REST query respect the language from the start. Not sure how to hook into that one, tho.
Well, whatever works.

WordPress Unyson - Share page options

I'm using the unyson Framework for WordPress and currently using page options which work just fine on that particular page.
But I want to be able to access those options when on another page.
Here is my php -
$page = fw()->theme->get_options( 'service-settings' );
<?php echo wp_kses_post($page['service']['options']['service-box']['options']['description']; ?>
But this doesn't allow me the content from the array.
Using the following I can see the array, but cannot get the data.
fw_print($page);
Thanks guys
You're receiving just options array by calling fw()->theme->get_options('slug') - literally what you typed in the framework-customizations/theme/options/slug.php file.
If you want to receive the actual data you need to use DB helpers.
$data = fw_get_db_settings_option();
// or even refer to individual options, for performance's sake
$individual_option = fw_get_db_settings_option('option_id');
fw_print($data);
fw_print($individual_option);

Saving an array to Advanced Custom Fields WordPress

I'm using the ACF plugin for WordPress. I'm posting to a custom post type programmatically via my theme. Now, I thought I would be able to save an array of items to a custom field quite easily, but whenever I try to, nothing gets input. I simply get this error when I check the post screen in the admin area:
Warning: htmlspecialchars() expects parameter 1 to be string, array given in /home/lukeseag/public_html/spidr-wp/wp-content/plugins/advanced-custom-fields/core/fields/text.php on line 127
Now, I'm kind of throwing this out there for suggestions as to how I can go about solving this problem.
To give some context, I'm programmatically saving data input by a user, and creating a post with it. Much of the data is simple strings and numbers that can each have their own custom field.
But I have an unknown number of text strings and URL's (with an id number for each) coming through this page too, that need to be linked with the same post. I need to be able to output each set of text string and URL into their own div on the single.php post page. Now, ideally these text/url pairs would be saved in a single array so I can just loop through the array and output the data, but it looks like ACF doesn't want to let this happen?
Any suggestions as to how I can save this data and then output it easily on the single.php page? Each set of results will have an ID (number), text string and url.
Thanks!
This is exactly why all those "frameworks" are usually more pain than gain. they are designed to look flexible to the lazy but then they always prove useless on a real case scenario that is a bit more complex than anything that would actually be easily achieved without them.
Anyhow, as for your question.
The problem is that you are passing array instead of a string .
I am not going to go into debugging the plugin, and anyhow , more code and info is needed , so i will just give you ONE possible and easy solution, and that is to compose a pseudo-array string like so :
'ID|URL|STRING'
note that the delimiter pipe (|) is just an example, you could use ( , ) ( : ) ( # ) or whatever.
in other words :
$url = 'http://myurl.url/something';
$id = 35;
$string = 'my string';
$pseudo_r = $id . '|' . $url . '|' . $string . '|'; // results in 'ID|URL|STRING';
or you can use the implode() function
$pseudo_r = array(
"url" => $url,
"id" => $id ,
"string" => $string
);
$pseudo_r = implode("|", $pseudo_r); // gives a string
and pass it as a string that later on you can decompose it with explode() like so :
$pseudo_r = explode( '|', $pseudo_r ); // gives back the original array
( Please note that now the array is NON ASSOCIATIVE anymore . )
now, since you mentioned that each one of those is a set, you can compose the same pseudo array from the sets, using a different delimiter.
This might work for you , but essentially it is wrong .
why is it wrong ?
Because this is a generic and somewhat hackish solution that actually ignores your data type .
You are mixing 3 types of data types , URL , ID and a STRING .
All 3 ( should ) have potentially different validation schemes , and I suspect that the htmlspecialchars() part belong to the URL.
Another solution is just to find the right data field in the ACF settings or use a different field for each and then just DISPLAY it together , also using the implode() and explode() functions.
Yo can save the array using json_encode($your_array) and json_decode() to recover it. This works also for associative arrays.

Custom post types permalink with parent custom post type

Hard to define the Title of this Question....
I want to create a nice readable permalink structure for my 2 custom post types (CPT).
My first CPT "family" has the following rewrite-slug "family/%postname%" (all works fine)
The second CPT "childs" has a metabox where I can select the parent_id-field by choosing a CPT "family" where the child-CPT belongs to. That also works great.
Now I set the rewrite-slug for "childs" to "%parent_post_url%/child/%postname%" so that I can get the following URL "family/the-griffons/child/peter" . But when I call this URL wordpress displays a not-found-page. The crazy thing is that if I set the rewrite-slug hard to "family/the-griffons/child/%postname%" I can call the URL (both URLs are the same!!!)
So why toes WP throws an error when I try to get the URL dynamically but not when I hardcode the URL??
The child-parent relationship you think you have is not quite there. Based on what you've told us so far, it seems that all you have is a custom field denoting the "pseudo-parent" id. So what your question should really read is
How do I rewrite the first part of the cpt url, based on the cpt custom field value ?
because, as far as wordpress is concerned in your case, that's all that "parent id" really is- a custom field value.
you can try following the last part(Part 3.) of this tutorial, keeping in mind, that you'll want the actual path of the url of the "parent id" and not the cf "parent id" value itself, you'll have to implement something along the lines of:
$parent_id = get_post_meta($post_id, "your_cf_key_for_parent_id", true);
$full_parent_post_url = parse_url( get_permalink( $parent_id ) );
$parent_post_url = $full_parent_post_url['path'];
if(!$parent_post_url) { $parent_post_url = "default-fallback" }
$permalink = str_replace(‘%parent_post_url%’, $parent_post_url, $permalink);
return $permalink;
another relevant stackexchange answer:
using-custom-fields-in-custom-post-type-url
BUT as #c0ns0l3 mentioned using custom taxonomies IS the proper way to go about this.

Wordpress - Change page dynamically but within shortcode running php

I am using a custom shortcode plugin. The plugin allows me to run some php. The php queries a non-wp database to build a page of vehicle specs and everything works great. The issue is that all of the information needed for the page title and description is contained within the data coming from the database. I've tried some of the standard wp php filters but the title does not change.
Is this not possibly because of the execution timing of the shortcode?
TinyMCE in WP admin. Shortcode
-----------------------------------------------
[myplugin data_id='42']
PHP window in shortcode editor
-----------------------------------------------
$GP=array_merge($_GET, $_POST);
echo "hello word" //works
echo $data_id; //works
echo $GP[some_post_data]; //works
//connect to database (irrelevant)
echo "the title from data table for data_id 42 = ".$data[title]; //works
// the following has no effect on page title even though $data[title] contains valid data
add_filter('the_title','myCallback');
function myCallback($data){
return $data[title];
}
The problem is that $data[title] is out of scope, and that your filter callback is set up incorrectly. Also, you SHOULD encapsulate associative indexes with quotes.
When adding a callback to an existing filter, the arguments within the callback are passed by the filter definition. Case and point: Filtering The Title
The arguments within a standard filter for the_title are $title and $id. If you want to return the title from your $data array, you can do it the sloppy way using the global scope:
add_filter('the_title','myCallback');
function myCallback($title, $id){
global $data;
return $data['title'];
}
But personally, I would look into avoiding globals altogether and concentrate on utilizing custom filters. Look into Adding Your Own Hooks. After getting a handle on action hooks, Filter Hooks are pretty easy to grasp.

Resources