How to add ads to the end of RSS on wordpress? - wordpress

I have added a function to functions.php on my theme.
function insertAds($content) {
$content = $content.' add goes here';
return $content;}
add_filter('the_content_feed', 'insertAds');
add_filter('the_excerpt_rss', 'insertAds');
The problem is that I'm having the add displayed under each content, and not at the end of the rss page. How can I fix that?

WordPress doesn’t offer a hook for what you want to do. In which element would you place the ad?
The usual RSS-2-Feed has meta data and items (the content). There is no other element.
See wp-includes/feed-rss2.php for details.
Update
Adjust the following code to your needs and put the file into your plugin directory:
<?php
/*
Plugin Name: Last man adding
Description: Adds content to the last entry of your feed.
Version: 0.1
Author: Thomas Scholz
Author URI: http://toscho.de
Created: 31.03.2010
*/
if ( ! function_exists('ad_feed_content') )
{
function ad_feed_content($content)
{
static $counter = 1;
// We only need to check this once.
static $max = FALSE;
if ( ! $max )
{
$max = get_option('posts_per_rss');
}
if ( $counter < $max )
{
$counter++;
return $content;
}
return $content . <<<MY_ADDITIONAL_CONTENT
<hr />
<p>Place your ad here. Make sure, your feed is still
validating</p>
MY_ADDITIONAL_CONTENT;
}
}
add_filter('the_content_feed', 'ad_feed_content');
add_filter('the_excerpt_rss', 'ad_feed_content');
Is this the effect you had in mind? As you can see, adding content is rather easy. :)

Related

Show shortcode for a given word only once

I'm trying to implement a custom functionality to a wordpress shortcode plugin that shows a tooltip for specified words by automatically calling for information from Wikipedia.
Currently my code snippet works fine, but it shows the tooltips for each occurrence of the word in an article. For example if I specified the word : "dessert" in an array it will show the tooltip for all 5 words "dessert" found in the post. I'm looking for a way to limit the tooltip shortcode to be applied only once per word ( in this case "dessert" which has been specified in the array).
Me code snippet is this:
function add_wikitips($content) {
if( is_single() && is_main_query() ) {
$arr = array('dessert');
for ($i = 0; $i < count($arr); $i++) {
$content = str_replace($arr[$i], '[wiki]'.$arr[$i].'[/wiki]', $content);
}
}
return $content;
}
add_filter('the_content', 'add_wikitips');
I tried adding ob_end_clean(); then
static $content = null;
if ($content === null) {
return $content;
}
, but these methods didn't work. Probably because I didn't implement them properly.
Thanks a lot in advance for any advice and suggestions.
Probably, you can try this: Using str_replace so that it only acts on the first match?
You want the first work to have Wiki link. So replace the first occurrence only when you are doing str_replace()
May be like:
function str_replace_first($from, $to, $content)
{
$from = '/'.preg_quote($from, '/').'/';
return preg_replace($from, $to, $content, 1);
}
echo str_replace_first('abc', '123', 'abcdef abcdef abcdef');
// outputs '123def abcdef abcdef'
Mentioned in Karim's amswer

Change Wordpress logo click redirection

