Edit Auto Meta Keywords and Description WP Plugin - php

i am using a WP plugin to auto generate keywords and description for my site,
it is a single page Plugin, i want to modify it to work as i want, i am pasting whole code of php file:
<?php
/*
Plugin Name: Meta Keywords Generator
Plugin URI: http://home.techphernalia.com/2011/09/meta-keywords-generator/
Description: This plugin helps your SEO by adding meta keywords tag to each page, post, archive (category, tag, date, day and year). Now it also allows you to specify common keywords to be included on every web page. Plugin from one of the best coder Durgesh Chaudhary. For any support just leave your question on our Meta Keywords Generator page.<br/>Please update some settings to get more benefit Update settings
.
Version: 1.10
Author: Durgesh Chaudhary
Author URI: http://home.techphernalia.com/
*/
add_action('admin_menu', 'tp_mkg_add_page');
add_action('admin_init', 'tp_mkg_register');
add_action('wp_head','tp_act');
add_action('rightnow_end','tp_notify');
function tp_mkg_register(){
register_setting( 'tp_mkg_options', 'tp_mkg_options', 'tp_mkg_options_validate' );
add_settings_section('tp_mkg_main_section', 'Quick Settings', 'tp_mkg_section_main_render', 'techphernalia');
add_settings_field('tp_mkg_compulsary', 'Compulsary Keywords', 'tp_mkg_render_fields', 'techphernalia', 'tp_mkg_main_section');
}
function tp_mkg_add_page() {
add_options_page('Meta Keywords Generator', 'Meta Keywords Generator ', 'manage_options', 'techphernalia', 'tp_mkg_render_page');
}
function tp_mkg_render_page() {
echo '<style>#tp_promotion span {display: none;}#tp_promotion a{background: url(http://techphernalia.com/sprite_master.png) left top no-repeat;float: left;width: 32px;height: 32px;margin-right: 10px;}#tp_promotion a.twitter_link{ background-position: left -414px;}#tp_promotion a.facebook_link{background-position: -69px -414px;}</style>';
echo '<div class="wrap">
<center><h2>Meta Keywords Generator Settings</h2></center>
We are working continuously to provide you more SEO benefit and here comes the first in this series which allow you to provide some keywords which you want to be available on each and every web page served to your user. Currently we have only one setting we will have more soon.<br/><br/>Feel free to <b>request features</b> on our blog or on plugin page.
<form action="options.php" method="post">';
settings_fields('tp_mkg_options');
do_settings_sections('techphernalia');
echo '<input name="Submit" class="button-primary" type="submit" value="';
esc_attr_e('Save Changes');
echo'" />
</form></div>';
echo '<br/><br/><div id="tp_promotion"><a target="_blank" href="http://home.techphernalia.com/feed/" title="Subscribe to Our RSS feed" class="rss_link"><span>Subscribe to RSS feed</span></a>
<span>Follow us on Twitter</span><span>Visit us on Facebook</span>
</div>';
}
function tp_mkg_section_main_render() {
echo '<b>Compulsary Keywords</b> : Comma separated keywords which should appear on all the web page displayed.';
}
function tp_mkg_render_fields() {
$options = get_option('tp_mkg_options');
echo "<textarea id='tp_mkg_compulsary' name='tp_mkg_options[tp_mkg_compulsary]' cols='80' rows='10' maxlength='500' style='max-width:660px;max-height:164px;' >{$options['tp_mkg_compulsary']}</textarea>";
}
function tp_mkg_options_validate($input) {
$temp = trim($input['tp_mkg_compulsary']);
$temp = str_replace(";","",$temp);
$newinput['tp_mkg_compulsary'] = trim(str_replace("\"","",$temp));
return $newinput;
}
function tp_notify () {
echo '<p>SEO provided by <strong>Meta Keywords Generator</strong> from techphernalia.com</p>';
}
function tp_parse ($str) {
$str = str_replace("\"","'",$str);
$done = str_replace(", "," ",$str);
$done = str_replace(" ",", ",$done);
if (strpos($str," ")) return $str.", ".$done;
else return $str;
}
function tp_act () {
$name = get_option("blogname");
$desc = get_option("blogdescription");
if (is_tag()) $title = single_tag_title('',false);
if (is_category()) $title = single_cat_title('',false);
if (is_single() || is_page()) {
$add = "";
$postid = get_query_var("p");
$post = get_post($postid);
$title = single_post_title('',false);
$catlist = get_the_category($post->ID);
if (is_array($catlist)) { foreach ($catlist as $catlist) { $add .= ", ".$catlist->name; }}
$taglist = get_the_tags($post->ID);
if (is_array($taglist)) { foreach ($taglist as $taglist) { $add .= ", ".$taglist->name; }}
$description = substr(strip_tags($post->post_content),0,400);
}
$tp_mkg_options=get_option("tp_mkg_options");
echo '<!-- SEO by Meta Keywords Generator : techphernalia.com v1.10 start-->
';
if (!is_home()) {
echo '<meta name="keywords" content="'.tp_parse($title).', '.tp_parse($name).$add.", ".$tp_mkg_options["tp_mkg_compulsary"].'" />
<meta name="description" content="'.str_replace("\"","'",strip_shortcodes( $description )).'" />
';
} else {
echo '<meta name="keywords" content="'.tp_parse($desc).', '.$name.", ".$tp_mkg_options["tp_mkg_compulsary"].'" />
<meta name="description" content="'.str_replace("\"","'",strip_shortcodes( $desc )).'" />
';
}
echo '<!-- SEO by Meta Keywords Generator : techphernalia.com v1.10 end-->
';
}
?>
by default it is showing first 400 characters as description, i want to show Post title at the end and start of description,
any help will be highly appreciated.
Thanks

