I am trying to improve the below switch statement. What's happening here is that the code is called multiple times based on an x amount of tokens found, so the below code runs once per token.
If the $post->ID is not found then a notification is sent to that token and the id gets added in the database.
This works however at some point it's stopping after around 40% of tokens checked presumably because the ID is found? Since I am on wordpress, I used the update_option to store the id in a table but perhaps an alternative approach can be used?
$os = $this->os;
switch ($os) {
case "iOS":
$iOS_pastPushSavedID = get_option( 'iOS_pastPushSavedID', $default = false);
if($post->ID != $iOS_pastPushSavedID) {
update_option( 'iOS_pastPushSavedID', $post->ID, no);
$sendPush = true;
//$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
$sendPush = false;
}
break;
case "Android":
$android_pastPushSavedID = get_option( 'android_pastPushSavedID', $default = false);
if($post->ID != $android_pastPushSavedID) {
//$title = ($os . '_New Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
update_option( 'android_pastPushSavedID', $post->ID, no);
$sendPush = true;
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $android_pastPushSavedID . ' / postID: ' . $post->ID);
$sendPush = false;
}
break;
case "Fire OS":
$fireos_pastPushSavedID = get_option( 'fireos_pastPushSavedID', $default = false);
if($post->ID != $fireos_pastPushSavedID) {
//$title = ($os . '_New Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
update_option( 'fireos_pastPushSavedID', $post->ID, no);
$sendPush = true;
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $fireos_pastPushSavedID . ' / postID: ' . $post->ID);
$sendPush = false;
}
break;
case "Safari":
$safari_pastPushSavedID = get_option( 'safari_pastPushSavedID', $default = false);
if($post->ID != $safari_pastPushSavedID) {
//$title = ($os . '_New Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
update_option( 'safari_pastPushSavedID', $post->ID, no);
$sendPush = true;
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $safari_pastPushSavedID . ' / postID: ' . $post->ID);
$sendPush = false;
}
break;
case "Chrome":
$chrome_pastPushSavedID = get_option( 'chrome_pastPushSavedID', $default = false);
if($post->ID != $chrome_pastPushSavedID) {
//$title = ($os . '_New Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
update_option( 'chrome_pastPushSavedID', $post->ID, no);
$sendPush = true;
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $chrome_pastPushSavedID . ' / postID: ' . $post->ID);
$sendPush = false;
}
break;
case "Firefox":
$firefox_pastPushSavedID = get_option( 'firefox_pastPushSavedID', $default = false);
if($post->ID != $firefox_pastPushSavedID) {
//$title = ($os . '_New Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
update_option( 'firefox_pastPushSavedID', $post->ID, no);
$sendPush = true;
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $firefox_pastPushSavedID . ' / postID: ' . $post->ID);
$sendPush = false;
}
break;
default:
$sendPush = false;
}
Unless I am misunderstanding your process, this is a very DRY / concise way to do it without the verbose switch/case block:
$os_opts=[
'iOS'=>'iOS',
'Android'=>'android',
'Fire OS'=>'fireos',
'Safari'=>'safari',
'Chrome'=>'chrome',
'Firefox'=>'firefox'
];
$os=$this->os;
$sendPush=false;
if(isset($os_opts[$os])){ // deny empty and invalid options
$os_opt="{$os_opts[$os]}_pastPushSavedID"; // build string for next two functions
if($post->ID!=get_option($os_opt,$default=false)){
update_option($os_opt,$post->ID,no);
$sendPush = true;
}
}
The $os_opts array has keys that match $os, and values that work with get_option() & update_option(). This will largely reduce code length, and make future modifications very easy to do.
Since the get_option() result is only used once, it doesn't make sense to declare it as a variable; just use it in the if condition.
The first parameter of get_option() and update_option() always end with the same substring. I makes sense to prepend the $os_opts[$os] value to it and declare it as a variable. The variable declaration is not necessary but my personal rule is; if you are going to use data more than once use a variable, if only once don't declare it.
You can do it like this. You can shorten your code like this.
$optionName='';//added some default values
$sendPush = false;;//added some default values
switch ($os) {
case "iOS":
$optionName='iOS_pastPushSavedID';
break;
case "Android":
$optionName='android_pastPushSavedID';
break;
case "Fire OS":
$optionName='fireos_pastPushSavedID';
break;
case "Safari":
$optionName='safari_pastPushSavedID';
break;
case "Chrome":
$optionName='chrome_pastPushSavedID';
break;
case "Firefox":
$optionName='firefox_pastPushSavedID';
break;
default:
$sendPush = false;
}
//this is operation which is common when $optionName is not empty.
if(!empty($optionName))
{
$optionData = get_option($optionName, $default = false);
if($post->ID != $optionData) {
update_option( $optionData, $post->ID, no);
$sendPush = true;
} else {
$sendPush = false;
}
}
Id write it more like this
function getOptionSpecifier() {
switch ($this->os) {
case "iOS":
return 'iOS_pastPushSavedID';
case "Android":
return 'android_pastPushSavedID';
case "Android":
return 'android_pastPushSavedID';
case "Fire OS":
return 'fireos_pastPushSavedID';
case "Safari":
return 'safari_pastPushSavedID';
case "Chrome":
return 'chrome_pastPushSavedID';
case "Firefox":
return 'firefox_pastPushSavedID';
default:
return '';
}
}
function send_notification($id) {
$optionSpecifier = getOptionSpecifier();
if ($optionSpecifier === NULL) {
return false;
}
$pastPushSavedID = get_option( $optionSpecifier, $default = false);
if($id != $pastPushSavedID) {
update_option( $optionSpecifier, $id, no);
return true;
//$title = ($os . '_New Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
} else {
//$title = ($os . '_Duplicate Push = ' . ' storedID: ' . $iOS_pastPushSavedID . ' / postID: ' . $post->ID);
return false;
}
}
$sendPush = send_notification($post->ID);
Multiple functions ala "separation of concerns" and so ...
Related
I am making a custom design which I will use with Wordpress (not a theme).
I created a function to get one, more or all embedded items in a post.
It works with <img>, <audio>, <video>, <iframe> and <a> tags, but it can be easily edited to get any html tag.
I use it in a loop:
if (have_posts()) : while (have_posts()) : the_post();
I tested it breefly for all tags and different amounts of items, and it works properly with all but iframes. You can get all other tags.
The function gets the src attribute and then recreates the whole element as needed, with additonal attributes if needed.
I'll post the whole function below, it is a little long.
So I would like to get the iframe source. I tried many different preg_match ways to get it but it did not work.
It's weird that it works with 'video' when it's either written first or in if part... but no iframes.
Since I am neither wordpress nor php developer, any other remarks - be it the security concerns or me doing something wrong - I would really appreciate to be told.
I would also like to know if I use properly ob_start(); and does it help to make this function easier for the server, if there are many visitors at the same time...
Also if there is a better way to make the arguments for the function...
I will add later a wrapper for each individual item, which is very useful (for example create a menu from posts links), and I hope that someone might find it useful, especially when those iframes get fixed.
This is the function:
// $universal_modifier for img size ('thumbnail') or link target '_blank'
// example: get_the_customized_post_content('link', 'all', 'link-class', '_blank');
// example: get_the_customized_post_content('image', 1, 'image-class', 'custom-thumbnail');
function get_the_customized_post_content($item_type = null, $items_num = null, $item_classes = null, $universal_modifier = null)
{
// PHP automatically flushes open output buffers when it reaches the end of a script
ob_start();
global $post;
$single_img = false;
if ($items_num) {
if ($item_type === 'image') {
if ($items_num === 1 && $universal_modifier) {
$single_img = true;
// this will get the featured image, which allows for getting
// the 'full' img with its sourceset
the_post_thumbnail($universal_modifier, array(
'class' => esc_attr($item_classes),
'alt' => esc_html(get_the_title())
));
} else {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = '';
$the_html_tag = '<img';
$close_tag = '';
}
} elseif ($item_type === 'audio') {
preg_match_all('/<audio.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->content, $item_src);
$additional_attr = 'preload=none loading=lazy controls';
$the_html_tag = '<audio';
$close_tag = '</audio>';
} elseif ($item_type === 'video') {
preg_match_all('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = 'loading=lazy frameborder=0 allowfullscreen';
$the_html_tag = '<iframe';
$close_tag = '</iframe>';
if (count($item_src[1]) === 0) {
echo 'Getting videos';
preg_match_all('/<video.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$additional_attr = 'preload=metadata loading=lazy controls';
$the_html_tag = '<video';
$close_tag = '</video>';
}
} elseif ($item_type === 'link') {
preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
preg_match_all('/<a.+>([^\'"]+)<\/a>/i', $post->post_content, $anchor_text);
if ($universal_modifier) {
$additional_attr = 'target=' . $universal_modifier;
} else {
$additional_attr = '';
}
$the_html_tag = '<a';
$close_tag = '</a>';
} else {
echo '<p class="' . esc_attr('not-found-info') . '">' . esc_html('Media not found...') . '</p>';
}
}
if ($single_img) {
$display_item = ob_get_clean();
echo $display_item;
} else {
if (count($item_src[1]) === 0) {
echo '<p class="' . esc_attr('not-found-info') . '">' . esc_html('Media not found...') . '</p>';
} else {
$num_of_items = count($item_src[0]);
if ($items_num === 'all') {
$items_total = $num_of_items;
} else {
$items_total = min($num_of_items, $items_num);
// get the smaller number of the two
}
if ($items_total > 0) {
for ($i = 0; $i < $items_total; $i++) {
if ($item_type === 'link') {
$source_type = 'href';
$item_content = $anchor_text;
} else {
$source_type = 'src';
$item_content = '';
}
$the_item = $the_html_tag . ' class="' . esc_attr($item_classes) . '" ' . $source_type . '="' . esc_url($item_src[1][$i]) . '" ' . esc_attr($additional_attr) . '>' . $item_content[1][$i] . $close_tag;
echo $the_item;
};
};
};
}
}
I had to change the function and I think it is better now. It works completely and is easy to use. The function is quite long…
I used var_dump($post->post_content) and saw that there were no iframes in the post content. They get echoed only in the output on the page.
Therefore I used get_media_embedded_in_content() with an appropriate media type to get the desired content, and then preg_match() to get what is needed.
When required only one image per post, the function gets the posts thumbnail 'full' (the post has to have the featured image – there is a plugin for an automatic creation) which returns the image with the sourceset, which makes it responsive. For more images per post it returns the full image size.
I added a wrapper for each individual item, if it's required. It's possible to add classes to it.
It is useful for wrapping images in a <a> tag – it automatically makes the href.
It’s also useful for wrapping links with <li> tags for making menus from the posts links (personally that was one of the most important things for me in this case).
If set link target, it will be used for all links – either links as items or links as wrappers.
Only images can be properly wrapped in <a> tag, others will be wrapped but will not have the href.
If $item_type set to 'video' it will find both <video> and <iframe> tags. It will search for <iframe> first, because it's most likely that everyone will post videos from external sources than self hosted videos.
<video> and <audio> will have controls.
<video> will have preload="metadata", and <audio> preload="none".
<iframe> will have frameborder="0" allowfullscreen.
All except the links will have loading="lazy".
I'm not sure yet if it will work for all of them with wordpress, but it makes no harm... and can be removed later if useless...
As far as I can see, I escaped all html/attribute/url outputs.
The function is called inside the loop, in the category page:
if (have_posts()) : while (have_posts()) : the_post();
get_the_customized_post_content(
$item_type = 'image',
$items_num = 'all',
$item_classes = 'item-image-class class-two',
$item_wrap = 'a',
$item_wrap_classes = 'item-wrap-class one-more-class',
$the_link_target = '_blank'
);
endwhile;
wp_reset_postdata();
endif;
or:
query_posts(array(
'category_name' => 'your-cat-name',
'posts_per_page' => 1
));
if (have_posts()) : while (have_posts()) : the_post();
get_the_customized_post_content(
$item_type = 'audio',
$items_num = 1,
$item_classes = 'item-audio-class',
$item_wrap = 'div',
$item_wrap_classes = 'item-wrap-class classs-two',
$link_target = false
);
endwhile;
wp_reset_postdata();
wp_reset_query();
endif;
$items_num can be 'all' or from 1 to as many as needed - if specified more items than the post has, it will return all the items the post has.
Anything that is not needed, make it false (… $item_wrap = false, …).
Sure there is a better way to write this, to write only those arguments one needs, and leaving out all that are false, but I do not know how to do it.
I would still like to hear the opinions of the wordpress/php developers, especially on the function's performance, and on the coding – I’m sure it can be written better…
Edit:
Improved preg_match_all for links creation.
Added multiple images alt tag.
Also you have to remove:
Featured Image width/height inline attributes
Featured Image Wordpress default classes
// remove Featured Image width/height inline attributes
function remove_img_size_attr($html)
{
$html = preg_replace('/(width|height)="\d+"\s/', "", $html);
return $html;
}
add_filter('post_thumbnail_html', 'remove_img_size_attr', 10);
add_filter('image_send_to_editor', 'remove_img_size_attr', 10);
// remove Featured Image classes
remove_action('begin_fetch_post_thumbnail_html', '_wp_post_thumbnail_class_filter_add');
all in functions.php
OK, the function (place it in functions.php):
function get_the_customized_post_content(
$item_type = null,
$items_num = null,
$item_classes = null,
$item_wrap = null,
$item_wrap_classes = null,
$link_target = null
) {
// PHP automatically flushes open output buffers when it reaches the end of a script
ob_start();
global $post;
$not_found_class = 'media-not-found'; // class for the p tag container for "Nothing found" info
if ($item_type && $items_num) {
if ($item_type === 'video') {
$the_item_media = get_media_embedded_in_content(apply_filters('the_content', get_the_content(), -1), array('video', 'iframe'));
$num_of_items = count($the_item_media);
} elseif ($item_type === 'audio') {
$the_item_media = get_media_embedded_in_content(apply_filters('the_content', get_the_content(), -1), array('audio'));
$num_of_items = count($the_item_media);
} elseif ($item_type === 'image') {
if ($items_num === 1) {
// this will get the featured image, which allows for getting
// the 'full' img with its sourceset
// it's buffered, otherwise it echos automatically
the_post_thumbnail('full', array(
'class' => esc_attr($item_classes),
'alt' => esc_attr(get_the_title())
));
$featured_img = ob_get_clean();
$the_item_url = get_the_post_thumbnail_url(get_the_ID(), 'full');
$num_of_items = 1;
} else {
preg_match_all('/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $item_src);
$the_item_media = $item_src[1];
$the_item_url = $item_src[1];
$the_title_attr = $item_src[1];
$num_of_items = count($the_item_media);
};
} elseif ($item_type === 'link') {
preg_match_all('/<a.+href=[\'"]([^\'"]+)[\'"].*>([^\'"]+)<\/a>/i', $post->post_content, $link_parts);
$num_of_items = count($link_parts[0]);
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Please enter the item type.') . '</p>';
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Please enter the item type and the number of items to return...') . '</p>';
};
if ($num_of_items > 0) {
if ($link_target) {
$link_target_window = 'target=' . esc_attr($link_target);
} else {
$link_target_window = '';
};
if ($items_num === 'all') {
$items_total = $num_of_items;
} else {
$items_total = min($num_of_items, $items_num);
// get the smaller number of the two
};
if ($item_type === 'image') {
if ($items_num === 1) {
if ($item_wrap) {
if ($item_wrap === 'a') {
echo '<a class="' . esc_attr($item_wrap_classes) . '" href="' . esc_url($the_item_url) . '" ' . $link_target_window . '>';
} else {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
}
};
echo $featured_img;
if ($item_wrap) {
echo '</' . $item_wrap . '>';
}
} else {
for ($i = 0; $i < $items_total; $i++) {
if ($item_wrap) {
if ($item_wrap === 'a') {
echo '<a class="' . esc_attr($item_wrap_classes) . '" href="' . esc_url($the_item_url[$i]) . '" ' . $link_target_window . '>';
} else {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
}
};
$img_src = pathinfo($item_src[1][$i]);
$img_alt_tag = $img_src['filename'];
$fix_filename = array();
$fix_filename[0] = '/-/';
$fix_filename[1] = '/_/';
$fix_filename[2] = '/\s\s+/';
$img_alt_tag = ucwords(preg_replace($fix_filename, ' ', $img_alt_tag));
echo '<img class="' . esc_attr($item_classes) . '" alt="' . esc_attr($img_alt_tag) . '" src="' . esc_url($item_src[1][$i]) . '" loading=' . esc_attr('lazy') . '>';
if ($item_wrap) {
echo '</' . $item_wrap . '>';
}
};
}
} elseif ($item_type === 'link') {
for ($i = 0; $i < $items_total; $i++) {
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
echo '<a class="' . esc_attr($item_classes) . '" href="' . esc_url($link_parts[1][$i]) . '" ' . esc_attr($link_target_window) . '>' . esc_html($link_parts[2][$i]) . '</a>';
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} elseif ($item_type === 'video') {
for ($i = 0; $i < $items_total; $i++) {
preg_match('/<iframe.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
if ($item_src[1]) {
echo '<iframe class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" frameborder="0" allowfullscreen></iframe>';
} else {
preg_match('/<video.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_src[1]) {
echo '<video class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" preload="metadata" controls></video>';
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
};
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} elseif ($item_type === 'audio') {
for ($i = 0; $i < $items_total; $i++) {
preg_match('/<audio.+src=[\'"]([^\'"]+)[\'"].*>/i', $the_item_media[$i], $item_src);
if ($item_wrap) {
echo '<' . $item_wrap . ' class="' . esc_attr($item_wrap_classes) . '">';
};
if ($item_src[1]) {
echo '<audio class="' . esc_attr($item_classes) . '" loading="lazy" src="' .
esc_url($item_src[1]) . '" preload="none" controls></audio>';
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
if ($item_wrap) {
echo '</' . $item_wrap . '>';
};
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Nothing found.') . '</p>';
};
} else {
echo '<p class="' . esc_attr($not_found_class) . '">' . esc_html('Media not found.') . '</p>';
};
};
I am using the Divi Theme.
The shortcode is working, however it is displaying directly under the header rather than where I place the shortcode within the Divi Builder.
I read more about WP shortcodes and it looked like we should be using return rather than echo, but when I change it to return it does not display at all on the page.
Thanks!
function breadcrumb() {
$delimiter = '»'; // delimiter between crumbs
$home = 'Home'; // text for the 'Home' link
$showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
$before = '<span class="current">'; // tag before the current crumb
$after = '</span>'; // tag after the current crumb
global $post;
$homeLink = get_bloginfo('url');
echo '<div id="crumbs">' . $home . ' ' . $delimiter . ' ';
if (is_single() && !is_attachment()) {
if (get_post_type() != 'post') {
$post_type = get_post_type_object(get_post_type());
$slug = $post_type->rewrite;
return '' . $post_type->labels->singular_name . '';
if ($showCurrent == 1) {
return ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
}
} else {
$cat = get_the_category();
$cat = $cat[0];
$cats = get_category_parents($cat, true, ' ' . $delimiter . ' ');
if ($showCurrent == 0) {
$cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
}
echo $cats;
if ($showCurrent == 1) {
echo $before . get_the_title() . $after;
}
}
} elseif (!is_single() && !is_page() && get_post_type() != 'post' && !is_404()) {
$post_type = get_post_type_object(get_post_type());
return $before . $post_type->labels->singular_name . $after;
} elseif (is_attachment()) {
$parent = get_post($post->post_parent);
$cat = get_the_category($parent->ID);
$cat = $cat[0];
return get_category_parents($cat, true, ' ' . $delimiter . ' ');
echo '' . $parent->post_title . '';
if ($showCurrent == 1) {
echo ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
}
} elseif (is_page() && !$post->post_parent) {
if ($showCurrent == 1) {
return $before . get_the_title() . $after;
}
} elseif (is_page() && $post->post_parent) {
$parent_id = $post->post_parent;
$breadcrumbs = array();
while ($parent_id) {
$page = get_page($parent_id);
$breadcrumbs[] = '' . get_the_title($page->ID) . '';
$parent_id = $page->post_parent;
}
$breadcrumbs = array_reverse($breadcrumbs);
for ($i = 0; $i < count($breadcrumbs); $i++) {
return $breadcrumbs[$i];
if ($i != count($breadcrumbs)-1) {
return ' ' . $delimiter . ' ';
}
}
if ($showCurrent == 1) {
return ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
}
}
return '</div>';
}
function breadcrumb() {
$delimiter = '»'; // delimiter between crumbs
$home = 'Home'; // text for the 'Home' link
$showCurrent = 1; // 1 - show current post/page title in breadcrumbs, 0 - don't show
$before = '<span class="current">'; // tag before the current crumb
$after = '</span>'; // tag after the current crumb
global $post;
$homeLink = get_bloginfo('url');
$bredcrumb = '<div id="crumbs">' . $home . ' ' . $delimiter . ' ';
if (is_single() && !is_attachment()) {
if (get_post_type() != 'post') {
$post_type = get_post_type_object(get_post_type());
$slug = $post_type->rewrite;
$bredcrumb .='' . $post_type->labels->singular_name . '';
if ($showCurrent == 1) {
$bredcrumb .=' ' . $delimiter . ' ' . $before . get_the_title() . $after;
}
} else {
$cat = get_the_category();
$cat = $cat[0];
$cats = get_category_parents($cat, true, ' ' . $delimiter . ' ');
if ($showCurrent == 0) {
$cats = preg_replace("#^(.+)\s$delimiter\s$#", "$1", $cats);
}
$bredcrumb .= $cats;
if ($showCurrent == 1) {
$bredcrumb .= $before . get_the_title() . $after;
}
}
} elseif (!is_single() && !is_page() && get_post_type() != 'post' && !is_404()) {
$post_type = get_post_type_object(get_post_type());
$bredcrumb .= $before . $post_type->labels->singular_name . $after;
} elseif (is_attachment()) {
$parent = get_post($post->post_parent);
$cat = get_the_category($parent->ID);
$cat = $cat[0];
$bredcrumb .= get_category_parents($cat, true, ' ' . $delimiter . ' ');
$bredcrumb .= '' . $parent->post_title . '';
if ($showCurrent == 1) {
$bredcrumb .= ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
}
} elseif (is_page() && !$post->post_parent) {
if ($showCurrent == 1) {
$bredcrumb .= $before . get_the_title() . $after;
}
} elseif (is_page() && $post->post_parent) {
$parent_id = $post->post_parent;
$breadcrumbs = array();
while ($parent_id) {
$page = get_page($parent_id);
$breadcrumbs[] = '' . get_the_title($page->ID) . '';
$parent_id = $page->post_parent;
}
$breadcrumbs = array_reverse($breadcrumbs);
for ($i = 0; $i < count($breadcrumbs); $i++) {
$bredcrumb .= $breadcrumbs[$i];
if ($i != count($breadcrumbs)-1) {
$bredcrumb .= ' ' . $delimiter . ' ';
}
}
if ($showCurrent == 1) {
$bredcrumb .= ' ' . $delimiter . ' ' . $before . get_the_title() . $after;
}
}
$bredcrumb .= '</div>';
echo $bredcrumb;
return $bredcrumb;
I have a method that updated fields in a table. Its used to update three tables, invoices invoice_items and payments All three tables have the same field to be updated. When the below code runs, the multi_checked() method runs for the first two times, but not for the third time and It's not obvious to me as to why. Any Ideas?
Method Call:
elseif (isset($_POST[$mod . '-del']) && count($check) > 0) {
$state = multi_checked(
$check,
'UPDATE ' . $db['database'] . '.invoices SET deleted="Y"',
EVENT_DEL,
'Invoice [' . $c . '] deleted',
'Please select at least one item',
FALSE,
'SELECT id FROM ' . $db['database'] . '.invoices'
);
$state = multi_checked(
$check,
'UPDATE ' . $db['database'] . '.payments SET deleted="Y"',
EVENT_DEL,
'Payment [' . $c . '] deleted',
'Please select at least one item',
TRUE,
'SELECT id FROM ' . $db['database'] . '.payments',
null,
"id_invoice"
);
$state = multi_checked(
$check,
'UPDATE ' . $db['database'] . '.invoice_items SET deleted="Y"',
EVENT_DEL,
'Invoice Item [' . $c . '] deleted',
'Please select at least one item',
TRUE,
'SELECT id FROM ' . $db['database'] . '.invoice_items',
null,
"id_invoice"
);
} # Clear Export timestamps
the multi_checked method is described as follows:
function multi_checked(
$check,
$query,
$event_type,
$event_desc,
$none = 'Please select at least one item',
$redirect = TRUE,
$meta_query = NULL,
$success_msg = NULL,
$field = "id"
) {
global $db, $mod;
$batch_count = count($check);
$meta_data = NULL;
if ($batch_count == 0) {
add_msg($none);
return (0);
} else {
$changed = 0;
$ref = load_array('SELECT MAX(id) FROM ' . $db['database'] . '.eventlog'); # batch id
foreach ($check As $c) {
if ($meta_query != NULL) {
$meta_data = load_array($meta_query . ' WHERE id' . $field . '="' . $c . '"');
if ($meta_data != NULL) $meta_data = ' (' . $meta_data . ')';
}
$q = $query . ' WHERE ' . $field . '="' . $c . '"';
$z = $query . ' WHERE ' . $field . '="' . $c . '"';
$g = "asf";
if (run_query($query . ' WHERE ' . $field . '="' . $c . '"') == 0) {
eventlog($db['database'], $event_type, $mod, $c, uid(), '[Batch #' . $ref . '] ' . $event_desc . $meta_data, uname());
$changed++;
} else {
eventlog($db['database'], $event_type, $mod, $c, uid(), '[Batch #' . $ref . '] FAIL: ' . $event_desc . $meta_data, uname(), FALSE, FALSE);
}
}
# Check for errors
if ($changed != $batch_count) {
add_error($changed . ' of ' . $batch_count . ' items processed - you may need to check the system log for details');
} # Success!
else {
$message = ($changed . ' item' . ($changed > 1 ? 's' : NULL) . ' processed successfully');
if ($changed > 1) { # log batch summary
#mysql_query("FLUSH QUERY CACHE");
eventlog($db['database'], $event_type, $mod, 0, uid(), '[Batch #' . $ref . '] ' . $changed . ' records processed', uname());
}
# Redirect
if ($redirect) {
header('Location: ?m=' . $mod . '&changed=' . $changed . '&message=' . $success_msg);
exit;
} else {
add_msg($message);
}
}
return ($changed);
}
}
The second call to multi_check has $redirect parameter set to TRUE - so the function redirects, preventing the script to call the function the third time...
I have strange problem with PHP. When I set the string like '<' and if I make new string with few strings then when is go to '<' is stop to working and go to next row of the script
$a = new SomeObject();
$a->where('id', 13332, "<");
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '>?';
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '<?';
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '=?';
} else {
$this->_where = ' WHERE ' . $column . $operator . '?';
}
$this->_where = ' WHERE ' . $column . chr(0x3c) . '?';
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
And the result is:
1< WHERE id c
And my question is why less < is cannot get like string. The > and = operators is OK. But the < just is not recognize. What I'm doing wrong?
Remove one line and it will work (test one below yourself):-
<?php
error_reporting(E_ALL); //check all type of errors
ini_set('display_errors',1); // display those if any happen
$a = new SomeObject();
$a->where('id', 13332, "<");
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '> ?'; // added space
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '< ?'; // added space
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '= ?'; // added space
} else {
$this->_where = ' WHERE ' . $column . $operator . '?';
}
//$this->_where = ' WHERE ' . $column . chr(0x3c) . '?'; remove this line
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
Note:-
Reason for not working:-
You have to add spaces too to make it correct(commented by #RiggsFolly) (For browser showing sake)
You are just over-writing your conditions. (commented and example by #JonStirling :- https://3v4l.org/vCO5Z) (for working purpose)
In this line:
$this->_where = ' WHERE ' . $column . chr(0x3e) . '?';
you overwrite your all previous changes so no wonder you can not see right result
Please try with this function and let me know will it gives you desired output
public function where($column, $param, $operator = '=') {
echo strlen($operator);
if (isset($column) && strlen($operator) > 0) {
echo $operator;
if ($operator === '>') {
$this->_where = ' WHERE ' . $column . '> ?';
} else if ($operator == '<') {
$this->_where = ' WHERE ' . $column . '< ?';
} else if ($operator === '=') {
$this->_where = ' WHERE ' . $column . '= ?';
} else {
$this->_where = ' WHERE ' . $column . $operator . ' ?';
}
if($this->_where != '')
{
$this->_where .= ' and ' . $column . chr(0x3e) . ' ?';
}
else
{
$this->_where = ' WHERE ' . $column . chr(0x3e) . ' ?';
}
echo '<br/>' . $this->_where . '<br/>';
} else {
throw new \Exception('We need to have $column variable like string and $param like Param!', 500);
}
echo '<br/>c';
}
Recently we've been creating a website for our business using a purchased WP theme (Jupiter) that my boss, the owner, has had a few very particular modifications he's wanted (some for reasons I don't understand) and given I have working knowledge of HTML and CSS, and very very basic PHP knowledge, I have attempted and been able to make all his customizations except one:
The theme is designed to be responsive, and as such, the custom portfolio gallery style (which appears like an image gallery on computers: http://14d.mercysou.server312.com/photos) will progressively shrink on different devices so that by the time you are down to a smartphone, only 1 column of images will show up and you can scroll down. My supervisor would like it to be customized so that regardless of screen size, even on phones, there is at minimum 2 columns of images across the screen at all times. The PHP for this portfolio gallery (called "masonry") is as follows:
<?php
function mk_portfolio_masonry_loop(&$r, $atts)
{
global $post;
extract($atts);
global $mk_options;
$output = '';
$terms = get_the_terms(get_the_id(), 'portfolio_category');
$terms_slug = array();
$terms_name = array();
if (is_array($terms)) {
foreach ($terms as $term) {
$terms_slug[] = $term->slug;
$terms_name[] = '<span>' . $term->name . '</span>';
}
}
$post_type = get_post_meta($post->ID, '_single_post_type', true);
$post_type = !empty($post_type) ? $post_type : 'image';
$link_to = get_post_meta(get_the_ID(), '_portfolio_permalink', true);
$hover_overlay_value = get_post_meta($post->ID, '_hover_skin', true);
$hover_overlay = !empty($hover_overlay_value) ? (' style="background-color:' . $hover_overlay_value . '"') : '';
$column = get_post_meta(get_the_ID(), '_masonry_img_size', true);
$column = !(empty($column)) ? $column : 'x_x';
switch ($column) {
case 'x_x':
$width = 300;
$height = 300;
break;
case 'two_x_x': //
$width = 600;
$height = 300;
break;
case 'three_x_x':
$width = 900;
$height = 300;
break;
case 'four_x_x':
$width = 1200;
$height = 300;
break;
case 'x_two_x':
$width = 300;
$height = 600;
break;
case 'two_x_two_x':
$width = 600;
$height = 600;
break;
case 'three_x_two_x':
$width = 900;
$height = 600;
break;
case 'four_x_two_x':
$width = 1200;
$height = 600;
break;
default:
$width = 300;
$height = 300;
break;
}
$lightbox_full_size = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$permalink = '';
if (!empty($link_to)) {
$link_array = explode('||', $link_to);
switch ($link_array[0]) {
case 'page':
$permalink = get_page_link($link_array[1]);
break;
case 'cat':
$permalink = get_category_link($link_array[1]);
break;
case 'portfolio':
$permalink = get_permalink($link_array[1]);
break;
case 'post':
$permalink = get_permalink($link_array[1]);
break;
case 'manually':
$permalink = $link_array[1];
break;
}
}
if ($ajax == 'true' || empty($permalink)) {
$permalink = get_permalink();
}
$output .= '<article id="' . get_the_ID() . '" class="mk-portfolio-item mk-portfolio-masonry-item masonry-'.$item_id.' mk-isotop-item ' . $hover_scenarios . '-hover size_' . $column . ' portfolio-' . $post_type . ' ' . implode(' ', $terms_slug) . '">';
$image_src_array = wp_get_attachment_image_src(get_post_thumbnail_id(), 'full', true);
$image_src = bfi_thumb($image_src_array[0], array(
'width' => $width * $image_quality,
'height' => $height * $image_quality
));
$item_bg_color_value = get_post_meta($post->ID, '_hover_skin', true);
$item_bg_color = !empty($item_bg_color_value) ? (' background-color:' . $item_bg_color_value . '!important') : '';
$output .= '<div style="margin:0 ' . ($grid_spacing / 2) . 'px ' . $grid_spacing . 'px;" class="item-holder">';
//$output .= ($hover_scenarios == 'fadebox' || $hover_scenarios == 'none') ? '<a class="project-load" data-post-id="' . get_the_ID() . '" href="' . $permalink . '">' : '';
$output .= '<div class="featured-image">';
$output .= '<img alt="' . get_the_title() . '" class="item-featured-image" title="' . get_the_title() . '" src="' . mk_thumbnail_image_gen($image_src, $width, $height) . '" itemprop="image" />';
if ($hover_scenarios == 'fadebox') {
$output .= '<div class="hover-overlay gradient"' . $hover_overlay . '></div>';
} else {
if ($hover_scenarios == 'zoomout') {
$output .= '<div class="image-hover-overlay" style="' . $item_bg_color . '"></div>';
} else {
$output .= '<div class="image-hover-overlay"></div>';
}
}
if ($hover_scenarios == 'fadebox') {
$output .= '<div class="grid-hover-icons">';
if ($post_type == 'image' || $post_type == '') {
$output .= '<a rel="portfolio-grid" title="' . get_the_title() . '" data-fancybox-group="portfolio-masonry-item" class="zoom-badge mk-lightbox" href="' . $image_src_array[0] . '"><i class="mk-jupiter-icon-plus-circle"></i></a>';
} else if ($post_type == 'video') {
$video_id = get_post_meta($post->ID, '_single_video_id', true);
$video_site = get_post_meta($post->ID, '_single_video_site', true);
$video_url = '';
if ($video_site == 'vimeo') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://vimeo.com/' . $video_id . '?autoplay=0';
} elseif ($video_site == 'youtube') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://www.youtube.com/watch?v=' . $video_id . '?autoplay=0';
} elseif ($video_site == 'dailymotion') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://www.dailymotion.com/video/' . $video_id . '?logo=0';
}
$output .= '<a title="' . get_the_title() . '" class="video-badge mk-lightbox" data-fancybox-group="portfolio-masonry-item" href="' . $video_url . '"><i class="mk-jupiter-icon-plus-circle"></i></a>';
}
$output .= '</div>';
}
if ($hover_scenarios == 'light-zoomin' ) {
$output .= '<div class="grid-hover-icons">';
if ($post_type == 'image' || $post_type == '') {
$output .= '<a rel="portfolio-grid" title="' . get_the_title() . '" data-fancybox-group="portfolio-masonry-item" class="zoom-badge mk-lightbox" href="' . $image_src_array[0] . '"><i class="mk-jupiter-icon-plus-circle"></i></a>';
} else if ($post_type == 'video') {
$video_id = get_post_meta($post->ID, '_single_video_id', true);
$video_site = get_post_meta($post->ID, '_single_video_site', true);
$video_url = '';
if ($video_site == 'vimeo') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://vimeo.com/' . $video_id . '?autoplay=0';
} elseif ($video_site == 'youtube') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://www.youtube.com/watch?v=' . $video_id . '?autoplay=0';
} elseif ($video_site == 'dailymotion') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://www.dailymotion.com/video/' . $video_id . '?logo=0';
}
$output .= '<a title="' . get_the_title() . '" class="video-badge mk-lightbox" data-fancybox-group="portfolio-masonry-item" href="' . $video_url . '"><i class="mk-jupiter-icon-plus-circle"></i></a>';
}
$output .= '</div>';
}
if ($hover_scenarios != 'fadebox' && $hover_scenarios != 'light-zoomin' && $hover_scenarios != 'none') {
$output .= '<div class="grid-hover-icons">';
if ($post_type == 'image' || $post_type == '') {
$output .= '<a data-fancybox-group="portfolio-grid" title="' . get_the_title() . '" class="zoom-badge mk-lightbox" href="' . $lightbox_full_size[0] . '"><i class="mk-jupiter-icon-plus-circle"></i></a>';
} else if ($post_type == 'video') {
$video_id = get_post_meta($post->ID, '_single_video_id', true);
$video_site = get_post_meta($post->ID, '_single_video_site', true);
$video_url = '';
if ($video_site == 'vimeo') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://vimeo.com/' . $video_id . '?autoplay=0';
} elseif ($video_site == 'youtube') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://www.youtube.com/watch?v=' . $video_id . '?autoplay=0';
} elseif ($video_site == 'dailymotion') {
$video_url = 'http' . ((is_ssl()) ? 's' : '') . '://www.dailymotion.com/video/' . $video_id . '?logo=0';
}
$output .= '<a title="' . get_the_title() . '" class="video-badge mk-lightbox" href="' . $video_url . '"><i class="mk-jupiter-icon-plus-circle"></i></a>';
}
$output .= '</div>';
}
if ($hover_scenarios != 'none') {
$output .= ($hover_scenarios == 'slidebox') ? '<div class="portfolio-meta"' . $hover_overlay . '>' : '<div class="portfolio-meta">';
$output .= '<h3 class="the-title">' . get_the_title() . '</h3><div class="clearboth"></div>';
if ($meta_type == 'category') {
$output .= '<div class="portfolio-categories">' . implode(', ', $terms_name) . ' </div>';
} else {
$output .= '<time class="portfolio-date" datetime="' . get_the_date() . '">' . get_the_date() . '</time>';
}
$output .= '</div><!-- Portfolio meta -->';
}
$output .= '</div><!-- Featured Image -->';
//$output .= ($hover_scenarios == 'fadebox' || $hover_scenarios == 'none') ? '</a><!-- project load -->' : '';
$output .= '</div>';
$output .= '</article>' . "\n\n\n";
return $output;}
I'm aware that what I need to modify in order to achieve my desired 2 column style is on and around line 30, particularly this part:
$column = get_post_meta(get_the_ID(), '_masonry_img_size', true);
$column = !(empty($column)) ? $column : 'x_x';
switch ($column) {
case 'x_x':
$width = 300;
$height = 300;
break;
case 'two_x_x': //
$width = 600;
$height = 300;
break;
case 'three_x_x':
$width = 900;
$height = 300;
break;
case 'four_x_x':
$width = 1200;
$height = 300;
break;
case 'x_two_x':
$width = 300;
$height = 600;
break;
case 'two_x_two_x':
$width = 600;
$height = 600;
break;
case 'three_x_two_x':
$width = 900;
$height = 600;
break;
case 'four_x_two_x':
$width = 1200;
$height = 600;
break;
default:
$width = 300;
$height = 300;
break;
}
I have read several tutorials and attempted my best to create a 2 column function and use that in the switch instead but I fear that my knowledge of PHP is just not good enough to properly implement this. Any thoughts, suggestions, or help would be greatly appreciated as I am no professional, we don't have the budget to hire one, and yet the responsibility has fallen on me as I'm the only somewhat web literate guy in the office.
seeing as it is responsive it stands to reason that its the css that forces the 2 columns. I can't be certain because i cant see the code but i would do this with css media queries, making the items in the columns 100% width when reaching a specific screen width. if this is the case try and find the code that does that and make the width 50%.
I cannot guarantee this will work without seeing the whole code but its a start for you. the php doesn't know the screen width.