I'm writing a plugin that adds a page with a tag [deposit_page]; that tag should be replaced with some PHP code.
This is what I have, but it doesn't work. Is there something I'm missing or doing wrong?
function deposit_page_content($content) {
$deposit_page_content = "here will go the content that should replace the tags";//end of variable deposit_page_content
$content=str_ireplace('[deposit_page]',$deposit_page_content,$content);
return $content;
}
add_filter("the_content", "deposit_page_content");
I just noticed I gave the same variable name to the content that should replace the tag and the function itself. Could this be the problem?
WordPress has support for [square_bracket_shortcodes] built in.
See: http://codex.wordpress.org/Shortcode_API
Here is your simple example:
function deposit_page_shortcode( $atts ) {
$deposit_page_content = "here will go the content that should replace the tags";
return $deposit_page_content;
}
add_shortcode( 'deposit_page', 'deposit_page_shortcode' );
You can paste this into your active theme's functions.php file.
If you wanted attributes, like [my_shortcode foo=bar], you'd do, at the top of this function:
extract(shortcode_atts(array(
'foo' => 'default foo',
'example' => 'default example',
), $atts));
// Now you can access $foo and $example
Related
I'm building a simple plugin that uses the geoservices web service and what I'm trying to do is dynamically change the content on a WordPress page based on their location. I have it working somewhat but my issue is that it's returning both the location-specific text AND the default. I know it's because i'm using the shortcode instance more than once but I don't know how to change it to ONLY show the location specific content and if the location is not set or does not match the shortcode params then fall back to the default one. I don't want to add "default" as a shortcode param because it could contain HTML or something else.
Here is an example of my shortcode:
[geo city="Orlando"]555-123-6349[/geo][geo city="Raleigh"]919-999-9999[/geo][geo city="Default"]Default text here[/geo]
So based on the above, the desired result would show Orlando's phone number if the user is from Orlando or it would show Raleigh number if they are from Raleigh. Otherwise, if they are not from either of those places, it would use the default.
Here is my shortcode:
function geo_services( $atts , $content = null ) {
// Attributes
extract(shortcode_atts(array(
'city' => '',
'state' => '',
), $atts));
require_once('geoplugin.class.php');
$geoplugin = new geoPlugin();
$geoplugin->locate();
if($city === $geoplugin->city){
return $content;
} elseif ($state === $geoplugin->region){
return $content;
} elseif ($city === 'Default') {
return $content;
}
}
add_shortcode( 'geo', 'geo_services' );
And here is what is happening when I use the example shortcode above:
I believe you may be misunderstanding how shortcodes work in WP. In your example, you have added 3 shortcodes to the content. Each of those shortcodes is going to run. Not one or the other. So doing,
[geo city="Orlando"]555-123-6349[/geo][geo city="Raleigh"]919-999-9999[/geo][geo city="Default"]Default text here[/geo]
means that each of those will be called and evaluated. $geoplugin->city is always going to return the city of the user, regardless of what attributes you supplied. And since you are returning $content in all cases, it will always spit out the content that you added inside the shortcode. This is why you are seeing all 3 responses.
Instead, I would try the approach below. If your goal is to spit out content based on the city of the user, you really don't need to supply an attribute to the shortcode. See the following example:
//in your post/page content, simply use the shortcode geo
[geo]
//your function should be
function geo_services( $atts , $content = null ) {
//
require_once('geoplugin.class.php');
//
$geoplugin = new geoPlugin();
$geoplugin->locate();
//
switch( $geoplugin->city ) {
case 'Orlando':
return '555-123-6349';
break;
case 'Raleigh':
return '919-999-9999';
break;
default:
return 'Default text here';
break;
}
}
add_shortcode( 'geo', 'geo_services' );
Providing another answer based on OP comments. If you really need to manage the content via the WYSIWYG, then you could supply the content for each city as an attribute.
//add shortcode to post/page content
[geo orlando="555-123-6349" raleigh="919-999-9999" default="Custom default text here"]
//your function should be
function geo_services( $atts , $content = null ) {
//don't use extract since we expect X number of atts now
$atts = shortcode_atts(array(
'default' => 'Default text here'
), $atts);
//
require_once('geoplugin.class.php');
//
$geoplugin = new geoPlugin();
$geoplugin->locate();
//was the city provided as an attribute?
if( isset($atts[ strtolower($geoplugin->city) ]) ) {
return $atts[ strtolower($geoplugin->city) ];
}else {
return $atts['default'];
}
}
add_shortcode( 'geo', 'geo_services' );
You may have to get creative with the HTML portion of the content, but now you can include X number of cities, with their custom content, in the shortcode itself. If the city is not supplied, or does not match, it will fallback to the default.
I’m looking for a way to send all WordPress emails using a custom WooCommerce template so all emails will look the same.
The path to the template would be:
woocommerce/emails/my-custom-woocommerce-template.php
Does it have to all be templatized in a single file? If not, a combination of these entry points can probably get you the standardization you're looking for:
email-header.php lets you customize the start of the email including the header image (if you need to do more than change its URL). It opens the layout tags for the rest of the email content
email-footer.php lets you customize the footer, and closes the layout tags started in the header.
email-styles.php or the woocommerce_email_styles filter let you customize the CSS (see some gotchas in my article here).
Various actions/filters are scattered throughout the emails for customizing individual parts.
You can use the below function. It is working
function myplugin_woocommerce_locate_template( $template, $template_name, $template_path ) {
global $woocommerce;
// List of all templates that should be replaced with custom template
$woo_templates = array(
'emails/admin-new-order.php',
'emails/admin-failed-order.php',
'emails/admin-cancelled-order.php',
'emails/customer-completed-order.php',
'emails/customer-new-account.php',
'emails/customer-note.php',
'emails/customer-on-hold-order.php',
'emails/customer-processing-order.php',
'emails/customer-refunded-order.php',
'emails/customer-reset-password.php',
);
//Check whether template is in replacable template array
if( in_array( $template_name, $woo_templates ) ){
// Set your custom template path
$template = your_template_path.'emails/my-custom-woocommerce-template';
}
// Return what we found
return $template;
}
add_filter( 'woocommerce_locate_template', 'myplugin_woocommerce_locate_template', 10, 3 );
add_filter( 'wp_mail', 'your_wp_mail_action' ); // $args = compact( 'to', 'subject', 'message', 'headers', 'attachments' )
function your_wp_mail_action( $args ) {
global $your_prefix_your_email_args; // the args you could use in my-custom-woocommerce-template file
$your_prefix_your_email_args = $args;
ob_clean();
get_template_part( 'woocommerce/emails/my-custom-woocommerce-template' );
$args['message'] = ob_get_clean();
// ... your logic
return $args;
}
To view and update email settings, log into your website dashboard. In the left-hand menu, click on WooCommerce → Settings.
There, you’ll find several options tabs at the top. Click Emails to view the following templates
you can custom all as you want
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.
I have added a menu using add_menu_page which all works correctly, but when clicked I want this menu page to open the post editor for a particular post id.
As a proof of concept i have tried echoing a javascript redirect out into the do function like so...
// Load up the menu page
function register_availability_custom_menu_page() {
add_menu_page('custom menu title', 'Availability', 'add_users', 'options', 'options_do_page');
}
function options_do_page() {
echo "<script type=\"text/javascript\">";
echo "window.location = '/whatever_page.php';";
echo "</script>";
}
This approach does work but I was wondering if it is the best approach, is there a better way to redirect to the page I am after?
UPDATE
I have now also tried using wp_redirect with this code...
add_action( 'admin_menu' , 'admin_menu_new_items' );
function admin_menu_new_items() {
wp_redirect( home_url() );
exit;
}
This gives me a Headers already sent error, can anyone suggest where I am going wrong?
If I'm understanding this correctly, you don't need the redirect. Instead of using a $menu_slug in the function add_menu_page, put the address of the target page, e.g.:
$the_post_title = 'The Portfolio';
add_action( 'admin_menu', 'wpse_59050_add_menu' );
function wpse_59050_add_menu()
{
global $the_post_title;
$our_page = get_page_by_title( $the_post_title );
$settings_page = add_menu_page(
'Edit '.$our_page->post_title,
'Edit '.$our_page->post_title,
'add_users',
'/post.php?post='.$our_page->ID.'&action=edit',
'',
'',
2
);
}
This function is from the following WordPress Answer: Highlighting a Menu Item by Post Name. You'll need some jQuery to do the correct highlighting of this top level menu, check both my and TheDeadMedic answers in that Q.
This other one is useful too: Add highlighting to new Admin Dashboard Menu Item.
Recently did this for pootle page builder, and this AFAIK is the best way,
/**
* Redirecting from Page Builder > Add New page
* #since 0.1.0
*/
function add_new() {
global $pagenow;
if ( 'admin.php' == $pagenow && 'page_builder_add' == filter_input( INPUT_GET, 'page' ) ) {
header( 'Location: ' . admin_url( 'whatever-page.php' ) );
die();
}
}
add_action( 'admin_init', 'add_new' );
Replace page_builder_add with your page slug and admin_url( 'whatever-page.php' ) with url you wanna redirect to.
We always use scrutinizer-ci for best code practices and maintain code score greater than 9.5/10, so all code (Including this) is secure and optimized ;)
Lemme know how it works for ya.
Cheers
I found a 2-step solution that doesn't use JS/JQ.
Step 1:
Near the top of your script, put the following PHP to display CSS that hides your first page:
add_action('admin_head', 'hide_my_first_page');
function hide_my_first_page(){
echo '<style>
a[href="admin.php?page=admin_menu_slug"] + ul > li.wp-first-item{
display: none;
}
</style>';
}
Where admin_menu_slug is the 4th argument passed to add_menu_page();.
Step 2:
Take the function of the page you want to run and pass it as the 5th argument in add_menu_page();
I try to create a theme in WordPress, and allow the user for some Page Templates, to load either a Slide-show in the header or to display the title.
Lets say, I have a template name called, Portfolio and another page template called Portfolio with Slide-show In Head.
Can I from within the portfolio.php and portfolio-with-slide.php to send variables in the header.php in order to decide what to display, or have I to create a second header for the second option and load the one need it into the template file with get_header('title') and get_header('slide')
What is the best approach ?
I personally use the second option - create a second header for the second option and load the one need it into the template file with get_header('title') and get_header('slide').
This is the best approach in terms of code maintainability.
A proper solution is to write a filter to replace the title:
function this_is_the_title_now( $title ) {
// can return un-altered $title or can use fancy logic here
return( "This is the new title." );
}
add_filter( 'the_title', 'this_is_the_title_now', 10, 2 );
This can be put into functions.php of your theme, or in page-whatever.php.
since wordpress 5.5 get_header has $args parameter ready to use:
https://developer.wordpress.org/reference/functions/get_header/
You can just put your arguments into get_header like this:
get_header( 'yourheadername', [ 'header_arg' => 'XYZ' ] ); (if you're using customized header.php file, in this case would it be: header-yourheadername.php)
or for default header.php file:
get_header( null, [ 'header_arg' => 'XYZ' ] );
then inside your header file you can use:
<?php echo $args['header_arg']; ?>
inside if or whatever you want :-)
You can use set_query_var to send variables to your header.php file, or any template part file.
For example, in your Portfolio Slideshow template (portfolio-with-slide.php) file:
//portfolio-with-slide.php
set_query_var('includeSlideshow', true);
Then in your header.php file (or a template part file):
//Header.php
$slideshowHeader = get_query_var('includeSlideShow');
//If variable exists and is boolean true
if($slideshowHeader !== null && $slideshowHeader === true) {
//code to include slideshow in header
}