I am the author of this plugin, you could have asked this on official plugin url mentioned above.
We are generating description at this statement
$description = substr(strip_tags($post->post_content),0,400);
if you want to have site_title at beginning and at end, simply append $title at beginning and end.
$description = $title . substr(strip_tags($post->post_content),0,400) . $title;
but it may exceed 400 characters so you need to manage accordingly.
If you want to remove 400 chars limit remove substr part as
$description = $title . strip_tags($post->post_content) . $title;

Related

How to add meta tags in Wordpress for each post

I have multiple single-episodes.php single-movies.php single-seasons.php single-tvshows.php and I want each of them to have custom meta tags title and description I'm not good in coding so i was looking for a solution in google and i found this
To set the description to be unique on each posts you can add a conditional tag query that asks “If this is a single post view, show the post description of your choice; if this is a multi-post view, show the blog name and description.” The conditional tag query looks like this:
<meta name="description" content="<?php if ( is_single() ) { single_post_title('', true); } else { echo "description of your choice"; } ?>" />
how i can implament this code in the header so each single take a custome meta tags
You can work with the function is_single() in your <head> section.
Source : https://developer.wordpress.org/reference/functions/is_single/
Here is a working demo : https://developer.wordpress.org/reference/functions/is_single/#comment-496
is_single('my-slug');
// When the Post with post_name (slug) of "my-slug" is being displayed.
For the purpose of the post, I coded it for you below.
<?php
// Variables
$my_custom_title = '';
$my_custom_description = '';
if(is_single('episodes')) {
$my_custom_title = 'Episodes';
$my_custom_description = 'My custom description for episodes.';
}
elseif(is_single('seasons')) {
$my_custom_title = 'Seasons';
$my_custom_description = 'My custom description for seasons.';
}
elseif(is_single('tvshows')) {
$my_custom_title = 'TV Shows';
$my_custom_description = 'My custom description for TV shows.';
}
else {
$my_custom_title = get_bloginfo('name');
$my_custom_description = get_bloginfo('description');
}
?>
<title><?php echo $my_custom_title; ?></title>
<meta name="description" content="<?php echo $my_custom_description; ?>" />
To know more about get_bloginfo() : https://developer.wordpress.org/reference/functions/get_bloginfo/

Shuffle given array

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

WordPress breadcrumbs in search results

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.

PHP jQuery Post - returns too much HTML

