I have a woocommerce and i use berocket product filters plugin. The plugin has a button that purge cache in its setting page. I want to create a scheduled task from inside plesk that hosts the woocommerce that trigger that function every 30 minutes.
I have located,i think, the function that use the above button but i need help creating the scheduled task.
I have the function in the main.php file located in the root directory of the plugin.
public function section_purge_cache ( $item, $options ) {
$html = '<tr>
<th scope="row">' . __('Purge Cache', 'BeRocket_AJAX_domain') . '</th>
<td>';
$old_filter_widgets = get_option('widget_berocket_aapf_widget');
if( ! is_array($old_filter_widgets) ) {
$old_filter_widgets = array();
}
foreach ($old_filter_widgets as $key => $value) {
if (!is_numeric($key)) {
unset($old_filter_widgets[$key]);
}
}
$html .= '
<span class="button berocket_purge_cache" data-time="'.time().'">
<input class="berocket_purge_cache_input" type="hidden" name="br_filters_options[purge_cache_time]" value="'.br_get_value_from_array($options, 'purge_cache_time').'">
' . __('Purge Cache', 'BeRocket_AJAX_domain') . '
</span>
<p>' . __('Clear attribute/custom taxonomy cache for plugin', 'BeRocket_AJAX_domain') . '</p>
<script>
jQuery(".berocket_purge_cache").click(function() {
var $this = jQuery(this);
if( ! $this.is(".berocket_ajax_sending") ) {
$this.attr("disabled", "disabled");
var time = $this.data("time");
$this.parents(".br_framework_submit_form").addClass("br_reload_form");
$this.find(".berocket_purge_cache_input").val(time).submit();
}
});
</script>
</td>
</tr>';
return $html;
}
Since this is a product from BeRocket i would suggest you to ask this question in the support forum of the plugin itself.
Here you go: https://wordpress.org/support/plugin/woocommerce-ajax-filters/
Related
I am trying to get the info stored in the array updated to the database. I cannot seem to get it to work. Any help will be appreciated. Thanks.
In the Config Class:
function update_cfg(array $upd)
{
if(is_array($upd))
{
$sql = array();
foreach($upd as $column => $info)
{
if(isset($info) && $column != 'update_cfg')
{
$sql[] = "`" . $column . "`='" . $info . "'";
}
}
if(is_array($sql))
{
$result = $this->Sys->db->query("UPDATE `dj_settings` SET " . implode(', ', $sql));
if($result)
{
unset($sql);
return TRUE;
}
else
{
unset($sql);
return FALSE;
}
}
}
}
Script:
<?php
global $Sys;
if(isset($_POST['update_cfg']))
{
unset($_POST['update_cfg']);
$update = $_POST;
unset($_POST);
if($Sys->Config->update_cfg($update))
{
$Sys->Template->setAlerts('The website has been successfully updated!');
}
else
{
$Sys->Template->setAlerts('The website has not been updated.', 'error');
}
unset($update);
}
?>
<div id="webCfg">
<h2>Website Configuration</h2>
<?php
global $Sys;
global $handle;
$alerts = $Sys->Template->getAlerts();
if ($alerts != '') { echo '<div><ul class="alerts">' . $alerts . '</ul></div>'; }
asort($handle);
if($handle['status'] == 1)
{
$enable = 'checked="checked"';
}
else
{
$disable = 'checked="checked"';
}
foreach ($handle as $key => $val)
{
$label = str_replace('_', ' ', $key);
if(strlen($val) <= 50 && !is_numeric($val))
{
$input[$key] = '<tr><td class="label"><label for="' . $key . '">' . ucwords($label) . '</label></td><td class="content"><input type="text" id="' . $key . '" name="' . $key . '" value="' . $val . '"/></td></tr>';
}
elseif(strlen($val) >= 51 && !is_numeric($val))
{
$input[$key] = '<tr><td class="label"><label for="' . $key . '">' . ucwords($label) . '</label></td><td class="content"><textarea id="' . $key . '" name="' . $key . '">' . ucfirst($val) . '</textarea></td></tr>';
}
elseif(is_numeric($val))
{
$input[$key] = '<tr><td class="label"><label for="' . $key . '">Website Status</label></td><td class="content"><input type="radio" id="' . $key . '" name="' . $key . '" value="1" ' . $enable . '> Enable <input type="radio" id="' . $key . '" name="' . $key . '" value="0" ' . $disable . '> Disable </td></tr>';
}
}
?>
<form action="" method="post">
<table cellpadding="1" cellspacing="0" id="webCfgTbl">
<?php
foreach (array_keys($input) as $key)
{
echo '<div class="row">' . $input[$key] . '</div>';
}
?>
<tr><td class="label"><label for="submit"></label></td><td class="content"><div class="row submitrow"><input type="submit" id="submit" name="update_cfg" class="submit" value="Update Settings" /></div></td></tr>
</table>
</form>
</div>
?>
The info from the database is loaded when the page is. When I change the values and click Update Settings, $Sys->Config->update_cfg() returns FALSE everytime. I am stumped on this and would appreciate any help. Thanks.
EDIT
When I echo the query in the update_cfg() function after the foreach() loop I get this:
UPDATE `dj_settings` SET `status`='0', `disabled_msg`=':: Test Message for Disabled Website ::', `email_auto_response`='Thank you so much for your email. I will respond back as soon as I am able. Usually within 30 minutes. Please feel free to look at the pictures and videos on our website, and the FAQ and Pricing tab is a great resource also. I will respond personally to any questions you may have shortly. Have a great day! Some tips on picking the right DJ: For most hiring a DJ is a first time experience. Picking the right DJ can be daunting and sometimes overwhelming task. Here are some good tips to follow to help you through your process. 1. Make sure they have their LLC or INC, and have a business license for your area. 2. Make sure they are insured. 3. Make sure that you sign some kind of a contract throughout the booking process. 4. Check reviews on reputable websites. ie.. thumbtack.com , weddingwire.com, or yellowpages.com. 5. If the price is too good to be true, it is. This is a big one, because you definitely get what you pay for when you hire a DJ. 6. Sit down with a couple of DJ's and talk them, generally your own intuition will get you far. If you follow those steps, you're sure to get a good DJ. No matter who it is, with my company or with a competitor. Your event will go off smoothly 99% of the time. Marshall Bracewell-Owner Dynamic DJ Company, LLC 803-807-1243 http://www.dynamicdjcompany.com', `web_url`='http://www.dynamicdjcompany.com', `web_email`='marshall#dynamicdjcompany.com'
Well...that's a start I guess...at least the update is working. Try first doing $info = $this->Sys->db->real_escape_string($info); then putting that into the "" . $column . "='" . $info . "'";
My code works properly, it is display all messages and entry dates. I want to display message and entry date when I select customer name from drop down list.
Here is my controller CustomerlifecycleController
public function actionCustomerlifecycleanalytic() {
$customername = Customer::model()->findall("store_id='" . Yii::app()->session['store_id'] . "'");
$customerlifecycle = CustomerLifecycle::model()->findAll();
$this->renderPartial('customerlifecycleanalytic', array( 'customername' => $customername, 'customerlifecycle' => $customerlifecycle), false, true);
}
Here is my view file customerlifecycleanalytic.php
Dropdown list
Customer name fetch from customer model
and there is column name id for customer
<select class="form-control selectpicker customerfilter">
<option value=''>Select Customer</option>
<?php
if (isset($customername)) {
foreach ($customername as $customernames) {
echo '<option value="' . $customernames['id'] . '" >' . $customernames['firstname'].' '. $customernames['lastname']. '</option>';
}
}
?>
</select>
Message and entry date fetch from Customerlifecycle model there is column name is customer_id
$msg = '<li {classstr}>
<div class="tl-circ">
</div>
<div class="timeline-panel">
<div class="tl-body">
<p>
{msg} on {date}</p>
</div>
</div>
</li>';
$cnt = 0;
$htmlstring = '';
foreach ($customerlifecycle as $key => $row) {
$htmlstring .= $msg;
$classString ='';
if ($cnt % 2 == 0) {
$classString = " class='timeline-inverted' ";
}
$htmlstring = str_replace("{classstr}", "$classString", $htmlstring);
$htmlstring = str_replace("{msg}", "$row->message", $htmlstring);
$htmlstring = str_replace("{date}", "$row->entrydate", $htmlstring);
$cnt++;
}
echo $htmlstring;
?>
My code is already running completely but I want when I select customer name form drop down list at that time it will display only that customer's message and entry date.
To display selected customer's message and entry date, you can call javascript function on onChange event of dropdownlist as follows:
<script type="text/javascript" language="Javascript">
function submitForm() {
document.getElementById("form-id").submit();
}
</script>
<select class="form-control selectpicker customerfilter" name="Customer[id]" onChange="js: return submitForm();">
Using this javascript function, submit the form and make changes in your controller as follows:
public function actionCustomerlifecycleanalytic() {
$customername = Customer::model()->findall("store_id='" . Yii::app()->session['store_id'] . "'");
$strCondition = "";
if(isset($_POST['Customer'])) {
if (!empty($_POST['Customer']['id'])) {
$strCondition .= "store_id = '" . Yii::app()->session['store_id'] . "' AND customer_id = '" . $_POST['Customer']['id'] . "'";
}
}
$customerlifecycle = CustomerLifecycle::model()->findAll($strCondition);
$this->renderPartial('customerlifecycleanalytic', array( 'customername' => $customername, 'customerlifecycle' => $customerlifecycle), false, true);
}
Hope this helps!
I have this tag cloud, which is currently set to show the most popular item first with the use of (line 205):
// arsort($array_end);
which reverses the array. If i leave this out it shows the list alphabetically.
I would like to have the results shown randomly. I thought of php-shuffle, but i don't know how to go about it. Appreciate if someone could help me out here, Cheers!
See php below (also uploaded php here as .txt):
//activate plugin WP function
//Checking search meter dependencies
global $wpdb, $table_prefix;
$sql = "SHOW TABLES LIKE '{$table_prefix}searchmeter_recent'";
$results = $wpdb->get_results($sql);
if (!$wpdb->num_rows )
{
die( '<p>This plugin will not work unless Search Meter plugin is installed and activated.</p>' );
}
register_activation_hook( __FILE__, 'initializeSearchTagCloud');
//activat plugin WP function
register_deactivation_hook( __FILE__, 'deactivateSearchTagCloud');
//set initial values when the plugin is activated
function initializeSearchTagCloud()
{
$search_tag_cloud=new searchTagCloud();
$search_tag_cloud->initializeSearchTagCloud();
}
//delete DB options when the plugin is activated
function deactivateSearchTagCloud() {
delete_option("searchTagCloudOption");
}
class searchTagCloud
{
public $widgetText;
public $numberSearches;
public $max_size;
public $min_size;
public $days_to_display;
var $error;
//constuctor function
function __construct()
{
$this->min_size=12;
$this->max_size=32;
$this->widgetText = 'What people is searching?';
$this->total_tags=10;
$this->show_author_credit=0;
$this->days_to_display=30;
//the size of the tag cloud is missed
}
//initialize options
//size of the smallest tag
//maximum size of the biggest tag
//Personalized text for the tag cloud
//how many links to display
function initializeSearchTagCloud()
{
global $wpdb, $table_prefix;
$wpdb->query("ALTER TABLE `{$table_prefix}searchmeter_recent` ADD COLUMN visible INT( 1 ) NOT NULL DEFAULT '1'");
$initializeOptions = array(
"min_size" => $this->min_size,
"max_size" => $this->max_size,
"total_tags" => $this->total_tags,
"widgetText" => $this->widgetText,
"days_to_display" => $this->days_to_display,
"show_author_credit" => $this->show_author_credit,
);
add_option("searchTagCloudOption", $initializeOptions, '', 'yes');
//select recent searched terms
}
//get DB options for the Search Tag Cloud
function getSearchTagCloudOptions()
{
$myOptions = get_option('searchTagCloudOption');
$this->min_size=$myOptions['min_size'];
$this->max_size=$myOptions['max_size'];
$this->widgetText=$myOptions['widgetText'];
$this->total_tags=$myOptions['total_tags'];
$this->days_to_display=$myOptions['days_to_display'];
$this->show_author_credit=$myOptions['show_author_credit'];
}
//set Search Tag Cloud class values
function setSearchTagCloudValues($min_size,$max_size,$total_tags,$widgetText,$show_author_credit,$days_to_display)
{
$this->min_size=$min_size;
$this->max_size=$max_size;
$this->widgetText=$widgetText;
$this->total_tags=$total_tags;
$this->show_author_credit=$show_author_credit;
$this->days_to_display=$days_to_display;
}
//update Search Tag Cloud class values and DB options
function updateSearchTagCloud($array_post)
{
global $wpdb, $table_prefix;
$this->setSearchTagCloudValues($array_post['min_size'],$array_post['max_size'],$array_post['total_tags'],$array_post['widgetText'],$array_post['show_author_credit'],$array_post['days_to_display']);
//set the new options in the database
update_option("searchTagCloudOption", $array_post, '', 'yes');
//I set all to visible
$wpdb->query("UPDATE `{$table_prefix}searchmeter_recent` SET visible=1");
if(is_array($array_post['checkbox_visible']))
{
foreach($array_post['checkbox_visible'] as $index=>$value)
$wpdb->query("UPDATE `{$table_prefix}searchmeter_recent` SET visible=0 WHERE terms = '{$value}'");
}
return __("Options Saved Correctly");
}
//Function to select from search meter tables in the database the most common searches.
function select_searches_for_tagcloud()
{
// List the most recent successful searches.
global $wpdb, $table_prefix;
$this->getSearchTagCloudOptions();
$count = intval($this->total_tags);
//first I need to know how many invisible tags we have
//select terms, COUNT( * ) AS total FROM `wp_searchmeter_recent` WHERE datetime>='2010-07-05' GROUP BY `terms` LIMIT 0,15
//$datebeginning = date()-dÌas
$datebeginning = date('Y-m-d', mktime(0, 0, 0, date("m"),date("d")-$this->days_to_display, date("Y")));
$tags = $wpdb->get_results(
//select recent searched terms
" SELECT terms, visible, COUNT( * ) AS total
FROM `{$table_prefix}searchmeter_recent`
WHERE datetime>='{$datebeginning}' AND
hits>0 AND
visible=1
GROUP BY `terms`
LIMIT {$count}");
return $tags;
}
function selectPopularSearchesforAdmin()
{
// List the most recent successful searches.
global $wpdb, $table_prefix;
$this->getSearchTagCloudOptions();
$count = intval($this->total_tags);
//first I need to know how many invisible tags we have
//select terms, COUNT( * ) AS total FROM `wp_searchmeter_recent` WHERE datetime>='2010-07-05' GROUP BY `terms` LIMIT 0,15
//$datebeginning = date()-dÌas
$datebeginning = date('Y-m-d', mktime(0, 0, 0, date("m"),date("d")-$this->days_to_display, date("Y")));
$invisible_tags = $wpdb->get_results(
" SELECT terms, COUNT( * ) AS total
FROM `{$table_prefix}searchmeter_recent`
WHERE visible=1 AND
`datetime`>='{$datebeginning}' AND
hits>0
GROUP BY `terms`
LIMIT {$count}");
// I have to show the tags plus the invisible ones
$count = $count + count($invisible_tags);
$tags = $wpdb->get_results(
//select recent searched terms
" SELECT terms, visible, COUNT( * ) AS total
FROM `{$table_prefix}searchmeter_recent`
WHERE datetime>='{$datebeginning}' AND
hits>0
GROUP BY `terms`
LIMIT {$count}");
return $tags;
}
//function that creates the tag cloud and prints it.
function popular_searches_tag_cloud($args)
{
$results=$this->select_searches_for_tagcloud();
if(count($results)>0)
{
foreach($results as $index)
{
$array_end[$index->terms]=$index->total;
}
// arsort($array_end);
// largest and smallest array values
$max_qty = max(array_values($array_end));
$min_qty = min(array_values($array_end));
// find the range of values
$spread = $max_qty - $min_qty;
if ($spread == 0) { // we don't want to divide by zero
$spread = 1;
}
// set the font-size increment
$step = ($this->max_size - $this->min_size) / ($spread);
//set the counter for the loop at 0
$counter=0;
// loop through the tag array
if(count($array_end)>0)
{
$html='<div class="search-tag-cloud">';
$html.='<h2>'.$this->widgetText.'</h2>';
foreach ($array_end as $key => $value)
{
if($counter<=$this->total_tags)
{
$counter++;
// calculate font-size
// find the $value in excess of $min_qty
// multiply by the font-size increment ($size)
// and add the $min_size set above
$size = round($this->min_size + (($value - $min_qty) * $step));
$html.= '<a href="?s=' . $key . '" style="font-size: ' . $size . 'px"
title="' . $key . '">' . $key . '</a> ';
}
else
break;
}
if($this->show_author_credit==1)
$html.='<div id="search-tag-cloud"><p style="text-align:right"><small>WP plugin by Marketing Online</small></p></div>';
$html.='</div>';
echo $html;
}
}
}
}
/*end class--------------------------------*/
//setting the admin page
//create admin->settings page
//create Settings Section to configure plugin values
if (is_admin() ){ // admin actions
add_action('set_twitter_keyword_values','set_twitter_keyword');
add_action('admin_menu','admin_setSearchTagCloud');
add_action('admin_init','searchTagCloudSettings' );
} else {
// non-admin enqueues, actions, and filters
}
//adding the page in the admin section
function admin_setSearchTagCloud() {
add_options_page('Popular Searches Tag Cloud Options', 'Popular Searches Tag Cloud', 8,__FILE__, 'searchTagCloudOptions');
}
//register form fields
function searchTagCloudSettings() { // whitelist options
register_setting('search-tag-cloud-options', 'widgetText', 'wp_filter_nohtml_kses');
register_setting('search-tag-cloud-options', 'max_size', 'checkValueisInt');
register_setting('search-tag-cloud-options', 'min_size', 'checkValueisInt');
register_setting('search-tag-cloud-options', 'total_tags', 'checkValueisInt');
register_setting('search-tag-cloud-options', 'checkbox_visible');
register_setting('search-tag-cloud-options', 'show_author_credit', 'checkValueisInt');
register_setting('search-tag-cloud-options', 'days_to_display', 'checkValueisInt');
}
function searchTagCloudOptions()
{
$html= '<div class="wrap">';
$html= '<form method="post">';
settings_fields('search-tag-cloud-options');
$html.= '<h2>'. __("Popular Searches Tag Cloud Options: Manage Options").'</h2>';
if($_POST['type-submit']=='Y')
{
$message=updateSearchTagCloudForm($_POST);
if($message!='')
$html.= '<div class="error"><p><strong>'.$message.'</strong></p></div>';
else
$html.= '<div class="updated"><p><strong>'.__("Options Saved").'</strong></p></div>';
$myOptions=get_option('searchTagCloudOption');
}
else
$myOptions=get_option('searchTagCloudOption');
$html.= '<label for="newpost-edited-text">'.__('Set the header for the Popular Searches Tag Cloud to be visible: ').'</label>';
$html.= '<input type="text" name="widgetText" size="40" maxlength="150" value="'.$myOptions['widgetText'].'" /><br /><br />';
$html.= '<label for="newpost-edited-text">'.__('Size of the biggest tag: ').'</label>';
$html.= '<input type="text" name="max_size" size="10" maxlength="3" value="'.$myOptions['max_size'].'" /><br /><br />';
$html.= '<label for="newpost-edited-text">'.__('Size of the smallest tag: ').'</label>';
$html.= '<input type="text" name="min_size" size="10" maxlength="3" value="'.$myOptions['min_size'].'" /><br /><br />';
$html.= '<label for="newpost-edited-text">'.__('Number of searches to display: ').'</label>';
$html.= '<input type="text" name="total_tags" size="10" maxlength="3" value="'.$myOptions['total_tags'].'" /><br /><br />';
$html.= '<label for="newpost-edited-text">'.__('You want to show searches from the last : ').'</label>';
$html.= '<input type="text" name="days_to_display" size="10" maxlength="3" value="'.$myOptions['days_to_display'].'" /> days<br /><br />';
$html.=getMostPopularSearchesAdmin($results, 15, false);
$html.= '<br /><br /><label for="newpost-edited-text">'.__('Display developer credits in the Widget: ').'</label>';
$html.= '<input type="checkbox" name="show_author_credit" value="1" ';
if ($myOptions['show_author_credit']==1)
$html.='checked';
$html.='/><br /><br />';
$html.= '<input type="hidden" name="type-submit" value="Y">';
$html.= '<br><input type="submit" class="button-primary" value="'.__('Save Options').'" />';
//here I need the list of all searches, order by total
$html.= '</form>';
$html.= '</div>';
echo $html;
}
//function to show common searches to edit in the admin page. Completes the admin form.
function getMostPopularSearchesAdmin(){
$searchcloud=new searchTagCloud();
$results=$searchcloud->selectPopularSearchesforAdmin();
if (count($results)) {
$html='<table cellpadding="3" cellspacing="2">';
$html.='<tbody>';
$html.='<tr class="alternate"><th class="left">Term</th><th>Set not Visible</th>';
if ($do_include_successes) {
$html.='<th>Results</th>';
}
$html.='</tr>';
$class= '';
$counter=0;
foreach ($results as $result) {
$html.='<tr class="'.$class.'">';
$html.='<td>'.htmlspecialchars($result->terms).'</td>';
$html.='<td align="center"><input type="checkbox" name="checkbox_visible['.$counter.']" value="'.$result->terms.'" ';
if ($result->visible==0)
$html.='checked';
$html.='/>';
$html.='</td>';
$html.='</tr>';
$class = ($class == '' ? 'alternate' : '');
$counter++;
}
$html.='</tbody>';
$html.='</table>';
} else {
$html.='<p>No searches recorded for this period.</p>';
}
return $html;
}
//This functions checks the data send by the form and calls the update the option.
function updateSearchTagCloudForm($array)
{
$message='';
$search_tag_cloud=new searchTagCloud();
//check values before inserting into DB
$message=checkNumbers($array['max_size']);
$message.=checkNumbers($array['min_size']);
$message.=checkNumbers($array['total_tags']);
$message.=checkSearchCloudWidgetText($array['widgetText']);
$message.=checkNumbers($array['days_to_display']);
if($array['show_author_credit'])
$message.=checkNumbers($array['show_author_credit']);
if($message!='')
return $message;
if($message=='')
{
$search_tag_cloud->updateSearchTagCloud($array);
}
}
//checking function for the form fields functions in the admin page
function checkNumbers($number)
{
if(!intval( $number ))
return __("The field maximum size and minimum size have to be numeric<br />");
elseif($number>100)
return __("Maximum size and minimum size have to be smaller than 100<br />");
else
return "";
}
//checking function for the form fields functions in the admin page
function checkSearchCloudWidgetText($widgetText)
{
if(strlen($widgetText)>150)
{
return __("You are not allowed to include more than 150 characters in the Widget Text<br />");
}
return "";
}
//Widgetizing the plugin functions
function setSearchTagCloudPlugin()
{
register_sidebar_widget(__('Popular Searches Tag Cloud'), 'callSearchTagCloud');
register_widget_control(__('Popular Searches Tag Cloud'), 'callSearchTagCloud', 200, 200 );
}
add_action("plugins_loaded", "setSearchTagCloudPlugin");
//function to initailize the class. Called from sidebar.php, it checks dependencies from the search meter plugin.
function callSearchTagCloud()
{
global $wpdb, $table_prefix;
$sql = "SHOW TABLES LIKE '{$table_prefix}searchmeter_recent'";
$results = $wpdb->get_results( $sql );
if ( ! $wpdb->num_rows )
{
die( '<p>This plugin will not work unless Search Meter plugin is installed and activated. -- widget</p>' );
}
else
{
$search_tag_cloud=new searchTagCloud();
$search_tag_cloud->initializeSearchTagCloud();
}
$searchcloud=new searchTagCloud();
$searchcloud->popular_searches_tag_cloud($tags,$args);
}
function setSearchTagCloudControl()
{
echo '<p><label for="myHelloWorld-WidgetTitle">To configure options go to "Settings > Popular Searches Tag Cloud" in this admin panel</label></p>';
}
Use the shuffle function:
This function shuffles (randomizes the order of the elements in) an array.
A little below
// arsort($array_end);`
You got this code:
foreach ($array_end as $key => $value)
{
Replace it with this:
$array_end_keys = array_keys($array_end);
shuffle($array_end_keys);
foreach ($array_end_keys as $key)
{
$value = $array_end[$key];
In WordPress i'm currently using Yoast's SEO Plugin to display breadcrumbs for my pages and posts, which is working fine when visiting a specific page.
Here is the function i'm using to display the breadcrumbs inside of my WordPress templates:
<?php if ( function_exists('yoast_breadcrumb') ) {
yoast_breadcrumb('<p id="breadcrumbs">','</p>');
} ?>
For example when browsing to Team Members which is a child of About Us I get:
Home > About Us > Team Members
However i'd like to be able to display the same breadcrumbs (for the individual pages and posts) inside the search results loop.
So far what displays when searching for Members is:
Your Search Results:
Team Members
Home > Search > Members
Members Area
Home > Search > Members
But I don't want breadcrumbs for the Search Results page, I want them for the individual pages and posts that are displayed as a result of searching for a keyword.
For example Imagine I searched again for Members I would like displayed the below:
Your Search Results:
Team Members
Home > About Us > Team Members
Members Area
Home > Members Area
I'm not fussed if this is or isn't integrated with the SEO plugin, however thus far it's the best solution I found to display breadcrumbs in WordPress!
Also incase abody requires it, here is my search.php file: http://pastebin.com/0qjb2954
Try this. That's my own working snippet that shows breadcrumbs inside search loop.
/*Begin Loop */
<?php
echo '<div class="b-search_result_list__item_breadcrumbs breadcrumbs">';
$current_type = get_post_type();
if ($current_type == 'page') {
$parents = get_post_ancestors(get_the_ID());
if($parents){
for($i=count($parents)-1;$i>=0;$i--){
echo '<span typeof="v:Breadcrumb">';
echo '<a rel="v:url" property="v:title" title="'.get_the_title($parents[$i]).'" href="'.get_permalink($parents[$i]).'">'.get_the_title($parents[$i]).'</a>';
echo '</span>';
}
}else{
echo '<span typeof="v:Breadcrumb">';
echo '<a rel="v:url" property="v:title" title="'.get_bloginfo('name').'" href="'.get_bloginfo('url').'">'.get_bloginfo('name').'</a>';
echo '</span>';
}
echo '<span typeof="v:Breadcrumb">';
echo '<span property="v:title">'.get_the_title().'</span>';
echo '</span>';
}else{
$current_obj = get_post_type_object($current_type);
echo '<span typeof="v:Breadcrumb">';
echo '<a rel="v:url" property="v:title" title="'.get_bloginfo('name').'" href="'.get_bloginfo('url').'">'.get_bloginfo('name').'</a>';
echo '</span>';
echo '<span typeof="v:Breadcrumb">';
echo '<a rel="v:url" property="v:title" title="'.$current_obj->labels->name.'" href="'.get_post_type_archive_link( $current_type ).'">'.$current_obj->labels->name.'</a>';
echo '</span>';
$current_taxonomies = get_object_taxonomies($current_type);
if($current_taxonomies){
$current_terms = get_the_terms(get_the_ID(), $current_taxonomies[0]);
if($current_terms){
$current_term = array_shift($current_terms);
echo '<span typeof="v:Breadcrumb">';
echo '<a rel="v:url" property="v:title" title="'.$current_term->name.'" href="'.get_term_link($current_term).'">'.$current_term->name.'</a>';
echo '</span>';
/*
var_dump($current_obj->labels->name); // Archive name
var_dump(get_post_type_archive_link( $current_type )); // Archive link
var_dump($current_term->name); // Term name
var_dump(get_term_link($current_term)); // Term link
var_dump(get_permalink()); // Post link
*/
}
}
echo '<span typeof="v:Breadcrumb">';
echo '<span property="v:title">'.get_the_title().'</span>';
echo '</span>';
}
echo '</div>';
?>
/*End Loop*/
try adding this line of code above the yoast breadcrumb function in your search.php file:
WPSEO_Breadcrumbs::$instance = NULL;
This would be line 22 I believe, and also make sure to use the Yoast breadcrumb function from your question, not the new breadcrumb() function that's there now.
Please let me know if this works!
Full explanation:
The Yoast plugin breadcrumbs functionality is build on the page load, based on the current page as the child. To make it load the right child and parents, you'd need to reset it before you run the function. There is no built-in reset function, however setting the static $instance to NULL should cause the plugin to re-generate its data based on the current global post object which is set while you're looping.
Building upon Yavor's answer I found a way. Been banging my head about it for hours. You can place the backup and restore otuside of the loop though. Here it is:
global $wp_query;
//backup
$old_singular_value = $wp_query->is_singular;
//change
$wp_query->is_singular = true;
//reset
WPSEO_Breadcrumbs::$instance = NULL;
//breadcrumbs
if (function_exists('yoast_breadcrumb')){
yoast_breadcrumb('<p id="breadcrumbs">','</p>');
}
//restore
$wp_query->is_singular = $old_singular_value;
It fakes the query to make it singular so the newly-refreshed breadcrumbs thinks that this is not the search page but a single post or page or whatever you are displaying as your search results.
Using a plugin to generate breadcrumbs is not really necessary. Here's a simple PHP function you can add to your functions.php file:
function breadcrumbs() {
global $post;
echo "<ul id='breadcrumbs'>";
if (!is_home()) {
echo '<li>Home</li>';
if (is_category() || is_single()) {
echo "<li>" . the_category(' </li><li> ');
if (is_single()) {
echo "</li><li>" . the_title() . "</li>";
}
} elseif (is_page()) {
if($post->post_parent){
foreach ( get_post_ancestors( $post->ID ) as $ancestor ) {
echo '<li>' . get_the_title($ancestor) . '</li>' . get_the_title();
}
} else {
echo "<li>" . get_the_title() . "</li>";
}
}
} elseif (is_tag()) {
single_tag_title();
} elseif (is_day()) {
echo "<li>Archive for " . the_time('F jS, Y') . "</li>";
} elseif (is_month()) {
echo "<li>Archive for " . the_time('F, Y') . "</li>";
} elseif (is_year()) {
echo "<li>Archive for " . the_time('Y') . "</li>";
} elseif (is_author()) {
echo "<li>Author Archive</li>";
} elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {
echo "<li>Blog Archives</li>";
} elseif (is_search()) {
echo "<li>Search Results for" . the_search_query() . "</li>";
}
echo "</ul>";
}
along with some CSS to style it, customize as you desire
#breadcrumbs {
list-style:none;
margin:5px 0;
overflow:hidden;
}
#breadcrumbs li{
float:left;
}
#breadcrumbs li+li:before {
content: '| ';
padding:0 4px;
}
You can then implement those breadcrumbs on any page you like, including your searchpage.php file or whichever file you use to display search results with this call
<?php breadcrumbs(); ?>
The search pages have a conditional function that can be used. You could always apply that to loading the breadcrumbs. Here is an example:
if ( ! is_search() ) {
if ( function_exists('yoast_breadcrumb') ) {
yoast_breadcrumb('<p id="breadcrumbs">','</p>');
}
}
It depends where you are loading the breadcrumbs as well, but this should typically work unless your theme is very unique.
I have a page that has a list of items. On the bottom of the page is a "view more" button. When someone clicks this button, the page needs to add more items. The var is $displayedquestions, and the page is coded right now to refresh when the "view more" button is clicked, but we'd like to have it do it live. How can this be done?
Here is code:
<?php
include "db_connect.php";
db_connect();
function tags($tags)
{
$tagarray=explode(",",$tags);
$i=0;
$finished='false';
while($finished=='false') {
if (empty($tagarray[$i])=='true') {
$finished='true';
} else {
$taglist = $taglist . '<a class="commonTagNames" href="">' . $tagarray[$i] . '</a> ';
$i++;
}
}
return $taglist;
}
function formattime($timesince)
{
$strsince=number_format($timesince,0,'','');
$nodecimals=intval($strsince);
if ($nodecimals<1){
return "Less than a minute ago";
} elseif ($nodecimals>=1&&$nodecimals<60) {
return $nodecimals . " min ago";
} elseif ($nodecimals>60&&$nodecimals<1440){
$hourssince=$nodecimals/60;
$hoursnodecimals=number_format($hourssince,0);
return $hoursnodecimals . " hours ago";
} elseif ($nodecimals>1440){
$dayssince=$nodecimals/1440;
$daysnodecimals=number_format($dayssince,0);
return $daysnodecimals . " days ago";
}
}
$submitbutton=$_REQUEST['viewmore'];
$numquestions=intval($_REQUEST['questions']);
if($numquestions!=0) {
$displayedquestions=$numquestions;
} else {
$displayedquestions=10;
}
$sql="SELECT * FROM `Questions` ORDER BY `Questions`.`ID` DESC LIMIT 0, " . $displayedquestions;
$questions=mysql_query($sql);
while($row = mysql_fetch_array($questions))
{
$id = $row['ID'];
$user = $row['userAsking'];
$question = $row['question'];
$tags = $row['tags'];
$timestamp = $row['timestamp'];
$time=strtotime($timestamp);
$secondssince=(date(U)-$time)/60;
$timesince=formattime($secondssince);
$responses=mysql_query("SELECT * FROM `answersToQuestions` WHERE `idOfQuestion`= '$id'");
$comments=mysql_num_rows($responses);
$likes=mysql_query("SELECT * FROM `likesOfQuestions` WHERE `idOfQuestion`= '$id'");
$numlikes=mysql_num_rows($likes);
$userprofileq = mysql_query("SELECT `ID`,`avatar` FROM `Users` WHERE `username` = '$user'");
$userprofileresult = mysql_fetch_row($userprofileq);
$linktoprofile = $userprofileresult[0];
$avatar = $userprofileresult[1];
$taglist=tags($tags);
echo "</li>";
echo '<li class="questionsList" onclick="showUser(' . $id . ')">
<div id="questionPadding">
<img class="askerImage" width=50 height=50 src="../Images/userimages/' . $avatar . '.png"/>
<div class="questionFirstRow"><h1 class="questionTitle">' . $question . '</h1></div>
<span class="midRow">
<span class="askerSpan"><a class="askerName" href="">'. $user .'</a></span>
</span>
<span class="bottomRow">
<img src="../Images/comment.png"/>
<span class="comments">' . $comments . '</span>
<img src="../Images/likes.png"/>
<span class="likes">' . $numlikes . '</span>
' . $timesince . '
</span>
</div>
</li>';
}
?>
<center><img class="moreQuestions" src="../Images/viewMoreBar.png" alt="More" /></center>
Without doing a lot of work you can add ajax to this. Use this function:
First, (I am assuming you are including the code above into another file) create a container around it. Ex:
<div id='container'>...</div>
Second, add this javascript to the page that includes the code you have above:
<script type="text/javascript">
$(function(){
$("#container img.moreQuestions").parent().live('click', (function (e) {
e.preventDefault();
$("#container").load($(this).attr("href"));
});
});
});
</script>
This will load into #container the script you already have without refreshing the rest of the page.
Note the selector for the More link (slash button) in my example is $("#container img.moreQuestions").parent() because you don't have a class or id on it. You should give a class or id to the More link and use that for the selector.
like #diEcho mentioned, jQuery would be a great help: You could easily refresh your list of items by ajax (retrieving the complete list from a php file for example) as well as update your DOM elements with newly added values. Give it a try.
In addition you should think about getting you initial items by ajax as well. Data logic /display /UI functionality were seperated cleanly this way.