How to add multiple custom fields to a wp_query in a shortcode? - shortcode

In a shortcode I can limit wp_query results by custom field values.
Example:
[my-shortcode meta_key=my-custom-field meta_value=100,200 meta_compare='IN']
And obviously it's possible to use multiple custom fields in a wp_query like WP_Query#Custom_Field_Parameters
But how can I use multiple custom fields in my shortcode? At the moment I do pass all the shortcode parameters with $atts.

On of a few different solutions might be to use a JSON encoded format for the meta values. Note that this isn't exactly user-friendly, but certainly would accomplish what you want.
You would of course need to generate the json encoded values first and ensure they are in the proper format. One way of doing that is just using PHP's built in functions:
// Set up your array of values, then json_encode them with PHP
$values = array(
array('key' => 'my_key',
'value' => 'my_value',
'operator' => 'IN'
),
array('key' => 'other_key',
'value' => 'other_value',
)
);
echo json_encode($values);
// outputs: [{"key":"my_key","value":"my_value","operator":"IN"},{"key":"other_key","value":"other_value"}]
Example usage in the shortcode:
[my-shortcode meta='[{"key":"my_key","value":"my_value","operator":"IN"},{"key":"other_key","value":"other_value"}]']
Which then you would parse out in your shortcode function, something like so:
function my_shortcode($atts ) {
$meta = $atts['meta'];
// decode it "quietly" so no errors thrown
$meta = #json_decode( $meta );
// check if $meta set in case it wasn't set or json encoded proper
if ( $meta && is_array( $meta ) ) {
foreach($meta AS $m) {
$key = $m->key;
$value = $m->value;
$op = ( ! empty($m->operator) ) ? $m->operator : '';
// put key, value, op into your meta query here....
}
}
}
Alternate Method
Another method would be to cause your shortcode to accept an arbitrary number of them, with matching numerical indexes, like so:
[my-shortcode meta-key1="my_key" meta-value1="my_value" meta-op1="IN
meta-key2="other_key" meta-value2="other_value"]
Then, in your shortcode function, "watch" for these values and glue them up yourself:
function my_shortcode( $atts ) {
foreach( $atts AS $name => $value ) {
if ( stripos($name, 'meta-key') === 0 ) {
$id = str_ireplace('meta-key', '', $name);
$key = $value;
$value = (isset($atts['meta-value' . $id])) ? $atts['meta-value' . $id] : '';
$op = (isset($atts['meta-op' . $id])) ? $atts['meta-op' . $id] : '';
// use $key, $value, and $op as needed in your meta query
}
}
}

Related

Adding a key value pair to an existing json object in perl

I want to add a key value pair to a JSON object. Following is the structure of Param{Data} variable for the below code.
$VAR1 = {
'ArticleID' => '86',
'OldTicketData' => {
...
},
'TicketID' => '67'
};
Following is the function in which I want to perform the mentioned operation:
sub PrepareRequest {
my ( $Self, %Param ) = #_;
my %TicketInfo = $Self->{TicketObject}->ArticleGet(
ArticleID => $Param{Data}->{ArticleID},
userID => $Param{Data}->{CustomerID},
);
my %newParamData = to_json($Param{Data});
%newParamData->{'OldTicketData'}->{'Body'}=$TicketInfo{Body};
return {
Success => 1,
Data => %newParamData,
};
}
Above function returns 'OldTicketData'. I want following key-pair attached to 'OldTicketData' element of the JSON object ->('Body', $TicketInfo{Body}). Consider, $TicketInfo{Body} returns a string 'someString'.
Your code is the wrong way around. You need to add the key to the hash reference first, before you turn it into JSON.
$Param{Data}->{'OldTicketData'}->{'Body'}=$TicketInfo{Body};
my $newParamData = to_json($Param{Data});
In addition, since to_json returns a string, which is scalar, you need to use $newParamData instead of %newParamData.
Of course you need to fix your return as well.
return {
Success => 1,
Data => $newParamData,
};

Fetch all user information with Net::LDAP