I have a problem when using jQuery Post, the PHP returns all the HTML of the page up to the newly created HTML, rather then just the HTML that is output by the PHP.
As an example say the php outputs: '<div>Some Content</div>'
Then the jQuery Post returns: '<html><head>...all the head content...</head><body>...other content...<div>Some Content</div>'
Here's the jQuery (link to full code: http://pastebin.com/U7R8PqX1):
jQuery("form[ID^=product_form]").submit(function() {
var current_url = js_data.current_url;
form_values = jQuery(this).serialize();
jQuery.post(current_url+"?ajax=true", form_values, function(returned_data) {
jQuery('div.shopping-cart').html(returned_data);
}
});
return false;
});
And here's the PHP (version 5.3.6 - link to full code: http://pastebin.com/zjSUUbmL):
function output_cart()
{
ob_start();
echo $this->output_cart_html();
$output = ob_get_contents();
ob_end_clean();
echo $output;
exit();
}
function output_cart_html() {
if (!isset($_SESSION['cart_items']))
{
$output = '<div class="cart_content faded">BASKET - Empty</div>';
return $output;
} else {
$total_items = 0;
$total_items = 0;
$items_in_cart = $_SESSION['cart_items'];
// work out total price and total items
foreach ($items_in_cart as $item_in_cart) {
$total_items += $item_in_cart['quantity'];
$total_price += floatval($item_in_cart['updated_price']*$item_in_cart['quantity']);
}
$template_url = get_bloginfo('template_directory');
$output = '';
$output_price = $dp_shopping_cart_settings['dp_currency_symbol'].number_format($total_price,2);
if($total_items == 1){ $item_text = ' Item'; } else { $item_text = ' Items'; }
$output .= $total_items . $item_text;
$output .= ' <span class="bullet"></span> Total '.$output_price;
// empty cart btn
$output .= '<form action="" method="post" class="empty_cart">
<input type="hidden" name="ajax_action" value="empty_cart" />
<span class="emptycart"> <img src="'.$template_url.'/images/empty.png" width="9" height="9" title="Empty Your Items" alt="Empty Your Items" />Empty Your Cart</span>
</form>';
// check out btn
$output .= ' <span class="bullet"></span> <span class="gocheckout">'.$this->output_checkout_link().' </span>';
return $output;
}
}
You need to check if the form has been posted yet with the PHP. To do this, just check if the 'ajax' parameter is there, or send another $_GET variable if you wish (by adding &anotherparementer=1 to the end of the jQuery post URL). Example:
<?php
if(isset($_GET['ajax'])) {
//your PHP code here that submits the form, i.e. the functions that you have, etc.
}
else {
?>
<html>
<head>
head content here...
</head>
<body>
body content here...
</body>
</html>
<?php
}
?>
I hope this helps.
Ok it turns out my problem was with the way Wordpress processes AJAX requests. The plugin I was building on top of was using AJAX but didn't have these issues (I'm not sure why maybe because they were using eval), so I hadn't realised there was a correct way of using AJAX with Wordpress. Here's a bunch of information if anyone else has similar problems:
http://codex.wordpress.org/AJAX_in_Plugins
http://byronyasgur.wordpress.com/2011/06/27/frontend-forward-facing-ajax-in-wordpress/
(this one really helped me out, a very simple example that I was able to adapt)
-- sorry I couldn't post more links because I'm too new on this site, but check out the links at the bottom of the first link above, especially the '5 Tips'.
As I'm using classes I instantiated the class from the index file of my plugin with this:
if ($_POST['action'] === 'action_name') {
$class_obj = new \namespace_name\class();
add_action('wp_ajax_action_name', array($class_obj, 'method_name'));
add_action('wp_ajax_nopriv_action_name', array($class_obj, 'method_name'));
}

Have a php class return array values and keep looping until end

