Check the theme location within a Wordpress plugin - wordpress

I want to improve a Wordpress plugin that adds one or more flags to a menu in conjunction with WPML. (plugin name: WPML flag in menu)
It should only work with menus in the primary location and not in other locations like sidebars or in the footer.
<?php
/*
Plugin Name: WPML flag in menu
Plugin URI: http://www.MijnPress.nl
Description: Shows translated flags (for every language except current viewing lang) in the default or wp_nav_menu at last position
Version: 1.1
Author: Ramon Fincken
Author URI: http://www.MijnPress.nl
*/
add_filter( 'wp_nav_menu_items', 'plugin_wpml_flag_in_menu' );
function plugin_wpml_flag_in_menu($items, $args = NULL)
{
if(function_exists('icl_get_languages'))
{
$languages = icl_get_languages('skip_missing=0&orderby=code');
$new_items = '';
if(!empty($languages)){
foreach($languages as $l){
// Exclude current viewing language
if($l['language_code'] != ICL_LANGUAGE_CODE)
{
$new_items .= '<li class="menu-item menu-item-type-post_type menu-item-object-page">';
if(!$l['active']) $new_items .= '<a href="'.$l['url'].'">';
if($l['country_flag_url']){
$new_items .= '<img src="'.$l['country_flag_url'].'" height="12" alt="'.$l['language_code'].'" width="18" />';
}
// $items .= icl_disp_language($l['native_name'], $l['translated_name']);
if(!$l['active']) $new_items .= '</a>';
$new_items .= '</li>';
}
}
}
}
// Idea by Simon Weil
if(is_rtl())
{
$items = $new_items.$items;
}
else
{
$items .= $new_items;
}
return $items;
}
?>
I want to extend the if-statement ("if(function_exists('icl_get_languages'))" by something like "if(function_exists('icl_get_languages') && $location == 'primary')"
but I have no clue how to get the value of the "current location".

The theme_location is available through the $args:
add_filter( 'wp_nav_menu_items', 'plugin_wpml_flag_in_menu', 10, 2 );
function plugin_wpml_flag_in_menu( $items, $args ) {
if( $args->theme_location == 'primary' ) {
// do stuff
}
return $items;
}

Related

ACF menu item modification in WordPress

im trying to put icons in front of every menu item with ACF. I used this tutorial here https://www.advancedcustomfields.com/resources/adding-fields-menu-items/
It works perfectly but it always add icon AFTER the menu item but I need it to put it IN FRONT of it. I believe it is just some minor code edit I cant see.
Here is my code:
add_filter('wp_nav_menu_objects', 'my_wp_nav_menu_objects', 10, 2);
function my_wp_nav_menu_objects( $items, $args ) {
// loop
foreach( $items as &$item ) {
// vars
$icon = get_field('icon', $item);
// append icon
if( $icon ) {
$item->title .= ''.$icon.'';
}
}
// return
return $items;
}
Thank you for any help.
ms
what you do there is that you add it after the title,
so insted of: $item->title .'' . $icon . '';
It should look like this: $item->title = $icon . $item->title;

How to display featured image on Wordpress category rss feed?

This below code is working for post and not for category:
function featuredtoRSS($content) {
global $post;
if ( has_post_thumbnail( $post->ID ) ){
$content = '<div>' . get_the_post_thumbnail( $post->ID, 'medium', array(
'style' => 'margin-bottom: 15px;' ) ) . '</div>' . $content;
}
return $content;
}
add_filter('the_excerpt_rss', 'featuredtoRSS');
add_filter('the_content_feed', 'featuredtoRSS');
How to modify it?
assume that all your posts are come from single.php. WordPress provides has_category() function to check if post has specific category.
So your code on single.php will need to be like something in given below
if( has_category('video') ){
the_post_thumbnail();
}
where it checks if post has 'video' category. And if it is true then the feature image will be displayed. otherwise, it can't. Hope it will be help you.
If you want to use a plugin you can use a plugin. If the plugin does not support displaying images in the rss feed you can add this in the function.php file. Something like:
function cattitlerss($content) {
$postcat = "";
foreach((get_the_category()) as $cat) {
$postcat .= ' ('.$cat->cat_name . ')';
}
$content = do_shortcode('[wp_custom_image_category onlysrc="false" size="full" term_id="123" alt="alt :)"]');
return $content;
}
add_filter('the_title_rss', 'cattitlerss');

How-to get a menu label via $post-> or $page->ID

Entirely Revised Please Reread
Hello,
The theme I am using displays the page's title as opposed to it's menu label in the breadcrumbs. I am trying to get the breadcrumbs to instead display the associated menu label if it is available and if not then default to the page_title.
I have come up with some code that I think is close. Line 4/// $menu_items = wp_get_nav_menu_items( $slug ); returns null and it should return the nav item that contains $slug of the current post. Obviously, there is something I do not understand.
What I am attempting to do is get the slug of the current post, then using the slug get the nav item post. Then extract the title of the nav item and use that in place of the page title in the breadcrumbs. If the page was not in the nav system then it should default to the page title, as might be the case for a ppc campaign landing page.
if ( is_page() && !$post->post_parent ) {
$title = null;
$slug = mpactMEDIA_get_the_slug( get_the_ID() );
$menu_items = wp_get_nav_menu_items( $slug );
//var_dump((array)$menu_items);
foreach ( (array)$menu_items as $key => $menu_item ) {
$title = $menu_item->post_title;
}
if ( $title ) { echo $delimiter . ' ' . $before . $title . $after; }
else { echo $delimiter . ' ' . $before . get_the_title() . $after; }
}
I'm my functions.php file I have the following function
function mpactMEDIA_get_the_slug( $id=null ){
if( empty($id) ) global $post;
if( empty($post) ) return '';
$id = $post->ID;
endif;
$slug = basename( get_permalink($id) );
return $slug;
}
Thank you in advance,
Tim
I read the question a few times, I got here searching for an answer, ended up making my own.
function get_menu_label_by_post_id($post_id, $menu) {
$menu_title = '';
$nav = wp_get_nav_menu_items($menu);
foreach ( $nav as $item ) {
if ( $post_id == $item->object_id ) {
$menu_title = $item->post_title;
break;
}
}
return ($menu_title !== '') ? $menu_title : get_the_title($post_id);
}
Example usage:
echo get_menu_label_by_post_id($post->ID, 'Primary Nav');
This will return what the menu label is if it finds it, otherwise just the title of the post ID.
Check the documentation for wp_get_nav_menu_items. It doesn't take a page slug as a parameter at all.
If you want to list child pages of a given page, use wp_list_pages and pass a child_of parameter to it.
Also, as a side note, if you know the $post and want the slug, it's just $post->post_name

Wordpress remove shortcode and save for use elsewhere

Trying to remove the gallery shortcode from the post content and save in a variable for use elsewhere in the template. The new Wordpress gallery tool is great for selecting which images they want and assigning captions, hoping to use this to create the gallery, but then pull it out of the content on the front-end.
So this little snipped works just fine for removing the gallery and reapplying formatting... however I want to save that gallery shortcode.
$content = strip_shortcodes( get_the_content() );
$content = apply_filters('the_content', $content);
echo $content;
Hoping to save the shortcode so it can be parsed into an array and used to recreate a custom gallery setup on the front-end. An example of this shortcode I'm trying to save is...
[gallery ids="1079,1073,1074,1075,1078"]
Any suggestions would be greatly appreciated.
Function to grab First Gallery shortcode from post content:
// Return first gallery shortcode
function get_shortcode_gallery ( $post = 0 ) {
if ( $post = get_post($post) ) {
$post_gallery = get_post_gallery($post, false);
if ( ! empty($post_gallery) ) {
$shortcode = "[gallery";
foreach ( $post_gallery as $att => $val ) {
if ( $att !== 'src') {
if ( $att === 'size') $val = "full"; // Set custom attribute value
$shortcode .= " ". $att .'="'. $val .'"'; // Add attribute name and value ( attribute="value")
}
}
$shortcode .= "]";
return $shortcode;
}
}
}
// Example of how to use:
echo do_shortcode( get_shortcode_gallery() );
Function to delete First gallery shortcode from Post content:
// Deletes first gallery shortcode and returns content
function strip_shortcode_gallery( $content ) {
preg_match_all( '/'. get_shortcode_regex() .'/s', $content, $matches, PREG_SET_ORDER );
if ( ! empty( $matches ) ) {
foreach ( $matches as $shortcode ) {
if ( 'gallery' === $shortcode[2] ) {
$pos = strpos( $content, $shortcode[0] );
if ($pos !== false)
return substr_replace( $content, '', $pos, strlen($shortcode[0]) );
}
}
}
return $content;
}
// Example of how to use:
$content = strip_shortcode_gallery( get_the_content() ); // Delete first gallery shortcode from post content
$content = str_replace( ']]>', ']]>', apply_filters( 'the_content', $content ) ); // Apply filter to achieve the same output that the_content() returns
echo $content;
just use the get_shortcode_regex():
<?php
$pattern = get_shortcode_regex();
preg_match_all('/'.$pattern.'/s', $post->post_content, $shortcodes);
?>
that will return an array of all the shortcodes in your content, which you can then output wherever you feel, like so:
<?php
echo do_shortcode($shortcodes[0][1]);
?>
similarly, you could use the array entries to check for shortcodes in your content and remove them with str_replace():
<?php
$content = $post->post_content;
$content = str_replace($shortcodes[0][1],'',$content);
?>
Something like $gallery = do_shortcode('[gallery]'); might work.

How to show recent post in the main domain from subdomain blog

need to show the recent post from my subdomain to my main domain frontend. I am using below code, but its picking only main domain recent post. any help to fetch subdomain recent post ?
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ){
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
EDIT 2:
So it turns out, that you are not running both sites from the same WordPress installation(otherwise referred to as a WordPress Network). Here is what I can suggest that you use in this case.
Put this code in the main site's functions.php:
/**
* this function retrieves the requested part of the main site
* ok, well basically can be from any site, depending on the $url param, as long as it has the proper function that will display the requested content
* #param $url - the url of the site
* #param $key - part of the name of the function that will display the content
* #param $add_qs - any additional query string that will be appended, use "&params=param1,param2,param3" to pass "param1", "param2" and "param3"
* to the loading function
*/
function get_main_site_part($url, $key, $add_qs = '') {
// cache the result, so we don't make a request with each page load
$cache = ABSPATH . 'wp-content/uploads/main_site_' . $key . '.txt';
$cache_lifetime = 300;
// just to make sure - try to remove the trailing slash in the $url
$url = untrailingslashit($url);
$uri = $url . '/?including_template_part=1&load_part=' . $key . $add_qs;
# reload the cache on every 5 minutes
if (!file_exists($cache) || time() - filemtime($cache) > $cache_lifetime) {
$main_site_html = wp_remote_get($uri);
if (is_a($main_site_html, 'WP_Error')) {
//print_r($main_site_html);
//exit('error! ');
return;
}
$fp = fopen($cache, 'w');
fwrite($fp, $main_site_html);
fclose($fp);
} else {
$main_site_html = file_get_contents($cache);
}
return $main_site_html;
}
Now put this function in your sub-domain's functions.php:
/* HTML LOADING HOOK - For loading content from one site to another - best application in multisite */
function print_requested_template_part() {
// Respond only to requests from the same address...
if ( $_SERVER['REMOTE_ADDR'] == $_SERVER['SERVER_ADDR'] && $_SERVER['REQUEST_METHOD'] == 'GET' && isset($_GET['including_template_part']) && isset($_GET['load_part']) && $_GET['load_part'] != '' ) {
$part = $_GET['load_part'];
$func = 'render_' . str_replace('-', '_', $part); // if you have declared a function called "render_footer_include", then "?load_part=footer_include"
if ( function_exists($func) ) {
// Allow for passing parameters to the function
if ( isset($_GET['params']) ) {
$params = $_GET['params'];
$params = ( strpos($params, ',') !== false )? explode(',', $params) : array($params);
call_user_func_array($func, $params);
} else {
call_user_func($func);
}
}
exit; // if we don't exit here, a whole page will be printed => bad! it's better to have empty footer than a footer with the whole main site...
}
}
add_action('init', 'print_requested_template_part', 1);
function render_my_recent_posts( $numberposts = 5 ) { ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul><?php
}
Then in your main site call this function, where you want your recent posts to appear:
echo get_main_site_part( 'http://questions.admissiontimes.com/', 'my_recent_posts', '&params=5' )
EDIT 1:
Using the sample code that you have in your question, combined with my solution from below, here is what the final code will look like:
<?php
switch_to_blog( 2 ); // Switch to the blog that you want to pull posts from. You can see the ID when you edit a site through the Network Admin - the URL will look something like "http://example.com/wp-admin/network/site-info.php?id=2" - you need the value of "id", in this case "2" ?>
<h2>Recent Posts</h2>
<ul>
<?php
$args = array( 'numberposts' => '5' );
$recent_posts = wp_get_recent_posts( $args );
foreach( $recent_posts as $recent ) {
echo '<li><a href="' . get_permalink($recent["ID"]) . '" title="Look '.esc_attr($recent["post_title"]).'" >' . $recent["post_title"].'</a> </li> ';
}
?>
</ul>
<?php restore_current_blog(); // Restore the current blog ?>
Now, you just put that code wherever you had your original code and everything should be working properly.
You need to switch to the blog in question, using the switch_to_blog($blog_id) function, where $blog_id is the ID of the blog(sub-site) in question.
Then do your normal get_posts/or equivalent/ function and display/store the posts in the way you want.
Once you're done with that, just call restore_current_blog() and that's it.

Resources