I would like to change the logo redirection when clicked. Right now when you click on the logo, the user is redirected to the homepage but I want it to redirect to another site. How do I do this?
I agree with Stu Mileham. Another way to implement what you are asking for would be to use JavaScript / jQuery.
Save the following code to a .js file (eg. pageRedirect.js, let's say placed in a js folder inside your theme's root folder):
(function($) {
$(document).ready(function() {
$('#pageLogo').on( "click", function(event) {
event.preventDefault();
window.location.assign("http://www.google.com/");
});
});
})(jQuery);
To make the previous code work, you would have to select somehow the page logo via jQuery.
On the previous code this is achived via $('#pageLogo') since I have made the assumption that your logo has an id with the value pageLogo.
Of course, to enable your theme to use this pageRedirect.js file, you have to enqueue it by placing the following code to your theme's functions.php file:
/**
* Enqueue pageRedirect script.
*/
function pageRedirect_scripts() {
wp_enqueue_script( 'page-redirect-js', get_template_directory_uri() . '/js/pageRedirect.js', array('jquery'), '20150528', true );
}
add_action( 'wp_enqueue_scripts', 'pageRedirect_scripts' );
Code Explanation:
//-jQuery selects html element with id='pageLogo'
//-when it is clicked, it calls a function in which it passes the event
$('#pageLogo').on( "click", function(event) {
//prevents page from redirecting to homepage
event.preventDefault();
//redirects to your desired webpage
window.location.assign("http://www.google.com/");
});
If you don't have the option to change the link from admin then you will have to edit your theme's header.php file (most likely, depends on how the theme is built though).
Many themes have a tag similar to the following:
<img src="logo.jpg">
You would need to change this to:
<img src="logo.jpg">
I've added the target tag to open the site in a new window, this is my personal preference when re-directing to a different site but it's optional.
Your theme files might look very different to this, it's impossible to know for sure without seeing some code, but this should give you an idea.
Also be aware that your changes could be overwritten by a theme update. This can be avoided by creating a child theme.
https://codex.wordpress.org/Child_Themes
Depends on your theme
Some theme creators gives you the possibility to change the link from admin
Some theme creators just believe that clicking the logo you need to go on homepage - so you need to edit the theme
Depending upon the theme you are using, you can try one of the following options.
Explore the admin options and see if the theme provides a direct way to change the link on the logo.
If not found in admin options, try looking for the code in header.php. Do an inspect element on your logo and see the html code surrounding the logo file, If the code is directly present in header.php, your task is simple. Just change the code to update the URL, instead of reading it from home_url(). Something like <a href="<?php echo home_url();?>"> will need to be replaced with <a href="https://www.example.com">
The other option to look for is get_custom_logo. Some themes get the logo code from this function. You can apply a filter to change the home_url just before this method is called in your theme and then remove filter afterwards. Or else you can copy the code from wordpress and update it with a differently named function say get_custom_link_logo in functions.php then where'ver your theme is using get_custom_logo you can use get_custom_link_logo instead of that.
function get_custom_link_logo ( $blog_id = 0 ) {
$html = "";
$switched_blog = false;
if ( is_multisite() && ! empty( $blog_id ) && (int) $blog_id !== get_current_blog_id() ) {
switch_to_blog( $blog_id );
$switched_blog = true;
}
$custom_logo_id = get_theme_mod( 'custom_logo' );
// We have a logo. Logo is go.
if ( $custom_logo_id ) {
$custom_logo_attr = array(
'class' => 'custom-logo',
'itemprop' => 'logo',
);
/*
* If the logo alt attribute is empty, get the site title and explicitly
* pass it to the attributes used by wp_get_attachment_image().
*/
$image_alt = get_post_meta( $custom_logo_id, '_wp_attachment_image_alt', true );
if ( empty( $image_alt ) ) {
$custom_logo_attr['alt'] = get_bloginfo( 'name', 'display' );
}
/*
* If the alt attribute is not empty, there's no need to explicitly pass
* it because wp_get_attachment_image() already adds the alt attribute.
*/
$html = sprintf( '%2$s',
esc_url( "https://www.example.com" ),
wp_get_attachment_image( $custom_logo_id, 'full', false, $custom_logo_attr )
);
}
// If no logo is set but we're in the Customizer, leave a placeholder (needed for the live preview).
elseif ( is_customize_preview() ) {
$html = sprintf( '<img class="custom-logo"/>',
esc_url( "https://www.example.com" )
);
}
if ( $switched_blog ) {
restore_current_blog();
}
/**
* Filters the custom logo output.
*
* #since 4.5.0
* #since 4.6.0 Added the `$blog_id` parameter.
*
* #param string $html Custom logo HTML output.
* #param int $blog_id ID of the blog to get the custom logo for.
*/
return apply_filters( 'get_custom_logo', $html, $blog_id ); }
This might not cover all the use cases, but you get the idea. Depending upon the theme you'll have a similar solution for your case. The important thing to figure out which case you fall under will be to identify the code where html for your logo is getting added. header.php is a good starting point.
Use this javascript in the header or footer of your theme:
<script>
document.getElementsByClassName("site-logo")[0].getElementsByTagName('a')[0].href="https://www.test.com";
</script>
i am assuming that site-logo is the class name of your LOGO.