I'm trying to create a website that allows for easy theme adding/manipulation like wordpress and other CMS systems do. To do this I'd like to make it so the theme file that delivers the content uses as little php code as possible. At the moment this is the (extremely simplified) class
class getparents {
var $parentsarray;
function get_parents() {
$this->parentsarray = array();
$this->parentsarray[] = array('Parent0',3,1);
$this->parentsarray[] = array('Parent1',8,2);
$this->parentsarray[] = array('Parent2',2,3);
return $this->parentsarray;
}
}
And retrieving it like this:
$parents = new getparents();
?><table><?php
foreach($parents->get_parents() as $rowtable)
{
echo "<tr><td>$rowtable[0] has category ID $rowtable[1] and is on level $rowtable[2] </td></tr>";
}
?></table><?php
But I want to make the retrieving more like this:
<table>
<tr><td><?php echo $cat_title; ?> has category ID <?php echo $cat_id; ?> and is on level <?php echo $cat_level; ?> </td></tr>
</table>
Which basically mean the class would just return the value in an understandable way and automatically keep on looping without the user having to add *foreach($parents->get_parents() as $rowtable)* or something similar in their theme file.
Here's an example wordpress page to (hopefully) illustrate what I mean. This page retrieves all posts for the current wordpress category which is what I'm trying to mimic in my script, but instead of retrieving posts I want to retrieve the category's parents, but I don't think it's important to explain that in detail.
<?php
/**
* The template for displaying Category Archive pages.
*
* #package WordPress
* #subpackage Twenty_Ten
* #since Twenty Ten 1.0
*/
get_header(); ?>
<div id="container">
<div id="content" role="main">
<h1 class="page-title"><?php
printf( __( 'Category Archives: %s', 'twentyten' ), '<span>' . single_cat_title( '', false ) . '</span>' );
?></h1>
<?php
$category_description = category_description();
if ( ! empty( $category_description ) )
echo '<div class="archive-meta">' . $category_description . '</div>';
/* Run the loop for the category page to output the posts.
* If you want to overload this in a child theme then include a file
* called loop-category.php and that will be used instead.
*/
get_template_part( 'loop', 'category' );
?>
</div><!-- #content -->
</div><!-- #container -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
Note: My actual question doesn't have anything to do with wordpress at all so I didn't add it as a tag.
UPDATE: I think my question may have been unclear. Here's a messy example (that works nevertheless)
index.php
<?php
include_once("class.php");
include_once("config.php");
if(isset($_GET['catid']))
{
$getproducts = new getproducts($_GET['catid']);
$catproductsarray = $getproducts->getarray();
$indexxx = 0;
foreach($catproductsarray as $rowtable)
{
include("templates/$template/all_products.php");
$indexxx++;
}
}
class.php
class getproducts {
var $thearrayset = array();
public function __construct($indexx) {
$this->thearrayset = $this->makearray($indexx);
}
public function get_id($indexxx) {
echo $this->thearrayset[$indexxx]['id'];
}
public function get_catID($indexxx) {
echo $this->thearrayset[$indexxx]['catID'];
}
public function get_product($indexxx) {
echo $this->thearrayset[$indexxx]['name'];
}
public function makearray($indexx) {
$thearray = array();
if(!is_numeric($indexx)){ die("That's not a number, catid."); };
$resulttable = mysql_query("SELECT * FROM products WHERE catID=$indexx");
while($rowtable = mysql_fetch_array($resulttable)){
$thearray[] = $rowtable;
}
return $thearray;
}
public function getarray() {
return $this->thearrayset;
}
}
templates/default/all_products.php
<!-- The below code will repeat itself for every product found -->
<table>
<tr><td><?php $getproducts->get_id($indexxx); ?> </td><td> <?php $getproducts->get_catID($indexxx); ?> </td><td> <?php $getproducts->get_product($indexxx); ?> </td></tr>
</table>
So basically, index.php gets loaded by user after which the amount of products in mysql database is taken from the class. For every product, all_products.php gets called with $indexxx upped by one.
Now the only thing the user has to do is edit the HTML all_products.php and the products will all be displayed differently. This is what I'm going for, but in a clean, responsible way. Not like this, this is a mess!
UPDATE2: I found a better way to do it, but added it as an answer. Seemed more fitting and pevents this question from getting any longer/messyer than it already is.
Ok I'm getting a little bit closer to what I want, so I'm adding this as an answer.
The template:
<?php include("templates/$template/header.php"); ?>
<!-- [product][description][maxchars=##80##][append=##...##] -->
<!-- [categories][parents][name][append= ->] --><!-- maxchars=false means dont cut description -->
<!-- [categories][children][prepend=nothing] --><!-- prepend=nothing means no prepend -->
<div id="middle-left-section">
<table>
{start-loop-categories-parents}
<tr><td><!-- [categories][parents][name] --></td><td>
{end-loop-categories-parents}
</table>
<table>
<tr><td><!-- [categories][current] --></tr></td>
{start-loop-categories}
<tr><td> <!-- [categories][children] --></td><td>
{end-loop-categories}
</table>
</div>
<div id="middle-right-section">
<table id="hor-minimalist-a">
<thead>
<th scope="col"> </th>
<th scope="col">Name</th>
<th scope="col" width="200px">Description</th>
<th scope="col">Price</th>
</thead>
<tbody>
{start-loop-product}
<tr><td><img src="fotos/<!-- [product][thumb] -->"></img></td><td><!-- [product][name] --></td><td><!-- [product][description] --></td><td><!-- [product][price] --></td></tr>
{end-loop-product}
</tbody>
</table>
</div>
<div style="clear: both;"/>
</div>
<?php include("templates/$template/footer.php"); ?>
The class:
<?php
///////////////////////////
//Includes and functions//
/////////////////////////
include_once("config.php");
include_once("includesandfunctions.php");
function get_between($input, $start, $end)
{
$substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
return $substr;
}
function get_between_keepall($input, $start, $end)
{
$substr = substr($input, strlen($start)+strpos($input, $start), (strlen($input) - strpos($input, $end))*(-1));
return $start.$substr.$end;
}
class listproducts {
var $thearrayset = array();
var $file;
var $fp;
var $text;
var $products;
var $productskeepall;
var $done;
var $returnthisloopdone;
public function __construct() {
global $template;
//Get items from mysql database and put in array
$this->thearrayset = $this->makearray();
//Read file
$this->file = "templates/$template/all_products.php";
$this->fp = fopen($this->file,"r");
$this->text = fread($this->fp,filesize($this->file));
//Set other vars
$this->products = '';
$this->productskeepall = '';
$this->returnthisloopdone = '';
$this->done = ''; //Start $done empty
}
public function makearray() {
$thearray = array();
$resulttable = mysql_query("SELECT * FROM products");
while($rowtable = mysql_fetch_array($resulttable)){
$thearray[] = $rowtable; //All items from database to array
}
return $thearray;
}
public function getthumb($indexxx) {
$resulttable = mysql_query("SELECT name FROM mainfoto where productID=$indexxx");
while($rowtable = mysql_fetch_array($resulttable)){
return $rowtable['name']; //Get picture filename that belongs to requested product ID
}
}
public function listproduct()
{
global $template;
$this->products = get_between($this->done,"{start-loop-product}","{end-loop-product}"); //Retrieve what's between starting brackets and ending brackets and cuts out the brackets
$this->productskeepall = get_between_keepall($this->done,"{start-loop-product}","{end-loop-product}"); //Retrieve what's between starting brackets and ending brackets and keeps the brackets intact
$this->returnthisloopdone = ''; //Make loop empty in case it's set elsewhere
for ($indexxx = 0; $indexxx <= count($this->thearrayset) - 1; $indexxx++) //Loop through items in array, for each item replace the HTML comments with the values in the array
{
$this->returnthis = $this->products;
$this->returnthis = str_replace("<!-- [product][thumb] -->", $this->getthumb($this->thearrayset[$indexxx]['id']), $this->returnthis);
$this->returnthis = str_replace("<!-- [product][catid] -->", $this->thearrayset[$indexxx]['catID'], $this->returnthis);
$this->returnthis = str_replace("<!-- [product][name] -->", $this->thearrayset[$indexxx]['name'], $this->returnthis);
preg_match('/(.*)\[product\]\[description\]\[maxchars=##(.*)##\]\[append=##(.*)##\](.*)/', $this->done, $matches); //Check if user wants to cut off description after a certain amount of characters and if we need to append something if we do (like 3 dots or something)
$maxchars = $matches[2];
$appendeez = $matches[3];
if($maxchars == 'false'){ $this->returnthis = str_replace("<!-- [product][description] -->", $this->thearrayset[$indexxx]['description'], $this->returnthis);
}else{ $this->returnthis = str_replace("<!-- [product][description] -->", substr($this->thearrayset[$indexxx]['description'],0,$maxchars).$appendeez, $this->returnthis);
}
$this->returnthis = str_replace("<!-- [product][price] -->", $this->thearrayset[$indexxx]['price'], $this->returnthis);
$this->returnthisloopdone .= $this->returnthis; //Append string_replaced products section for every item in array
}
$this->done = str_replace($this->productskeepall, $this->returnthisloopdone, $this->done);
//Write our complete page to a php file
$myFile = "templates/$template/cache/testfile.php";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = $this->done;
fwrite($fh, $stringData);
fclose($fh);
return $myFile; //Return filename so we can include it in whatever page requests it.
}
} //End class
?>
The php requested by the website visitor, which will call the current template's all_products.php
include_once("class.php");
$listproducts = new listproducts();
include_once($listproducts->listproduct());
So what this really is, is just string_replacing the HTML comments in the template file with the PHP result I want there. If it's a loop, I Single out the html code I want to loop -> Start an empty string variable -> Repeat that HTML code, appending each loop to the string variable -> Use this string variable to replace the HTML comment
The newly built page is then written to an actual file, which is then included.
I'm completely new to OOP, so this is pretty elaborate stuff for me. I'd like to know if this is a good way to tackle my problem. And also, is it possible to prevent having to rewrite that entire class for every page?
As an example, if I also wanted to build a guestbook I'd like to rewrite the class in a way that it can accept passed variables and build the page from there, rather than pre-setting alot of stuff limiting it to one 'task' such as retrieving products. But before I go any further I'd like to know if this is an a-okay way to do this.

Categories