<?php
define('PATH', dirname(dirname(__FILE__)).'/');
require_once (PATH.'./wp-blog-header.php');
global $wpdb;
// if(!isset($_POST['username'])){
// //echo $_POST['submit'];
// exit('非法访问!');
// }
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$checkcode = $_POST["checkcode"];
$query_pwd_str = "SELECT password FROM yjhy_users_custom WHERE username=%s";
if($wpdb == null)
echo "wpdb is null";
$pwd_query_result = $wpdb->get_results($wpdb->prepare($query_pwd_str, $username));
$pwd_query_result_count = count($pwd_query_result);
if($pwd_query_result_count == 1){
//已经存在该用户名,返回数据
// error here
header('Content-type:text/json');
$json_ouput = '{"status":"success","errormsg":"'.$username.'"}';
echo $json_ouput;
}
?>
With the code above, I use method post to refer to the php file, and it ALWAYS responsed with 404 Error.
But, when I modify PHP code as BELOW:
<?php
//****************** move the function header() here
header('Content-type:text/json');
//****************** echo "{" here
echo "{";
?>
<?php
define('PATH', dirname(dirname(__FILE__)).'/');
require_once (PATH.'./wp-blog-header.php');
global $wpdb;
// if(!isset($_POST['username'])){
// //echo $_POST['submit'];
// exit('非法访问!');
// }
$username = $_POST["username"];
$password = $_POST["password"];
$email = $_POST["email"];
$checkcode = $_POST["checkcode"];
$query_pwd_str = "SELECT password FROM yjhy_users_custom WHERE username=%s";
if($wpdb == null)
echo "wpdb is null";
$pwd_query_result = $wpdb->get_results($wpdb->prepare($query_pwd_str, $username));
$pwd_query_result_count = count($pwd_query_result);
if($pwd_query_result_count == 1){
//已经存在该用户名,返回数据
// error here
$json_ouput = '"status":"success","errormsg":"'.$username.'"';
echo $json_ouput;
}
?>
<?php
//****************** echo "}" here
echo "}";
?>
AND THEN, it works, the server response status is 200!
I'm puzzled about this problem, and have searched all day and can't find the answer!
Why does the code work like this?
With 1 days' time, I find it out!
I request the link with the file path http://localhost:7770/api/register.php directly rather than request link by creating a page in the Dashboard, so the link is not in the WP's database.
And WP framework need to initialize itself when execute wp(); in the require_once (PATH.'./wp-blog-header.php');, but when the initial action execute in the file /wp-includes/class-wp.php with code below:
public function main($query_args = '') {
$this->init();
**$this->parse_request($query_args);**
$this->send_headers();
$this->query_posts();
$this->handle_404();
$this->register_globals();
do_action_ref_array( 'wp', array( &$this ) );
}
}
the statement $this->query_posts(); need to check the link $this->parse_request();. the func parse_request():
public function parse_request($extra_query_vars = '') {
global $wp_rewrite;
/**
* Filter whether to parse the request.
*
* #since 3.5.0
*
* #param bool $bool Whether or not to parse the request. Default true.
* #param WP $this Current WordPress environment instance.
* #param array|string $extra_query_vars Extra passed query variables.
*/
if ( ! apply_filters( 'do_parse_request', true, $this, $extra_query_vars ) )
return;
$this->query_vars = array();
$post_type_query_vars = array();
if ( is_array( $extra_query_vars ) ) {
$this->extra_query_vars = & $extra_query_vars;
} elseif ( ! empty( $extra_query_vars ) ) {
parse_str( $extra_query_vars, $this->extra_query_vars );
}
// Process PATH_INFO, REQUEST_URI, and 404 for permalinks.
// Fetch the rewrite rules.
$rewrite = $wp_rewrite->wp_rewrite_rules();
if ( ! empty($rewrite) ) {
// If we match a rewrite rule, this will be cleared.
***$error = '404';***
$this->did_permalink = true;
$pathinfo = isset( $_SERVER['PATH_INFO'] ) ? $_SERVER['PATH_INFO'] : '';
list( $pathinfo ) = explode( '?', $pathinfo );
$pathinfo = str_replace( "%", "%25", $pathinfo );
list( $req_uri ) = explode( '?', $_SERVER['REQUEST_URI'] );
$self = $_SERVER['PHP_SELF'];
$home_path = trim( parse_url( home_url(), PHP_URL_PATH ), '/' );
And the link is not in the database, so WP set the error 404 here below:
And then I get the error 404in ***$error = '404';***!
resolve solution:
create a page in the Dashboard.
modify the page url you want.
put your code in the page template.
use this template in the page.
and Ok
Related
I am trying to access php variable from wordpress shortcode function and use into og filter.
I have tried with php superglobals, set transient also, but nothing give the needed result.
Can someone take a look and help, thanks!
That's my code:
add_shortcode('test', 'get_sheet_value_shortcode');
function get_sheet_value_shortcode() {
ob_start();
$API = get_option('google_sheet_api');
$google_spreadsheet_ID = get_option('google_sheet_id');
$LANG = get_language_shortcode();
$api_key = esc_attr( $API);
$get_cell = new WP_Http();
$cell_url = "https://sheets.googleapis.com/v4/spreadsheets/$google_spreadsheet_ID/values/$LANG!A1:Z1000/?majorDimension=ROWS&key=$api_key";
$cell_response = $get_cell -> get( $cell_url);
if ( empty( $cell_response) ) {
return;
}
$json_body = json_decode($cell_response['body'],true);
$values = $json_body['values'];
//$values = json_encode($values);
array_shift($values); // removes first column key
if (! empty($values) ) {
$count = count($values);
// this will be using for share f-nality, so we can get same quote
$quote_number = array_search($rand_values, $values);
$rand_values = $values[array_rand($values)];
$image = (! empty($rand_values[3]) ) ? $rand_values[3] : '';
$GLOBALS['ogimage'] = $image;
}
ob_get_clean();
}
add_filter( 'aioseo_facebook_tags2', 'aioseo_filter_facebook_title2', 99 );
function aioseo_filter_facebook_title2( $facebookMeta ) {
$image = $GLOBALS['ogimage'];
if ( is_page('test') ) {
$facebookMeta['og:image'] = $image;
}
return $facebookMeta;
}
I am trying to process a cron job and keep getting a t-string error. I know this usually indicates a missing ; or } but I have double checked and triple checked.
Any idea? The returned error is
unexpected T_STRING in /.../wp-crm.php on line 40
<?php
/**
Name: Cron for WP Property Importer
Description: Allow cron jobs to be executed from Command Line interface.
#todo Fix so that we're using the correct deletion function.
*/
ini_set( "display_errors", 1);
set_time_limit(0);
ignore_user_abort(true);
define( 'WPP_XMLI_CRON_RUNNING', true );
/**
* Determine request type ( HTTP or SHELL COMMAND )
*/
/* HTTP */
if( isset( $_SERVER[ 'REQUEST_URI' ] ) && isset( $_SERVER[ 'QUERY_STRING' ] )){
$argv = array( __FILE__ );
$get =array();
parse_str( $_SERVER[ 'QUERY_STRING' ], $get );
foreach( $get as $k => $v ){
switch( $k ) {
case 'action':
$argv[1] = $v;
break;
case 'hash':
$argv[2] = $v;
break;
}
}
}
/* SHELL COMMAND */
else {
//** It seams cron service in CPanel works not like normal Linux Cron, so we have to emulate $argv
$VERBOSE = true;
if (!empty($_REQUEST) && array_key_exists('do_xml_import',$_REQUEST)){
$argv = array_keys($_REQUEST);
}
}
/** Need to at least have the do_xml_import argument */
if (empty($argv[0])) {
if($VERBOSE){ print("Missing arguments.\n"); }
exit(1);
}
$cron_action = $argv[1];
$schedule_hash = $argv[2];
$ms_url = (!empty($argv[3])) ? $argv[3] : '';
//** Load WP */
$wp_load_path = preg_replace( '%wp-content[/\\\\]plugins[/\\\\]wp-property-importer[/\\\\]cron.php%ix', 'wp-load.php', __FILE__ );
if(!file_exists($wp_load_path)) {
if($VERBOSE){ print('Cannot load WP using: ' . $wp_load_path ."\n"); }
exit(1);
} else {
/** these arguments should be passed in multisite mode */
if (!empty($ms_url) ) {
$site_name = parse_url('http://'.$ms_url,PHP_URL_PATH);
$site_domain = parse_url('http://'.$ms_url, PHP_URL_HOST);
/**
* Construct a fake $_SERVER global to get WordPress to load a specific site.
* This avoids alot of messing about with switch_to_blog() and all its pitfalls.
*/
$_SERVER=array(
'HTTP_HOST'=>$site_domain,
'REQUEST_METHOD'=>'GET',
'REQUEST_URI'=>"{$site_name}/",
'SERVER_NAME'=>$site_domain,
);
// Remove all our bespoke variables as they'll be in scope as globals and could affect WordPress
unset($site_name,$site_domain);
// Pretend that we're executing an AJAX process. This should help WordPress not load all of the things.
define('DOING_AJAX',true);
// Stop WordPress doing any of its normal output handling.
define('WP_USE_THEMES',false);
}
// Load WordPress - intentionally using an absolute URL due to issues with relative paths on the CLI.
include $wp_load_path;
}
//** Enable/disable debug mode. debug_mode argv must be passed to enable it. */
if( !defined( 'WPP_DEBUG_MODE' ) ) {
define( 'WPP_DEBUG_MODE', ( !empty( $argv[3] ) && $argv[3] == 'debug_mode' ? true : false ) );
}
//** Ensure file was loaded and procesed */
if( ABSPATH && class_exists( 'class_wpp_property_import' ) ) {
define('DOING_WPP_CRON', true);
} else {
if($VERBOSE){ print('Unable to load XML Importer.' . "\n"); }
exit(1);
}
if(empty($cron_action)) {
if($VERBOSE){ print("Missing action argument.\n"); }
exit(1);
}
/** Begin Loading Import*/
if($cron_action == 'do_xml_import' && !empty($schedule_hash)) {
define('WPP_IMPORTER_HASH', $schedule_hash);
//class_wpp_property_import::init();
class_wpp_property_import::run_from_cron_hash();
exit(0);
} elseif($cron_action == 'erase_all_properties') {
global $wpdb;
$wpdb->show_errors();
/** First, delete attachments */
$sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type = 'attachment' AND post_parent IN (SELECT ID FROM {$wpdb->prefix}posts WHERE post_type = 'property') OR post_excerpt = 'qr_code'";
foreach($wpdb->get_results($sql) as $row) {
wp_delete_attachment($row->ID, true);
if($VERBOSE){ print( "Deleted attachment: ".$row->ID."\r\n"); }
}
/** Now, delete posts */
$sql = "SELECT ID FROM {$wpdb->prefix}posts WHERE post_type = 'property'";
foreach($wpdb->get_results($sql) as $row){
wp_delete_post($row->ID, true);
if($VERBOSE){ print( "Deleted post: ".$row->ID."\r\n"); }
}
print( "Done deleting posts.\r\n");
exit(0);
}
else {
print( "Nothing done.\r\n");
exit(0);
}
exit(0);
?>
i using a wordpress plugin, i notice that returns a error on
$alias = (string)end(array_keys($settings));
above line .the error is
PHP Strict Standards: Only variables should be passed by reference in on wordpress function
i added that function below. anyone know how to solve that error please, becoz admin dashboard of the plugin not loading because of this error.
/*
* GET modules lists
*/
function load_modules ()
{
$folder_path = $this->cfg['paths']['plugin_dir_path'] . 'modules/';
$cfgFileName = 'config.php';
// static usage, modules menu order
$menu_order = array();
foreach(glob($folder_path . '*/' . $cfgFileName) as $module_config ){
$module_folder = str_replace($cfgFileName, '', $module_config);
// Turn on output buffering
ob_start();
if( is_file( $module_config ) ) {
require_once( $module_config );
}
$settings = ob_get_clean(); //copy current buffer contents into $message variable and delete current output buffer
if(trim($settings) != "") {
$settings = json_decode($settings, true);
$alias = (string) end(array_keys($settings));
// create the module folder URI
// fix for windows server
$module_folder = str_replace( DIRECTORY_SEPARATOR, '/', $module_folder );
$__tmpUrlSplit = explode("/", $module_folder);
$__tmpUrl = '';
$nrChunk = count($__tmpUrlSplit);
if($nrChunk > 0) {
foreach ($__tmpUrlSplit as $key => $value){
if( $key > ( $nrChunk - 4) && trim($value) != ""){
$__tmpUrl .= $value . "/";
}
}
}
// get the module status. Check if it's activate or not
$status = false;
// default activate all core modules
if(in_array( $alias, $this->cfg['core-modules'] )) {
$status = true;
}else{
// activate the modules from DB status
$db_alias = $this->alias . '_module_' . $alias;
if(get_option($db_alias) == 'true'){
$status = true;
}
}
// push to modules array
$this->cfg['modules'][$alias] = array_merge(array(
'folder_path' => $module_folder,
'folder_uri' => $this->cfg['paths']['plugin_dir_url'] . $__tmpUrl,
'db_alias' => $this->alias . '_' . $alias,
'status' => $status
), $settings );
// add to menu order arrayhttp://cc.aa-team.com/wp-plugins/smart-seo-v2/wp-admin/admin-ajax.php?action=pspLoadSection§ion=Social_Stats
if(!isset($this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']])){
$this->cfg['menu_order'][(int)$settings[$alias]['menu']['order']] = $alias;
}else{
// add the menu to next free key
$this->cfg['menu_order'][] = $alias;
}
// add module to activate modules array
if($status == true){
$this->cfg['activate_modules'][$alias] = true;
}
// load the init of current loop module
if( $status == true && isset( $settings[$alias]['module_init'] ) ){
if( is_file($module_folder . $settings[$alias]['module_init']) ){
//if( is_admin() ) {
$current_module = array($alias => $this->cfg['modules'][$alias]);
require_once( $module_folder . $settings[$alias]['module_init'] );
//}
}
}
}
}
// order menu_order ascendent
ksort($this->cfg['menu_order']);
}
End rereceives value by reference, but result of function is not variable.
You could rewrite your code.
$array_keys = array_keys($settings);
$alias = (string)end($array_keys);
unset($array_keys);
Can someone help why my JSON file can't show? I beginner for JSON. This is my code, its only show blank document. I am learning this tutorial from this website http://contohprogramandroid.blogspot.com/2013/10/contoh-program-android-aplikasi-wisata.html. thank you so much.
this my image when running the code.
//this is the code webservice.php
<?php
class Database {
private $host = "localhost";
private $user = "root";
private $pass = "";
private $db = "wisata_jogja";
private $conn;
// constructor
function __construct() {
try{
$this->conn = new PDO( "mysql:host=".$this->host.";dbname=".$this->db, $this->user, $this->pass );
}catch( PDOException $e ) {
echo "error pdo $e";
}
}
public function showAllData( $table ) {
$sql ="SELECT * FROM $table";
$q = $this->conn->query( $sql ) or die( "Failed !!" );
while ( $r = $q->fetch( PDO::FETCH_ASSOC ) ) {
$data[] = $r;
}
return $data;
}
}
$database = new Database();
$response = array();
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
$response['location'] = array();
foreach ( $database->showAllData( 'lokasi' ) as $value ) {
$kode = array();
extract( $value );
$kode['id'] = $id;
$kode['nama'] = $nama;
$kode['alamat'] = $alamat;
$kode['gambar'] = $gambar;
$kode['lat'] = $lat;
$kode['lng'] = $lng;
array_push( $response['location'], $kode );
}
echo json_encode( $response );
}
?>
Your condition to output is this:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
Thus, the script won't output any JSON since condition is not met.
From your screenshot it is clear your are missing the GET parameters.
In your browser add the parameter to the url:
http://localhost/wisata/webservice.php?get=lokasi
It's always good to take alternative action when condition is not true.
You should always echo something just so you know what is going on:
if ( isset( $_GET['get'] ) && $_GET['get']=='lokasi' ) {
//..............
echo json_encode( $response );
}else{
echo "cannot output JSON data: parameter is missing!!;
}
Are you sure that you pass the GET variable "lokasi" to your script ?
Otherwise, it would not go through the if condition
if(isset($_GET['get'] ) && $_GET['get']=='lokasi')
You can check this by trying to dump the variable or any foobar data inside the if condition to verify your code goes that far, for instance :
if(isset($_GET['get'] ) && $_GET['get']=='lokasi') {
$response['location'] = array();
$myTest = array('test');
var_dump($myTest); // Should display something on screen
// The rest of your code here
I'm getting the following error you see below on my WordPress site (the weird part is it only appears if a user is logged in)... How can I fix it?
Warning: array_key_exists() [function.array-key-exists]: The first argument should be
either a string or an integer in wp-content/plugins/display-name-author-permalink/display-name-author-permalink.php on line 55
Here is the code:
class DisplayNameAuthorPermaLink {
var $users = array();
// Build an array of usernames and display names and increment duplicates for uniqueness
function __construct() {
$i = 1;
foreach ( get_users() as $user ) {
$display_name = $display_name = sanitize_title($user->display_name);
if ( in_array(sanitize_title($user->display_name), $this->users) ) {
$i++;
$display_name .= "-$i";
}
$this->users[sanitize_title($user->user_login)] = $display_name;
}
add_action('pre_get_posts', array(&$this, 'switch_author'));
add_filter('author_link', array(&$this, 'filter_author'), 10, 3);
}
// Switch the display name with the username so that we can populate the posts properly
// If the username was used in the call do a 404 template redirection
function switch_author() {
if ( ! is_author() )
return;
$author_name = get_query_var('author_name');
$key = array_search($author_name, $this->users);
if ( $key ) {
set_query_var('author_name', $key);
$author = get_user_by('login', $key);
set_query_var('author', $author->ID);
} else {
set_query_var('author_name', false);
set_query_var('author', false);
add_action('template_redirect', array(&$this, 'redirect_404'));
}
}
// Replace the username in author links generated in the theme with the users display name
function filter_author($link,$author_id,$author_nicename) {
if ( array_key_exists($author_nicename, $this->users) )
$link = str_replace($author_nicename,$this->users[$author_nicename], $link);
return $link;
}
// Redirect template to use 404 template
function redirect_404() {
include(get_404_template());
die();
}
}
// Instantiate the DisplayNameAuthorPermaLink class
$DisplayNameAuthorPermaLink = new DisplayNameAuthorPermaLink();