hatom-entry errors on the Google snippet test

Almost sure that I'm not the first one that has this question but when I test my (WordPress) page on Google Snippet Test Tool I got hatom-enty errors like:
hatom-feed
hatom-entry:
Fout: At least one field must be set for HatomEntry.
Fout: Missing required field "entry-title".
Fout: Missing required field "updated".
Fout: Missing required hCard "author".
I found some tutorials about this but that is for standard WordPress themes. I'm using Inovado from ThemeForest and I can't figure out in which file I have to edit this data.
Someone familiar with this?
I also got problems with snippet review... Good in testresults but doesn't show up in de Google Search Results. Don't know why...
You can Add this code to the function.php file in your theme's directory and it will solve the problems.
//mod content
function hatom_mod_post_content ($content) {
if ( in_the_loop() && !is_page() ) {
$content = '<span class="entry-content">'.$content.'</span>';
}
return $content;
}
add_filter( 'the_content', 'hatom_mod_post_content');
//add hatom data
function add_mod_hatom_data($content) {
$t = get_the_modified_time('F jS, Y');
$author = get_the_author();
$title = get_the_title();
if(is_single()) {
$content .= '<div class="hatom-extra"><span class="entry-title">'.$title.'</span> was last modified: <span class="updated"> '.$t.'</span> by <span class="author vcard"><span class="fn">'.$author.'</span></span></div>';
}
return $content;
}
add_filter('the_content', 'add_mod_hatom_data');
The code contains 2 functions. The first function will use the WordPress filter hook for “the_content” to add the class of “entry-content” to the article. To add in the other essential hAtom fields, the second function will add a short sentence to the end of your post article, which contains updated time, post title and author, with required microdata.

Translate product category|tag title for JigoShop with qTranslate

qTranslate creates additional language fields for products pages in JigoShop but not also for category|tags product as it does for posts.
If I put in the title of a menu item <!--:en-->title<!--:--><!--:fr-->title<!--:--> i'll get the translation I want. But when creting a new category|tag title the <!--:--> is striped out. How can I enable comments tags for cat|tag title?
Another option is to use [:en]Title[:fr]Titre in the same title field when creating a new category|tag product. On the admin panel I see the proper text for the language selected but for end user i see [:en]Title[:fr]Titre.
I found this link https://wordpress.stackexchange.com/questions/28165/translating-a-custom-taxonomy and according to this answer http://www.qianqin.de/qtranslate/forum/viewtopic.php? f=4&t=2045&start=0#p7380 I addet in functions.php
add_action('jigoshop_add_form', 'qtrans_modifyTermFormFor');
add_action('jigoshop_edit_form', 'qtrans_modifyTermFormFor');
Did not work. I don't see aditional translations fields for categories|tags in JigoShop.
The basic question is:
How do I translate product categories|tags in JigoShop using qTranslate?
I was having very similar problem. I found a solution here: http://www.qianqin.de/qtranslate/forum/viewtopic.php?f=3&t=4064&start=10#p12940
Basically, all you have to do is to rename all the categories as suggested in the answer above, then add to your theme's functions.php file:
function p_filter_categories( $categories ) {
if ( is_array( $categories ) ) {
foreach ( $categories as $i => $cat ) {
$categories[ $i ]->name = __( $cat->name );
}
} else {
$categories->name = __( $categories->name );
}
return $categories;
}
add_filter( 'get_the_categories', 'p_filter_categories', 10 );
add_filter( 'get_the_terms', 'p_filter_categories', 10 );
add_filter( 'get_term', 'p_filter_categories', 10 );
Hope that helps!
Not the ideal solution but works.
In JigoShop/edit product category/name:
[:en] Big [:fr] Grand
In functions.php
function translate_q ($echo) {
if (function_exists('qtrans_split')) {
$selectLanguage = qtrans_split($echo);
return $selectLanguage[qtrans_getLanguage()];
} else {
return $echo;
}
}
qtrans_split and qtrans_getLanguage are functions created by qTranslate.
From JigoShop plugin directory I opened jigoshop_template_functions.php, I grabbed from jigoshop_breadcrumb() function all the echos in $echo variable and at the end I have:
echo function_exists('translate_q') ? translate_q($echo) : $echo;
You will have to do the same thing in other places in JigoShop. I posted here to be a starting point.

