Warning: array_key_exists() on WordPress site. How do I fix? - php

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();

Related

WordPress passing vairiable from shortcode into another function

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;
}

Hwo to fix error in WordPress Trying to get property 'ID' of non-object in functions.php

I created a custom functionality in WooCommerce and it is about the filtering. If you choose any filter from the sidebar of the eshop and then browse to a single product page you'll have navigation arrows based on your previous selection filtering. It works fine but only in a specific product i get the error
Notice: Trying to get property 'ID' of non-object in functions.php on line 355
function filter_single_post_pagination($output, $format, $link, $post){
$variable = $_GET;
if (count($variable) == 0) {
$url = get_permalink($post->ID);
if (isset($post->ID)) {
if('previous_post_link' === current_filter()){
return "<a href='$url' rel='next'>→</a>";
} else {
return "<a href='$url' rel='prev'>←</a>";
}
}
}
else {
$pids = array();
$product_ids = "";
foreach ($variable as $key => $value) {
$product_ids .= $key."&";
array_push($pids, $key);
}
global $product;
$id = $product->get_id();
$key_val = array_search($id,$pids);
$custom_link = "?".$product_ids;
if (isset($pids[$key_val+1])) {
if('previous_post_link' === current_filter()){
$rel = 'next';
$next_url = get_permalink($pids[$key_val+1]);
return "<a href='$next_url.$custom_link' rel='$rel'>→</a>";
}
}
if (isset($pids[$key_val-1])) {
if('next_post_link' === current_filter()){
$rel = 'prev';
$previous_url = get_permalink($pids[$key_val-1]);
return "<a href='$previous_url.$custom_link' rel='$rel'>←</a>";
}
}
}
}

Prefix and suffix HTML to items in PHP array

I have a PHP array being created from a list of options in a WordPress plugin ($checklist) and I need to add some HTML to it.
public function get_the_checklist() {
// The default list
$options = get_option('uc_settings');
if (isset($options['list'])) {
$checklist = $options['list'];
// Split the list by line break
$checklist = preg_split('/[\n\r]+/', ($options['list']));
// Convert to associative array
foreach($checklist as $item) {
$item = '<div>'.$item.'</div>';
$default_checklist[] = array(
'text' => $item
);
}
}
// Are we resetting to default?
$reset = isset($_GET['reset_list']) ? true : false;
if ($reset) {
$user_id = get_current_user_id();
update_user_meta($user_id, 'user_checklist', $default_checklist);
return $default_checklist;
}
// Is user logged in?
if (is_user_logged_in()) {
$user_id = get_current_user_id();
// Look for custom list
$user_checklist = get_user_meta($user_id, 'user_checklist', true);
if (!$user_checklist) {
$user_checklist = $default_checklist;
}
} else {
return $default_checklist;
}
return $user_checklist;
}
I have done the following and it does add the prefix and suffix but it is showing as text and not HTML.
foreach($checklist as $item) {
$item = '<div>'.$item.'</div>';
$default_checklist[] = array(
'text' => $item
);
}
Here is an example of the output of the PHP above:
How can I make the text output as HTML instead?

why get 404 error when the PHP echo position is changed

<?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

foreach expects an array in a wordpress template

