How to replace the $content value in transformation? - xquery

I need to replace the $content value in my transformation.
xquery version "1.0-ml";
module namespace test =
"http://marklogic.com/rest-api/transform/security-load";
declare function test:transform(
$context as map:map,
$params as map:map,
$content as document-node()
) as document-node()
{
let $jsonObj := xdmp:from-json($content)
let $inputval := "fname,lname"
let $entity :="holidayDate"
let $domain :="referenceData"
let $uri := xdmp:apply(
xdmp:function(xs:QName("createUri"), "/wdsUtils.sjs"),
$jsonObj,
$inputval)
let $root := xdmp:apply(
xdmp:function(xs:QName("addMetaData"), "/wdsUtils.sjs"),
$entity,
$domain,
$jsonObj)
let $output := $root
return map:put($context,"uri",$uri),
document { $output }
};
I need to change the $content value with $root value and return it. I was trying to return $root directly but it didn't work, I was getting invalid document error.

The problem is that $output is scoped to the FLWOR statement, but you're referring to it outside of that statement. See the parentheses in the return below.
xquery version "1.0-ml";
module namespace test = "http://marklogic.com/rest-api/transform/security-load";
declare function test:transform(
$context as map:map,
$params as map:map,
$content as document-node()
) as document-node()
{
let $jsonObj := xdmp:from-json($content)
let $inputval := "fname,lname"
let $entity :="holidayDate"
let $domain :="referenceData"
let $uri :=
xdmp:apply(
xdmp:function(xs:QName("createUri"), "/wdsUtils.sjs"),
$jsonObj,
$inputval
)
let $root :=
xdmp:apply(
xdmp:function(xs:QName("addMetaData"), "/wdsUtils.sjs"),
$entity,
$domain,
$jsonObj
)
let $output := $root
return (
map:put($context,"uri",$uri),
document { $output }
)
};

Related

How to declar a variable using isset() function on Wordpress

I have a block of php codes I put in functions.php on Wordpress website, part of which is as shown below:
add_filter('request', 'my_change_term_request', 1, 1 );
function my_change_term_request($query){
$tax_name = 'ait-items'; // specify you taxonomy name here, it can be also 'category' or 'post_tag'
// Request for child terms differs, we should make an additional check
if( isset( $query['attachment'] ) && $query['attachment'] ) :
$include_children = true;
$name = $query['attachment'];
else:
$include_children = false;
if(isset($query['name'])){ $name = $query['name']; }
endif;
$term = get_term_by('slug', $name, $tax_name); // get the current term to make sure it exists
if (isset($name) && $term && !is_wp_error($term)): // check it here
if( $include_children ) {
unset($query['attachment']);
$parent = $term->parent;
while( $parent ) {
$parent_term = get_term( $parent, $tax_name);
$name = $parent_term->slug . '/' . $name;
$parent = $parent_term->parent;
}
} else {
unset($query['name']);
}
switch( $tax_name ):
case 'category':{
$query['category_name'] = $name; // for categories
break;
}
case 'post_tag':{
$query['tag'] = $name; // for post tags
break;
}
default:{
$query[$tax_name] = $name; // for another taxonomies
break;
}
endswitch;
endif;
return $query;
}
This line of codes generates error warning or notice on Wordpress:
$term = get_term_by('slug', $name, $tax_name);
like:
Notice: Undefined variable: name in /wp-content/themes/businessfinder2-child/functions.php on line 595
I have tried to replace the above line with:
$term = get_term_by('slug', if(isset($name)) { echo '$name'; }, $tax_name);
OR:
$term = get_term_by('slug', if(isset($query['name'])) { echo "$name"; }, $tax_name);
None of the above replacements work.
Very appreciate any advice.
$query is empty in nonsigular pages and it just works in singular page like post and page. Add this line in top of Function to prevent the function call in home page and etc.
if(empty($query)) return $query;
I fixed the issue. In case anyone has experience with similar issue, just declare $name as global variable before the error line like this:
global $name;
$term = get_term_by('slug', $name, $tax_name);
or at the beginning of the function.
thanks.

How to add a custom attribute?