Wordpress custom post type hierarchy and menu highlighting (current_page_parent)

I have created a custom post type of 'portfolio' and page with a template that retrieves all posts matching that custom post type.
The problem is when I drill down into the actual post, the post seems to sit under 'blog' in the main menu highlighting (displays current_page_parent as a class)
The permalink url is correct: www.site.com/portfolio/post-slug
But the menu thinks the parent is 'blog'.
This is obviously a hierarchical issue but I don't know what to do to fix it.
It appears this is an issue with the core Wordpress code; the code that generates the menu classes adds current_page_parent to your Blog page everywhere except when viewing static page templates.
(This has been discussed in passing at http://core.trac.wordpress.org/ticket/13543).
You can however get around this with some custom code using the page_css_class filter. For example, add something along these lines to functions.php (not 100% tested):
function my_page_css_class($css_class, $page) {
if (get_post_type()=='portfolio' || is_page(57)) {
if ($page->ID == get_option('page_for_posts')) {
foreach ($css_class as $k=>$v) {
if ($v=='current_page_parent') unset($css_class[$k]);
}
}
if ($page->ID==57) {
$css_class[]='current_page_parent';
}
}
return $css_class;
}
add_filter('page_css_class','my_page_css_class',10,2);
Replacing 57 with the ID of your portfolios page, of course. That removes current_page_parent when printing the blog page and adds current_page_parent to your portfolios page, when either viewing a single portfolio or viewing the portfolios page itself.
Here is my optimized/extended version of previously suggested solutions, which is pretty much fully automated. No more extra CSS or menu attributes needed.
This version dynamically gets a list of custom post types and if the current post type is a custom post type, then it removes the 'current_page_parent' class from all menu items.
Furthermore it checks each menu item to see if it's for a page with a page template like "page-{custom_post_type_slug}.php", and if so, it'll add the 'current_page_parent' class.
The filter priority is 1, as some themes, replace the current_page_parent/etc. classes with a class like 'active' (eg. 'roots' does this), so this filter needs to execute first.
Lastly, it makes use of 3 static variables since this function is repeatedly called and these (obviously) remain the same through all calls.
function theme_current_type_nav_class($css_class, $item) {
static $custom_post_types, $post_type, $filter_func;
if (empty($custom_post_types))
$custom_post_types = get_post_types(array('_builtin' => false));
if (empty($post_type))
$post_type = get_post_type();
if ('page' == $item->object && in_array($post_type, $custom_post_types)) {
$css_class = array_filter($css_class, function($el) {
return $el !== "current_page_parent";
});
$template = get_page_template_slug($item->object_id);
if (!empty($template) && preg_match("/^page(-[^-]+)*-$post_type/", $template) === 1)
array_push($css_class, 'current_page_parent');
}
return $css_class;
}
add_filter('nav_menu_css_class', 'theme_current_type_nav_class', 1, 2);
PS. Just to point out one shortcoming in all non-CSS solutions I've seen so far, including my own:
Something not taken into account is highlighting the menu item parent/ancestor of an item linking to a page which displays posts of the current custom post type. Consider a custom post type "product" and a menu like:
Home Company News Contact
|
\--About Us
\--Products
"Products" is a page with a template "page-product.php" and shows an overview of posts of type 'product'. It is highlighted due to posted solution. However 'Company' as its parent/ancestor should also be highlighted, but isn't. Something to keep in mind.
WP ticket: http://core.trac.wordpress.org/ticket/16382
function fix_blog_menu_css_class( $classes, $item ) {
if ( is_tax( 'my-cat-tax' ) || is_singular( 'my-post-type' ) || is_post_type_archive( 'my-post-type' ) ) {
if ( $item->object_id == get_option('page_for_posts') ) {
$key = array_search( 'current_page_parent', $classes );
if ( false !== $key )
unset( $classes[ $key ] );
}
}
return $classes;
}
add_filter( 'nav_menu_css_class', 'fix_blog_menu_css_class', 10, 2 );
I did some more looking around on this and found another way of doing this.
add_filter('nav_menu_css_class', 'current_type_nav_class', 10, 2);
function current_type_nav_class($css_class, $item)
{
if (get_post_type() === 'portfolio') {
$current_value = 'current_page_parent';
$css_class = array_filter($css_class, function ($element) use ($current_value) {
return ($element != $current_value);
});
}
$post_type = get_query_var('post_type');
if ($item->attr_title !== '' && $item->attr_title === $post_type) {
array_push($css_class, 'current_page_parent');
};
return $css_class;
}
I got some help form this post and then modified it to also remove the "current_page_parent" class from the blog page.
https://wordpress.stackexchange.com/questions/3014/highlighting-wp-nav-menu-ancestor-class-w-o-children-in-nav-structure/3034#3034
Cordially
Vayu
As explained at https://core.trac.wordpress.org/ticket/16382, .current_page_parent matches "anything that isn't a page" for the sake of backwards compatibility (bear in mind that this was considered backwards 10 years ago...) so themes nowadays really shouldn't still be using it.
So the simplest solution, and the most efficient (since unlike previous answers it doesn't require running extra code on every page load), is to modify your theme's CSS to replace use of the .current_page_parent class selector with .current-menu-parent, which does the right thing. (NB underscores vs hyphens.)
If you are using a third-party theme and don't want to modify it directly, then you can overwrite its properties in your own stylesheet. For example, if your theme has:
.current_page_parent > a {
border-bottom: 4px solid blue;
}
then in your child theme's stylesheet you would do this to cancel out its effects, and apply them to the correct class:
.current_page_parent > a {
border-bottom: transparent !important; /* Cancel out incorrect styling */
}
.current-menu-parent > a {
border-bottom: 4px solid blue; /* Add styling correctly */
}
This is just an example - the correct way will depend on how your theme is styling these links.
Here is a solution that worked for me, without having to define my custom post type or menu id or page id in the code:
http://dtbaker.net/web-development/how-to-stop-wordpress-automatically-highlighting-the-blog-page-in-the-menu/
function dtbaker_wp_nav_menu_objects($sorted_menu_items, $args){
// this is the code from nav-menu-template.php that we want to stop running
// so we try our best to "reverse" this code wp code in this filter.
/* if ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && empty( $wp_query->is_page ) && $home_page_id == $menu_item->object_id )
$classes[] = 'current_page_parent'; */
// check if the current page is really a blog post.
//print_r($wp_query);exit;
global $wp_query;
if(!empty($wp_query->queried_object_id)){
$current_page = get_post($wp_query->queried_object_id);
if($current_page && $current_page->post_type=='post'){
//yes!
}else{
$current_page = false;
}
}else{
$current_page = false;
}
$home_page_id = (int) get_option( 'page_for_posts' );
foreach($sorted_menu_items as $id => $menu_item){
if ( ! empty( $home_page_id ) && 'post_type' == $menu_item->type && empty( $wp_query->is_page ) && $home_page_id == $menu_item->object_id ){
if(!$current_page){
foreach($sorted_menu_items[$id]->classes as $classid=>$classname){
if($classname=='current_page_parent'){
unset($sorted_menu_items[$id]->classes[$classid]);
}
}
}
}
}
return $sorted_menu_items;
}
add_filter('wp_nav_menu_objects','dtbaker_wp_nav_menu_objects',10,2);

Resources