i need help with decode json
if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},
';
endwhile;
$json = substr($json,0,-1);
$json .= ']}';
echo $json;
endif;
break;
}
my error is
in the last } i have still , so i need to remove it.
but i dont know how ?
someone help me ?
As mentioned in the comments, json_encode is the way to go.
$toEncode = array(
"api_status" => 1,
"api_message" => "success",
"data" => array()
);
while ($loop->have_posts()) {
$loop->the_post();
array_push($toEncode["data"], array(
"id" => get_the_ID(),
"post_name" => get_the_title()
));
}
echo json_encode($toEncode);
However, I do not quite understand how your system for posts work. Are you using some type of iterator?
You can use php function json_decode / encode:
JSON_DECODE
JSON_ENCODE
f.ex.
json_decode($variable, true);
json_encode($variable, true);
use rtrim($json, ","); to remove last comma from json output
if($loop->have_posts()) :
$json = '{';
$json .= '
"api_status":1,
"api_message":"success",
"data": [';
while ( $loop->have_posts() ) : $loop->the_post();
$json .= '{
"id":'.get_the_ID().',
"post_name":"'.get_the_title().'"
},';
endwhile;
$json = rtrim($json, ",");
$json .= ']}';
echo $json;
endif;
break;
}
another way
$json = new array();
if($loop->have_posts()) :
$json["api_status"] = 1,
$json["api_message"] = "success",
$json["data"] = new array();
while ( $loop->have_posts() ) : $loop->the_post();
$json["data"]["id"] = get_the_ID();
$json["data"]["post_name"] = get_the_title();
endwhile;
echo json_encode($json);
endif;
break;
}
Related
Hellow.
I'm not only a php beginner and but a wordpress beginner.
I try to integrate 3rd-party PHP file and Javascript (For Age Verification using Phone. i.e: SMS Certification) into my wordpress site.
this 3rd-party reference
Using 'add_shortcode', i managed to add 'request function' to my wordpress site. (Reference Url's STEP 1)
if (! function_exists ( 'register_mycustom_agecert_page' ) ) {
function register_mycustom_agecert_page () {
$mid ='**********'; // Given MID(Merchant ID)
$apiKey ='********************************'; // apikey to MID
$mTxId ='***********';
$reqSvcCd ='01';
// Check if registered merchant or not.
$plainText1 = hash("sha256",(string)$mid.(string)$mTxId.(string)$apiKey);
$authHash = $plainText1;
$userName = 'Anonymous'; // User name
$userPhone = '01011112222'; // user Phone
$userBirth ='19830000'; // user Birth
$flgFixedUser = 'N'; // When fixing specific user, use below 'Y' setting.
if($flgFixedUser=="Y")
{
$plainText2 = hash("sha256",(string)$userName.(string)$mid.(string)$userPhone.(string)$mTxId.(string)$userBirth.(string)$reqSvcCd);
$userHash = $plainText2;
}
$foo = '';
$foo .= '<div align="center" class="age-gate-wrapper">';
$foo .= '<form name="saForm">';
$foo .= '<input type="hidden" name="mid" value="' . $mid . '">';
$foo .= '<input type="hidden" name="reqSvcCd" value="' . $reqSvcCd . '">';
$foo .= '<input type="hidden" name="mTxId" value="' . $mTxId . '">';
$foo .= '<input type="hidden" name="authHash" value="' . $authHash .'">';
$foo .= '<input type="hidden" name="flgFixedUser" value="' . $flgFixedUser . '">';
$foo .= 'input type="hidden" id="userName" name="userName"';
$foo .= '<input type="hidden" id="userPhone" name="userPhone">';
$foo .= '<input type="hidden" id="userBirth" name="userBirth">';
$foo .= '<input type="hidden" name="userHash" value="' . $userHash . '">';
$foo .= '<input type="hidden" name="directAgency" value="">';
$foo .= '<input type="hidden" name="successUrl" value="' . esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '<input type="hidden" name="failUrl" value="'. esc_url( get_stylesheet_directory_uri() . '/kg/success.php' ) . '">';
$foo .= '</form>';
$foo .= '<button onclick="callSa()">Proceed to "Age Verification"</button>';
$foo .= '</div>';
echo $foo;
}
add_shortcode( 'register_mycustom_agecert_page', 'register_mycustom_agecert_page');
}
callSa() script.
function callSa()
{
let window = popupCenter();
if(window != undefined && window != null)
{
document.saForm.setAttribute("target", "sa_popup");
document.saForm.setAttribute("post", "post");
document.saForm.setAttribute("action", "https://sa.inicis.com/auth");
document.saForm.submit();
}
}
function popupCenter() {
let _width = 400;
let _height = 620;
var xPos = (document.body.offsetWidth/2) - (_width/2); // Align center
xPos += window.screenLeft; // For dual monitor
return window.open("", "sa_popup", "width="+_width+", height="+_height+", left="+xPos+", menubar=yes, status=yes, titlebar=yes, resizable=yes");
}
And then, i put success.php file in "childtheme-folder/kg/".
(Reference's Step 2, 3)
success.php file.
<?php
// -------------------- recieving --------------------------------------
extract($_POST);
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
echo 'authRequestUrl : '.$_REQUEST["authRequestUrl"]."<br/>";
echo 'txId : '.$_REQUEST["txId"]."<br/><br/><br/>";
$mid ='********'; // Test MID. You need to replace Test MID with Merchant MID.
if ($_REQUEST["resultCode"] === "0000") {
$data = array(
'mid' => $mid,
'txId' => $txId
);
$post_data = json_encode($data);
// Start 'curl'
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $_REQUEST["authRequestUrl"]);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$response = curl_exec($ch);
curl_close($ch);
// -------------------- Recieve result -------------------------------------------
echo $response;
// Check If user age is under 20 years old or not.
$pre_age_cert_result = json_decode( $response, true );
if ( isset ($pre_age_cert_result) && ! empty ( $pre_age_cert_result['userBirthday'] ) ) {
$pre_user_input_date = date ( 'Ymd', strtotime ($pre_age_cert_result['userBirthday']) );
$user_input_date = new DateTime( $pre_user_input_date );
$current_date = new DateTime();
$user_input_date->add( new DateInterval( 'P20Y' ) );
if ( $current_date > $user_input_date ) {
$age_cert_check = true;
$age_checking_msg = 'Age Verification: Success';
} else {
$age_cert_check = false;
$age_checking_msg = 'Age Verification: Failed';
}
} else {
$age_cert_check = false;
$age_checking_msg = 'Some Problem.';
}
echo $age_checking_msg;
// Add result of age cert into usermeta.
if ( $age_cert_check === true ) {
echo 'Success - Process 01';
echo '<br>';
if ( is_user_logged_in() ) {
echo 'Success - Process 02';
echo '<br>';
$temp_current_user_id = get_current_user_id();
echo $temp_current_user_id;
if ( $temp_current_user_id !== 0 && $temp_current_user_id !== NULL ) {
echo 'Success - Process 03';
echo '<br>';
$result_cur_time = date( 'Ymd', strtotime("now") );
echo $result_cur_time;
update_user_meta( $temp_current_user_id, 'ageCert', true );
update_user_meta( $temp_current_user_id, 'ageCertDate', $result_cur_time );
} else {
echo 'Failure - Process 03';
echo '<br>';
return;
}
} else {
echo 'Failure - Process 02';
echo '<br>';
$button_link_03 = esc_url( wp_login_url() );
$button_text_03 = esc_html( __( 'You Need to Login.', 'woocommerce' ) );
echo ''.$button_text_03.'';
return;
}
} else {
echo 'Failure - Process 01';
echo '<br>';
return;
}
}else { // if resultCode===0000 is not, display below code.
echo 'resultCode : '.$_REQUEST["resultCode"]."<br/>";
echo 'resultMsg : '.$_REQUEST["resultMsg"]."<br/>";
}
?>
Finally i could get "echo 'Success - Process 01". But i can't display neither 'success -Process 02' nor 'Failure -Process 02'.
I think the cause of this is that success.php is not wordpress page. So success.php doesn't have access to wordpress function.
How can i achive my goal?
If it's not possible to fetch usermeta in custom page (like success.php), below can be option ?
Using wordpress Rest-API, send value of $user_input_date. And hook somewhere, like wp_remote_get() ?
Using alternative function which can get usermeta from wordpress.
Grating access to wordpress to success.php page
I would appreciate any reference page or example Code.
Thank you for reading this long article.
Finally i achive my goal - thanks to IT goldman and Json.
i added below 2 lines into success.php
$custom_path = '/wp-load.php file path';
require_once( $custom_path . '/wp-load.php' );
It works !
You can just include "wp-config.php"; as the first line of your php script then you get all wordpress functions, including get_user_meta.
you use use wp_load.php on success.php file
if your folder structure is like this (/wp-content/themes/child-theme/kg/success.php)
in the success.php file add this line
<?php
include_once("../../../../wp-load.php");
echo "test:: " . get_site_url();
wp-load.php which loads all the functions and code for wordpress(bootstraps).
I had to redirect the visitor to another page if something went wrong. Header location couldn't work because there is already some things displayed so I only have the choice to use javascript. Here is a piece of my PHP code :
add_action('frm_field_input_html', 'getDoctypes');
function getDoctypes($field, $echo = true){
$url = 'http://ff/interface/iface.php';
$html = '';
if ($field['id'] == get_id_from_key_frm('doctype')){
$data = array('action' => 'getDoctypes');
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded\r\n",
'timeout' => 30,
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
$return = file_get_contents($url, false, $context);
$doctypes = json_decode($return);
if ($return === FALSE || isset($doctypes -> code)){
$wpBaseUrl = site_url();
echo "<script>window.location = '$wpBaseUrl/error-connection-interface/' </script>";
}else{
$html = ">";
foreach ($doctypes as $code => $name){
$html .= "<option value=\"$code\">$name</option>";
}
}
}
if ($echo)
echo $html;
return $html;
}
The problem is when $return === FALSE, instead of executing the script, it just display "window.location = 'http://my_ip/error-connection-interface/'" into the HTML
Any ideas ?
Thanks in advance
Here's my code:
js
var priorities = {
banner: '300',
avatar: '301'
};
var editableDiv = $('*[data-edit]');
editableDiv.append('<div class="overlay-edit"></div>');
editableDiv.each(function(index, value) {
var actualPriorities = value.getAttribute("data-edit");
console.log(actualPriorities);
console.log(priorities[actualPriorities]);
});
html/php
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "=" . $value . " ";
}
}
?>
>
$this->htmlOptions contains
array('data-edit' => 'avatar')
The output :
banner
300
avatarĀ
undefined
I do not understand why my last result is undefined. When I'm trying
priorities['avatar']; // ouput is 301
The output is good.
The problem is the no breaking space character, and you can improve the code wrapping in quotes:
<div class="hexagon-wrap" style="height:<?php echo $this->outterHeight;?>px; width:<?php echo $this->outterWidth;?>px"
<?php
if($this->htmlOptions) {
foreach ($this->htmlOptions as $key => $value) {
echo $key . "='" . $value . "' ";
}
}
?>
Note that I change the with the ' (with a real space to separate the attributes)
Hope someone can help.
I'm currently building a directory, and have used ACF to populate some data. I am now working toward building a filter for the options selected within one of my ACF groups, The field group is called 'Member Directory' the field I'm specifically targeting is: 'wha_service_offered'.
There are four checkbox values within this:
supplier : Supplier
manufacturer : Manufacturer
installer : Installer
consultant : Consultant
I have used checkbox as more than one option may apply to a member.
I have set up functions.php with the following:
// Filter Services
add_action('pre_get_posts', 'my_pre_get_posts');
function my_pre_get_posts( $query )
{
// validate
if( is_admin() )
{
return $query;
}
// allow the url to alter the query
// eg: http://www.website.com/members?wha_service_offered=installer
// eg: http://www.website.com/members?wha_service_offered=consultant
if( isset($_GET['wha_service_offered']) )
{
$query->set('meta_key', 'wha_service_offered');
$query->set('meta_value', $_GET['wha_service_offered']);
}
// always return
return $query;
}
And within my archive-members.php
php
<div id="search-services">
<?php
$field = get_field_object('wha_service_offered');
$values = isset($_GET['wha_service_offered']) ? explode(',', $_GET['wha_service_offered']) : array();
?>
<ul>
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
<li>
<input type="checkbox" value="<?php echo $choice_value; ?>" <?php if( in_array($choice_value, $values) ): ?>checked="checked"<?php endif; ?> /> <?php echo $choice_label; ?></li>
</li>
<?php endforeach; ?>
</ul>
</div>
javascript
<script type="text/javascript">
(function($) {
$('#search-services').on('change', 'input[type="checkbox"]', function(){
// vars
var $ul = $(this).closest('ul'),
vals = [];
$ul.find('input:checked').each(function(){
vals.push( $(this).val() );
});
vals = vals.join(",");
window.location.replace('<?php echo home_url('members'); ?>?wha_service_offered=' + vals);
console.log( vals );
});
})(jQuery);
</script>
When the filter is used it simply returns a blank page.
I would be grateful if anyone could point out where I have made an error.
Thanks.
--
So debug returns:
Declaration of Custom_Nav_Walker::start_el() should be compatible with
Walker_Nav_Menu::start_el(&$output, $item, $depth = 0, $args = Array, $id = 0) in
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php on line 169
Warning: Cannot modify header information - headers already sent by (output started at
/Applications/MAMP/htdocs/website.com/wp-content/themes/wha/functions.php:169) in
/Applications/MAMP/htdocs/website.com/wp-includes/pluggable.php on line 1179
The offending item is:
class Custom_Nav_Walker extends Walker_Nav_Menu {
function check_current($classes) {
return preg_match('/(current[-_])/', $classes);
}
function start_el(&$output, $item, $depth, $args) {
global $wp_query;
$indent = ($depth) ? str_repeat("\t", $depth) : '';
$slug = sanitize_title($item->title);
$id = apply_filters('nav_menu_item_id', 'menu-' . $slug, $item, $args);
$id = strlen($id) ? '' . esc_attr( $id ) . '' : '';
$class_names = $value = '';
$classes = empty($item->classes) ? array() : (array) $item->classes;
$classes = array_filter($classes, array(&$this, 'check_current'));
if ($custom_classes = get_post_meta($item->ID, '_menu_item_classes', true)) {
foreach ($custom_classes as $custom_class) {
$classes[] = $custom_class;
}
}
$class_names = join(' ', apply_filters('nav_menu_css_class', array_filter($classes), $item, $args));
$class_names = $class_names ? ' class="' . $id . ' ' . esc_attr($class_names) . '"' : ' class="' . $id . '"';
$output .= $indent . '<li' . $class_names . '>';
$attributes = ! empty($item->attr_title) ? ' title="' . esc_attr($item->attr_title) .'"' : '';
$attributes .= ! empty($item->target) ? ' target="' . esc_attr($item->target ) .'"' : '';
$attributes .= ! empty($item->xfn) ? ' rel="' . esc_attr($item->xfn ) .'"' : '';
$attributes .= ! empty($item->url) ? ' href="' . esc_attr($item->url ) .'"' : '';
$item_output = $args->before;
$item_output .= '<a'. $attributes .'>';
$item_output .= $args->link_before . apply_filters('the_title', $item->title, $item->ID) . $args->link_after;
$item_output .= '</a>';
$item_output .= $args->after;
$output .= apply_filters('walker_nav_menu_start_el', $item_output, $item, $depth, $args);
}
}
I'm not understanding why the walker nav would affect the filter?
--
Corrected line 169 error by amending the following from:
function start_el(&$output, $item, $depth, $args) {
To
function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) {}
I now have the following errors:
Notice: Undefined index: choices in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Warning: Invalid argument supplied for foreach() in /Applications/MAMP/htdocs/website.com/wp-content/themes/wha/archive-members.php on line 54
Which relates to:
<?php foreach( $field['choices'] as $choice_value => $choice_label ): ?>
I am using the below php code to export from my mysql database:
<?php
require_once('connect.php');
$group = 1;//$_GET['group'];
$export = mysql_query ("SELECT * FROM relationship WHERE group_id = $group");
$fields = mysql_num_fields ( $export );
for ( $i = 0; $i < $fields; $i++ )
{
$header .= mysql_field_name( $export , $i ) . "\t";
}
while( $row = mysql_fetch_row( $export ) )
{
$line = '';
foreach( $row as $value )
{
if ( ( !isset( $value ) ) || ( $value == "" ) )
{
$value = "\t";
}
else
{
$value = str_replace( '"' , '""' , $value );
$value = '"' . $value . '"' . "\t";
}
$line .= $value;
}
$data .= trim( $line ) . "\n";
}
$data = str_replace( "\r" , "" , $data );
if ( $data == "" )
{
$data = "\n(0) Records Found!\n";
}
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=your_desired_name.xls");
header("Pragma: no-cache");
header("Expires: 0");
print "$header\n$data";
mysql_close($my_connection);
?>
I can download the file from my browser (chrome) if I simply run this php file.
However, the download does not show if I use a click button on another page and call below javascript to run this php file:
<script>
function export_data()
{alert(1);
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "export.php",
data: {group: localStorage.group_id},
dataType: "html",
success: function(response){
alert(response);
}
});alert(2);
}
</script>
Javascript will alert all the xls contents, but block the download.
How can I solve this?
Thanks in advance!
Why don't you just use window.location instead of AJAX ?
<script>
function export_data()
{
window.location='export.php';
}
</script>
You can remove JavaScript click even and direct create a link
Download
This will download file without referencing page on browser.