Currently have an small perl script what for the given username fetch his email address from the ActiveDirectory using Net::LDAP.
The search part is the following:
my $user = "myuser";
my $mesg = $ldap->search(
base => "dc=some,dc=example,dc=com",
filter => '(&(sAMAccountName=' . $user . ')(mail=*))', #?!?
);
for my $entry ($mesg->entries) {
my $val = $entry->get_value('mail');
say "==$val==";
}
Working ok.
How i should modify the above statement to fetch all available information for the given user myuser? I'm looking to get an perl-ish data structure, such something like next:
my $alldata = search(... all info for the given $user ... );
say Dumper $alldata; #hashref with all stored informations for the $user
It is probably dead simple - but i'm an total AD & LDAP-dumb person...
Edit: When I dump out the $msg->entries (what is an LADP::Entry object) got something, but i'm not sure than it contains everything or only the part of the stored data...
I've done something similar, and I use this to query LDAP:
my $ldapResponse = $ldap->search(base => $base, filter => $filter, attrs => $attrs);
And then this to parse it:
if ($ldapResponse && $ldapResponse->count()) {
$ldapResponse->code && die $ldapResponse->error;
my %domainNames = %{$ldapResponse->as_struct};
foreach my $domainName (keys %domainNames) {
my %ldapResponse;
my %dnHash = %{$domainNames{$domainName}};
foreach my $attr (sort(keys %dnHash)) {
# Note that the value for each key of %dnHash is an array,
# so join it together into a string.
my $value = join(" ", #{$dnHash{$attr}});
$ldapResponse{$attr} = $value;
}
// Dump/use %ldapResponse
}
}
I've never tried to use the ldap->entries in your code, but the above works for me!
I explicitly specify a(long) list of attributes ($attr), but perhaps that's optional as your example shows, and you can get ALL LDAP fields by just skipping that arg to search().

how to set a value for Zend_Form_Element_Submit (zendframework 1)

I have am having trouble setting the basic values of a zend form element submit button (Zendframework1). I basically want to set a unique id number in it and then retrieve this number once the button has been submitted.
Below is my code. you will nots that I tried to use the setValue() method but this did not work.
$new = new Zend_Form_Element_Submit('new');
$new
->setDecorators($this->_buttonDecorators)
->setValue($tieredPrice->sample_id)
->setLabel('New');
$this->addElement($new);
I would also appreciate any advice on what I use to receive the values. i.e what method I will call to retrieve the values?
The label is used as the value on submit buttons, and this is what is submitted. There isn't a way to have another value submitted as part of the button as well - you'd either need to change the submit name or value (= label).
What you probably want to do instead is add a hidden field to the form and give that your numeric value instead.
It's a little bit tricky but not impossible :
You need to implement your own view helper and use it with your element.
At first, you must add a custom view helper path :
How to add a view helper directory (zend framework)
Implement your helper :
class View_Helper_CustomSubmit extends Zend_View_Helper_FormSubmit
{
public function customSubmit($name, $value = null, $attribs = null)
{
if( array_key_exists( 'value', $attribs ) ) {
$value = $attribs['value'];
unset( $attribs['value'] );
}
$info = $this->_getInfo($name, $value, $attribs);
extract($info); // name, value, attribs, options, listsep, disable, id
// check if disabled
$disabled = '';
if ($disable) {
$disabled = ' disabled="disabled"';
}
if ($id) {
$id = ' id="' . $this->view->escape($id) . '"';
}
// XHTML or HTML end tag?
$endTag = ' />';
if (($this->view instanceof Zend_View_Abstract) && !$this->view->doctype()->isXhtml()) {
$endTag= '>';
}
// Render the button.
$xhtml = '<input type="submit"'
. ' name="' . $this->view->escape($name) . '"'
. $id
. ' value="' . $this->view->escape( $value ) . '"'
. $disabled
. $this->_htmlAttribs($attribs)
. $endTag;
return $xhtml;
}
}
So, you assign the helper to the element :
$submit = $form->createElement( 'submit', 'submitElementName' );
$submit->setAttrib( 'value', 'my value' );
$submit->helper = 'customSubmit';
$form->addELement( $submit );
This way, you can retrieve the value of the submitted form :
$form->getValue( 'submitElementName' );

How do i pass a variable for the query in a get Manager call?

I am trying to make a simple Rose DB call:
$id = xyz;
$name = "company";
DataB::testTable::Manager->get_testTable( query =>[ id => $id, name => $name ] );
in it possible to not have the whole query written every time, and declare it like a string variable such that i can just call
DataB::testTable::Manager->get_testTable( query =>[ $query ] );
where $query = qq { id => $id , name => $name };
Please Help
By what I understood from your question, I am giving this answer.
Try this one.
my $myquery = {query =>{ id=>$id, name=>$name }} ;
TGI::testTable::Manager->get_testTable($myquery);
Hope, this gives some idea to you.
Edit for "Hash with Array reference":
my $myquery = [ id=>$id, name=>$name ] ;
TGI::testTable::Manager->get_testTable(query => $myquery);
check out this : How to pass a a string variable as "query" for get Manager call?
Well actually i figured out how to do that . Its not that complicated. Only thing is RoseDB objects expect an array reference for a query. So something like this works :
my #query = ( id => $id, name => $name );
testDB::testTable::Manager->get_testTable( query => \#query );
Just thought would answer it myself, incase someonelse is looking for a solution to this

How to post array form using LWP

I am having problems creating an array that I can pass as a form using LWP. Basic code is
my $ua = LWP::UserAgent->new();
my %form = { };
$form->{'Submit'} = '1';
$form->{'Action'} = 'check';
for (my $i=0; $i<1; $i++) {
$form->{'file_'.($i+1)} = [ './test.txt' ];
$form->{'desc_'.($i+1)} = '';
}
$resp = $ua->post('http://someurl/test.php', 'Content_Type' => 'multipart/form-data'
, 'Content => [ \%form ]');
if ($resp->is_success()) {
print "OK: ", $resp->content;
}
} else {
print $claimid->as_string;
}
I guess I am not creating the form array correctly or using the wrong type as when I check the _POST variables in test.php nothing has been set :(
The problem is that for some reason you've enclosed your form values in single quotes. You want to send the data structure. E.g.:
$resp = $ua->post('http://someurl/test.php',
'Content_Type' => 'multipart/form-data',
'Content' => \%form);
You want to either send the hash reference of %form, not the has reference contained within an array reference as you had ([ \%form ]). If you had wanted to send the data as an array reference, then you'd just use[ %form ]` which populates the array with the key/value pairs from the hash.
I'd suggest that you read the documentation for HTTP::Request::Common, the POST section in particular for a cleaner way of doing this.