Okay I have installed a theme in wordpress that returns a few errors.
Warning: Invalid argument supplied for foreach() in /home/mvprop/public_html/wp-content/themes/yoo_vox_wp/warp/systems/wordpress.3.0/helpers/system.php on line 339
This problem is resolved on these forums
but I can't understand what the last post is about. The guy posts a bunch of random code that solves the problem. He doesn't specify where it's from or where to put it. Just pastes code that doesn't seem to have to do with anything.
line 334 to the end of the file
function getWidgets($position = null) {
if (empty($this->widgets)) {
foreach (wp_get_sidebars_widgets() as $pos => $ids) {
$this->widgets[$pos] = array();
foreach ($ids as $id) {
$this->widgets[$pos][$id] = $this->getWidget($id);
}
}
}
if (!is_null($position)) {
return isset($this->widgets[$position]) ? $this->widgets[$position] : array();
}
return $this->widgets;
}
/*
Function: displayWidget
Checks if a widget should be displayed
Returns:
Boolean
*/
function displayWidget($widget) {
if (!isset($widget->options['display']) || in_array('*', $widget->options['display'])) return true;
foreach ($this->getQuery() as $q) {
if (in_array($q, $widget->options['display'])) {
return true;
}
}
return false;
}
/*
Function: overrideConfig
Overrides default config based on page
Returns:
Void
*/
function overrideConfig() {
if (!count($this->config_overrides)) return;
foreach ($this->getQuery() as $q) {
if (isset($this->config_overrides[$q])) {
$this->warp->config->parseString($this->config_overrides[$q]);
}
}
}
/*
Function: isBlog
Returns:
Boolean
*/
function isBlog() {
return true;
}
/*
Function: isPreview
Checks for default widgets in theme preview
Returns:
Boolean
*/
function isPreview($position) {
// preview postions
$positions = array('logo', 'right');
return is_preview() && in_array($position, $positions);
}
/*
Function: ajaxSearch
Ajax search callback
Returns:
String
*/
function ajaxSearch(){
global $wp_query;
$result = array('results' => array());
$query = isset($_REQUEST['s']) ? $_REQUEST['s']:"";
if (strlen($query)>=3) {
$wp_query->query_vars['s'] = $query;
$wp_query->is_search = true;
foreach ($wp_query->get_posts() as $post) {
$content = !empty($post->post_excerpt) ? strip_tags(do_shortcode($post->post_excerpt)) : strip_tags(do_shortcode($post->post_content));
if (strlen($content) > 255) {
$content = substr($content, 0, 254).'...';
}
$result['results'][] = array(
'title' => $post->post_title,
'text' => $content,
'url' => get_permalink($post->ID)
);
}
}
die(json_encode($result));
}
/*
Function: _adminInit
Admin init actions
Returns:
Void
*/
function _adminInit() {
if ((defined('DOING_AJAX') && DOING_AJAX) && isset($_POST['warp-ajax-save'])) {
// update option values
foreach ($_POST as $option => $value) {
if (preg_match('/^(warp_|'.preg_quote($this->prefix, '/').')/', $option)) {
update_option($option, $value);
}
}
die();
}
wp_enqueue_script('warp-admin', rtrim(get_bloginfo('template_url'),'/').'/warp/systems/wordpress.3.0/js/wp-admin.js', false, '1.0');
add_action('wp_ajax_save_nav_settings', array($this,'_save_nav_settings'));
add_action('wp_ajax_get_nav_settings', array($this,'_get_nav_settings'));
}
/*
Function: _adminHead
Admin head actions
Returns:
Void
*/
function _adminHead() {
// init vars
$path =& $this->getHelper('path');
$head[] = '<link rel="stylesheet" href="'.$path->url('warp:systems/wordpress.3.0/css/admin.css').'" type="text/css" />';
$head[] = '<script type="text/javascript" src="'.$path->url('warp:systems/wordpress.3.0/js/admin.js').'"></script>';
echo implode("\n", $head);
}
/*
Function: _adminMenu
Admin menu actions
Returns:
Void
*/
function _adminMenu() {
// init vars
$path =& $this->getHelper('path');
$name = $this->xml->document->getElement('name');
$icon = $path->url('warp:systems/wordpress.3.0/images/yoo_icon_16.png');
if (function_exists('add_object_page')) {
add_object_page('', $name->data(), 8, 'warp', false, $icon);
} else {
add_menu_page('', $name->data(), 8, 'warp', false, $icon);
}
add_submenu_page('warp', 'Theme Options', 'Theme Options', 8, 'warp', array($this, '_adminThemeOptions'));
add_submenu_page('warp', 'Widget Options', 'Widget Options', 8, 'warp_widget', array($this, '_adminWidgetOptions'));
}
/*
Function: _adminThemeOptions
Render admin theme options layout
Returns:
Void
*/
function _adminThemeOptions() {
// init vars
$path =& $this->getHelper('path');
$xml =& $this->getHelper('xml');
$http =& $this->getHelper('http');
$check =& $this->getHelper('checksum');
// get warp xml
$warp_xml = $xml->load($path->path('warp:warp.xml'), 'xml', true);
// update check
$update = null;
if ($url = $warp_xml->document->getElement('updateUrl')) {
// get template info
$template = get_template();
$version = $this->xml->document->getElement('version');
$url = sprintf('%s?application=%s&version=%s&format=raw', $url->data(), $template, $version->data());
// only check once a day
if (get_option($this->prefix.'update_check') != date('Y-m-d').' '.$version->data()) {
if ($request = $http->get($url)) {
update_option($this->prefix.'update_check', date('Y-m-d').' '.$version->data());
update_option($this->prefix.'update_data', $request['body']);
}
}
// decode update response
$update = json_decode(get_option($this->prefix.'update_data'));
}
// verify theme files
if (($checksums = $path->path('template:checksums')) && filesize($checksums)) {
$check->verify($path->path('template:'), $log);
} else {
$log = false;
}
echo $this->warp->template->render('admin/theme_options', array('xml' => $this->xml, 'warp_xml' => $warp_xml, 'update' => $update, 'checklog' => $log));
}
/*
Function: _adminWidgetOptions
Render admin widget options layout
Returns:
Void
*/
function _adminWidgetOptions() {
// get position settings
$position_settings = $this->warp->config->get('warp.positions');
// get module settings
$module_settings = array();
$settings = $this->xml->document->getElement('modulesettings');
foreach ($settings->children() as $setting) {
$module_settings[$setting->attributes('name')] = $setting;
}
echo $this->warp->template->render('admin/widget_options', compact('position_settings', 'module_settings'));
}
/*
Function: getMenuItemOptions
Retrieve menu by id
Parameters:
$id - Menu Item ID
Returns:
Array
*/
function getMenuItemOptions($id) {
$menu_settings = array(
'columns' => 1,
'columnwidth' => -1,
'image' => ''
);
if (isset($this->menu_item_options[$id])) {
$menu_settings = array_merge($menu_settings, $this->menu_item_options[$id]);
}
return $menu_settings;
}
/*
Function: _save_nav_settings
Saves menu item settings
Returns:
Void
*/
function _save_nav_settings() {
if (isset($_POST['menu-item'])) {
$menu_item_settings = $this->menu_item_options;
foreach ($_POST['menu-item'] as $itemId=>$settings){
$menu_item_settings[$itemId] = $settings;
}
update_option($this->prefix.'menu-items', $menu_item_settings);
$this->menu_item_options = $menu_item_settings;
}
die();
}
/*
Function: _get_nav_settings
Returns menu item settings as json
Returns:
Boolean
*/
function _get_nav_settings() {
die(json_encode($this->menu_item_options));
}
}
/*
Function: mb_strpos
mb_strpos function for servers not using the multibyte string extension
*/
if (!function_exists('mb_strpos')) {
function mb_strpos($haystack, $needle, $offset = 0) {
return strpos($haystack, $needle, $offset);
}
}
Basically what this warning message tells you is that the variable you're passing into your foreach is not an array or object. Make sure your variable is valid by testing it ( is_array($var) or is_object($var) ) or placing this block of code in a try-catch.
If $var is supposed to be an array, you should also initialize it just to be certain.
$var = Array();
.
. // code that may change the data type of $var
.
if (is_array($var)) {
foreach($var as $v) {
//code here
}
}
From the manual at http://php.net/manual/en/control-structures.foreach.php:
The foreach construct provides an easy way to iterate over arrays. foreach works only on arrays and objects, and will issue an error when you try to use it on a variable with a different data type or an uninitialized variable.

Categories