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?
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 build a custom location rule to be able to select a grand-parent page, yet without success... Here is my goal :
Show this field group if :
Page Grand-Parent -------- is equal to --------- page x
Anyone ?
Thank you !
Johan
ACF Documentation is a bit poor on the subject...
Here is the answer...
Simply copy theses lines to your functions.php...
Thanx to John Huebner who kindly helped on the ACF Forum...
add_filter('acf/location/rule_types', 'acf_location_rules_page_grandparent');
function acf_location_rules_page_grandparent($choices) {
$choices['Page']['page_grandparent'] = 'Page Grandparent';
return $choices;
}
add_filter('acf/location/rule_values/page_grandparent','acf_location_rules_values_page_grandparent');
function acf_location_rules_values_page_grandparent($choices) {
// this code is copied directly from
// render_location_values()
// case "page"
$groups = acf_get_grouped_posts(array(
'post_type' => 'page'
));
if (!empty($groups)) {
foreach(array_keys($groups) as $group_title) {
$posts = acf_extract_var($groups, $group_title);
foreach(array_keys($posts) as $post_id) {
$posts[$post_id] = acf_get_post_title($posts[$post_id]);
};
$choices = $posts;
}
}
// end of copy from ACF
return $choices;
}
add_filter('acf/location/rule_match/page_grandparent', 'acf_location_rules_match_page_grandparent', 10, 3);
function acf_location_rules_match_page_grandparent($match, $rule, $options) {
// this code is with inspiration from
// acf_location::rule_match_page_parent()
// with addition of adding grandparent check
if(!$options['post_id']) {
return false;
}
$post_grandparent = 0;
$post = get_post($options['post_id']);
if ($post->post_parent) {
$parent = get_post($post->post_parent);
if ($parent->post_parent) {
$post_grandparent = $parent->post_parent;
}
}
if (isset($options['page_parent']) && $options['page_parent']) {
$parent = get_post($options['page_parent']);
if ($parent->post_parent) {
$post_grandparent = $parent->post_parent;
}
}
if (!$post_grandparent) {
return false;
}
if ($rule['operator'] == "==") {
$match = ($post_grandparent == $rule['value']);
} elseif ($rule['operator'] == "!=") {
$match = ($post_grandparent != $rule['value']);
}
return $match;
}
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();
I have created quite big import script which is importing products from CSV to magento. I have one remaining issue to resolve.
I use dropdowns for attributes. Unfortunately I can't set values for those attributes for a single product.
What I did:
created attribute set [php],
added dropdown attribute with values to this set [php],
added new product in proper attribute set and tried to set value for attribute I have created.
I tried few methods, here is the one looking good for me:
private function setOrAddOptionAttribute($product, $arg_attribute, $arg_value) {
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model = Mage::getModel('eav/entity_attribute_source_table');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
// determine if this option exists
$value_exists = false;
foreach($options as $option) {
if ($option['label'] == $arg_value) {
$value_exists = true;
break;
}
}
// if this option does not exist, add it.
if (!$value_exists) {
$attribute->setData('option', array(
'value' => array(
'option' => array($arg_value,$arg_value)
)
));
$attribute->save();
}
$product->setData($arg_attribute, $arg_value);
$product->save();
}
Unfortunately it don't work. Any ideas? I'm using Magento 1.7.0.2
You can do it like this:
$attr_id = $this->attributeValueExists('manufacturer', 'Samsung');
$product->setData('manufacturer', $attr_id );
$product->save();
public function attributeValueExists($arg_attribute, $arg_value)
{
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model= Mage::getModel('eav/entity_attribute_source_table') ;
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attribute_table = $attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
foreach($options as $option)
{
if ($option['label'] == $arg_value)
{
return $option['value'];
}
}
return false;
}
Let me know if you have any questions.
Cordially.
I rewrote the initial function so it works for text and select fields:
public function setOrAddOptionAttribute($product, $arg_attribute, $arg_value) {
$attribute_model = Mage::getModel('eav/entity_attribute');
$attribute_options_model = Mage::getModel('eav/entity_attribute_source_table');
$attribute_code = $attribute_model->getIdByCode('catalog_product', $arg_attribute);
$attribute = $attribute_model->load($attribute_code);
$attributeType = $attribute->getFrontendInput();
if ($attributeType == 'select') {
$attribute_options_model->setAttribute($attribute);
$options = $attribute_options_model->getAllOptions(false);
// determine if this option exists
$value_exists = false;
foreach ($options as $option) {
if ($option['label'] == $arg_value) {
$value_exists = true;
break;
}
}
// if this option does not exist, add it.
if (!$value_exists) {
$attribute->setData('option', array(
'value' => array(
'option' => array($arg_value, $arg_value)
)
));
$attribute->save();
// Now get the option value for this newly created attribute value
$_product = Mage::getModel('catalog/product');
$attr = $_product->getResource()->getAttribute($arg_attribute);
if ($attr->usesSource()) {
$option['value'] = $attr->getSource()->getOptionId($arg_value);
}
}
$product->setData($arg_attribute, $option['value']);
} else {
$product->setData($arg_attribute, $arg_value);
}
}
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.