How to add a custom attribute in the field Contact Form 7 without javascript ?
For example, there is such a field on the page:
<input type="text" name="name" class="form-control" id="name-1" data-attr="custom" data-msg="Текст 1">
Question: is it possible to set these custom attributes (data-attr, data-msg) of fields in the admin panel?
Find the name of your field.
[text* text-21]
If the name of your field name="text-21", like in my example, add this code to functions.php file.
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="text-21"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
Note, it will add those attributes to all forms elements where the name is text-21, if you want prevent it then give your form element some unique name [text* unique-name]
And change the code to
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="unique-name"' );
if ( $str_pos !== false ) {
$content = substr_replace( $content, ' data-attr="custom" data-msg="Foo Bar 1" ', $str_pos, 0 );
}
return $content;
}
Here is a generic solution that doesn't involve hardcoding the field name and the attributes
add_filter( 'wpcf7_form_tag', function ( $tag ) {
$datas = [];
foreach ( (array)$tag['options'] as $option ) {
if ( strpos( $option, 'data-' ) === 0 ) {
$option = explode( ':', $option, 2 );
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if ( ! empty( $datas ) ) {
$id = uniqid('tmp-wpcf');
$tag['options'][] = "class:$id";
add_filter( 'wpcf7_form_elements', function ($content) use ($id, $datas) {
return str_replace($id, $name, str_replace($id.'"', '"'. wpcf7_format_atts($datas), $content));
});
}
return $tag;
} );
It works on all data attributes so you can use it like this
[text* my-name data-foo:bar data-biz:baz placeholder "Blabla"]
Output: <input type="text" name="my-name" data-foo="bar" data-biz="baz" placeholder="Blabla">
Since wpcf7 doesn't provide a way to hook into options directly the solutions uses a trick and temporary adds a uniquely generated class to the field that is then replaced in a later filter with the added attributes
If you need it to work with more than just data attributes you can whitelist some more attributes by replacing this line
if ( strpos( $option, 'data-' ) === 0 ) {
to something like the following
if ( preg_match( '/^(data-|pattern|my-custom-attribute)/', $option ) ) {
Note: wpcf7_format_atts will not output empty attributes, so make sure you give a value to your attributes
Multiple attributes can be added also. eg
add_filter( 'wpcf7_form_elements', 'imp_wpcf7_form_elements' );
function imp_wpcf7_form_elements( $content ) {
$str_pos = strpos( $content, 'name="your-email-homepage"' );
$content = substr_replace( $content, ' aria-describedby="emailHelp" ', $str_pos, 0 );
$str_pos2 = strpos( $content, 'name="your-fname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="fnameHelp" ', $str_pos2, 0 );
$str_pos3 = strpos( $content, 'name="your-lname-homepage"' );
$content = substr_replace( $content, ' aria-describedby="lnameHelp" ', $str_pos3, 0 );
return $content;
}
Extending on from Tofandel's solution, for the benefit of those who got 99% of the way there, but suffered validation issues - I've resolved that in my case and would like to offer an extended solution that gets as far as Tofandel's (putting the attribute into the form proper) but also successfully validates on submission.
add_filter('wpcf7_form_tag', function($tag) {
$data = [];
foreach ((array)$tag['options'] as $option) {
if (strpos( $option, 'autocomplete') === 0) {
$option = explode(':', $option, 2);
$data[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if(!empty($data)) {
add_filter('wpcf7_form_elements', function ($content) use ($tag, $data) {
$data_attrs = wpcf7_format_atts($data);
$name = $tag['name'];
$content_plus_data_attrs = str_replace("name=\"$name\"", "name=\"$name\" " . $data_attrs, $content);
return $content_plus_data_attrs;
});
}
return $tag;
} );
Rather than changing the tag ID to a random value only to replace it with the "real" value later, we just reference the real value in the first place, replacing the relevant part of the content in the wpcf7_form_elements filter (in my case, autocomplete, but as Tofandel's example shows, this can be extended to any data attribute you'd like).
I propose a solution from the one given by Tofandel without JS (CF7) error and to authorize the use of an attribute without value:
/**
* Add custom attributes on inputs
* Put "data-my-attribute" to use it, with or without value
*
* #param array $tag
*
* #return array
*/
function cf7AddCustomAttributes($tag) {
$datas = [];
foreach ((array) $tag['options'] as $option) {
if (strpos($option, 'data-') === 0 || strpos($option, 'id:') === 0) {
$option = explode(':', $option, 2);
$datas[$option[0]] = apply_filters('wpcf7_option_value', $option[1], $option[0]);
}
}
if (!empty($datas)) {
$id = $tag['name'];
if (array_key_exists('id', $datas)) {
$id = $datas['id'];
} else {
$tag['options'][] = "id:$id";
}
add_filter('wpcf7_form_elements', function ($content) use ($id, $datas) {
$attributesHtml = '';
$idHtml = "id=\"$id\"";
foreach ($datas as $key => $value) {
$attributesHtml .= " $key";
if (is_string($value) && strlen($value) > 0) {
$attributesHtml .= "=\"$value\"";
}
}
return str_replace($idHtml, "$idHtml $attributesHtml ", $content);
});
}
return $tag;
}
add_filter('wpcf7_form_tag', 'cf7AddCustomAttributes');
I use this simple method for setting attribute
[checkbox optName use_label_element "optName"]
<script>
document.querySelector(".optName").setAttribute("onchange","myscript");
</script>

Wordpress - get_post_mime_type

I'm showing a list of files on a page with there mime type.
$type = get_post_mime_type( $document['document'] );
For a pdf it outputs 'application/pdf'
Is it possible to remove the application and just show pdf.
You could do a simple explode() operation on the string:
$type = explode( '/', get_post_mime_type( $document['document'] ) );
echo $type[1];
Or write a custom function for more fine-grained control (based on Codex example):
function so28344776_get_mime_for_attachment( $post_id )
{
$type = get_post_mime_type( $post_id );
if( ! $type )
return 'N/A';
switch( $type )
{
case 'image/jpeg':
case 'image/png':
case 'image/gif':
return "image";
case 'video/mpeg':
case 'video/mp4':
case 'video/quicktime':
return "video";
case 'text/csv':
case 'text/plain':
case 'text/xml':
return "text";
case 'application/pdf':
return "pdf";
default:
return "file";
}
}
// usage
echo so28344776_get_mime_for_attachment( $document['document'] );

using shortcode attributes value in a separate php file

How to use a shortcode attributes value in a seperate php file
I have written a shortcode which acepts parameters file and type
[includefile file='membership-booking' mtype="group"]
function shortcode_includefile( $atts){
$data= shortcode_atts( array (
'mtype' => 'post',
), $atts ) ;
$path = dirname(__FILE__) . "/shortcode_includefile/" . $atts['file']. ".php";
if(file_exists($path))
include $path;
$code = ob_get_contents();
ob_end_clean();
return $code;
}
attributes file is fixed 'membership-booking' only mtype can be either group or individual.
Now in membership-booking file i want to read attributes mtype value. on the basis of mytype value i need to echo something
In your function, you can use mtype like;
$mtype = $data["mtype"];
and you can use that variable globally like;
$mtype = "post"; // This is global
function shortcode_includefile( $atts){
$data = shortcode_atts( array (
'mtype' => 'post',
), $atts ) ;
$mtype = $data["mtype"];
$path = dirname(__FILE__) . "/shortcode_includefile/" . $atts['file']. ".php"; // You can use $mtype in this file
if(file_exists($path))
include $path;
$code = ob_get_contents();
ob_end_clean();
return $code;
}

Invalid argument for foreach associative array loop

I've got an invalid argument supplied for my last associative array foreach loop. I am looping through different email addresses and creating an array. Am I doing something wrong? Should I create a null array?
Cheers!
global $wpdb, $wpsc_variations;
$stock_table = $wpdb->prefix . 'postmeta';
$posts_table = $wpdb->prefix . 'posts';
$q = 'SELECT DISTINCT post_id FROM ' . $stock_table . ' WHERE meta_key=\'' . NOTIFY_META . '\' AND meta_value=1';
$q_assoc_arr = $wpdb->get_results($q, ARRAY_A);
foreach($q_assoc_arr as $row) {
$product_id = $row['post_id'];
$product_data = get_post_custom( $product_id );
$product_data['meta'] = maybe_unserialize( $product_data );
foreach ( $product_data['meta'] as $meta_key => $meta_value ) {
$product_data['meta'][$meta_key] = $meta_value[0];
}
if ($product_data['meta']['_wpsc_stock'] > 0) {
foreach (get_post_meta($product_id, NOTIFY_EMAILS_META, true) as $k=>$v) {
$emails[] = $v;
}
Your third foreach relies on the output of get_post_meta, but you're passing true as the 3rd parameter. This tells get_post_meta to return a single value as a string, not an array.
foreach expects an array to iterate over. :)
Note: This part will fail for certain, but your other instances of foreach may also fail if an array is not passed.

Resources