WordPress Snippets on Speckyboy Design Magazine https://speckyboy.com/topic/wordpress-snippets/ Design News, Resources & Inspiration Fri, 15 Dec 2023 06:13:24 +0000 en-US hourly 1 Getting Started with WordPress Shortcodes & Sample Snippets https://speckyboy.com/getting-started-with-wordpress-shortcodes-examples/ https://speckyboy.com/getting-started-with-wordpress-shortcodes-examples/#respond Mon, 17 Oct 2022 23:01:17 +0000 http://speckyboy.com/?p=14627 We show you how to create and use different types of shortcodes, and share ready-to-use snippets you can use on your WordPress site.

The post Getting Started with WordPress Shortcodes & Sample Snippets appeared first on Speckyboy Design Magazine.

]]>
WordPress shortcodes were introduced in 2.5 and help you to create macro codes to use within your content. If you think about it, this is a great way to create something like a dynamic ad spot or a call-to-action button in your posts.

If we use the call-to-action example, you could add something like this to your blog post to show the button and then edit the output in your templates functions.php file, which we’ll get to in a minute.

[button]

To customize the button, we could add something like the following:

[button type="twitter"]

Or, to make it even better, we could use an enclosing shortcode:

[button type="twitter"]Follow me on Twitter![/button]

With some imagination, you soon realize the potential of shortcodes and what can be done with them. In this article, I’ll show you how to create and use these three different types of shortcodes, and then I’ll show off some ready-to-use shortcodes to use on your own WordPress site.



Creating a Self-Closing Shortcode

The simplest shortcode is the self-closing one. We will create a simple link to a Twitter account and then add it to a blog post.

All the code goes in functions.php, which is located in /wp-content/themes/your-theme/. If you don’t have one, create it and put the code in it.

<?php 
function button_shortcode() {
    return '<a href="http://twitter.com/filipstefansson" class="twitter-button">Follow me on Twitter!</a>"';
}
add_shortcode('button', 'button_shortcode'); 
?>

Usage:

[button]

Simply using the add_shortcode() function, we can link any PHP function to our shortcode. In this simple example, all we do is return a link to the Twitter account, but let’s take this a step further and add some parameters.

Creating a Self-Closing Shortcode with Parameters

Shortcode has support for parameters, which lets us customize the output. In this example, we have two different buttons, so we have to define what button we want to show.

<?php
function button_shortcode($type) {
    extract(shortcode_atts(array(
        'type' => 'type'
    ), $type));
    
    // check what type the user entered
    switch ($type) {
        case 'twitter':
            return '<a href="http://twitter.com/filipstefansson" class="twitter-button">Follw me on Twitter!</a>';
            break;
        case 'rss':
            return '<a href="http://example.com/rss" class="rss-button">Subscribe to the feed!</a>'
            break;
    }
}
add_shortcode('button', 'button_shortcode');
?>

Now you can choose what button to display by defining type in your shortcode.

[button type="twitter"]
[button type="rss"]

This is great. But what if we wanted to change the text? We could keep on adding shortcode types like [button type="twitter-2"] and so on, but that’s not very dynamic. Let’s see how to do this the right way.

Creating an Enclosing Shortcode

The enclosing shortcode allows you to embed content within your shortcode, just like BBCode if you’ve ever used that.

<?php
function button_shortcode( $attr, $content = null ) {
    return '<a href="http://twitter.com/filipstefansson" class="twitter-button">' . $content . '</a>';
}
add_shortcode('button', 'button_shortcode');
?>

To use this shortcode, you embed the text you want to use like this:

[button]Follow me on Twitter![/button]

To make this button even better, we could add parameters as we did in the previous example. Let’s add two parameters this time, one for the Twitter username and one for the button style.

Then we can have different types of buttons and choose what Twitter account we want to link the button to.

<?php
function button_shortcode( $atts, $content = null ) {
   extract( shortcode_atts( array(
      'account' => 'account',
      'style' => 'style'
      ), $atts ) );

   return '<a href="http://twitter.com/' . esc_attr($account) . '" class="twitter-button ' . esc_attr($style) . '">' . $content . '</a>';
}
add_shortcode('button', 'button_shortcode');
?>

Usage:

[button account="filipstefansson" style="simple"]Follow me on Twitter![/button]
// Result: &lt;a href="http://twitter.com/filipstefansson" class="twitter-button simple">Follow me on Twitter!&lt;/a>

Now we have a customizable button that we can link to any Twitter account. As I’m sure you understand, you can create much more advanced shortcodes than this, but this is a good start.

Shortcodes in Widgets & Template Files

Now that you have seen the power of shortcodes, you may be wondering why you can’t use them in your widgets and your template files. Well, it turns out you can.

To activate shortcodes in your widgets, just put the following code in functions.php:

add_filter('widget_text', 'do_shortcode')

And to use a shortcode in your template files, you can access them by using the following:

do_shortcode("[button]");

Ready-to-Use Shortodes

Here are some cool shortcodes you can implement right away.

Code in Posts

If you run a blog that focuses on programming, you probably want to display code in your posts.

function code_shortcode( $attr, $content = null ) {
        $content = clean_pre($content); // Clean pre-tags
        return '<pre"><code>' .
               str_replace('<', '<', $content) . // Escape < chars
               '</code></pre>';
}
add_shortcode('code', 'code_shortcode');

Usage:

[code]&lt;?php echo 'Hello World!'; ?>

Embed Adsense Anywhere on Your Posts

With this shortcode, you can add a Google ad anywhere on your posts simply by using [adsense].

function showads() {
    return '<script type="text/javascript"><!--
    google_ad_client = "pub-XXXXXXXXXXXXXXXX";
    google_ad_slot = "XXXXXXXXXX";
    google_ad_width = XXX;
    google_ad_height = XX;
    //-->
    </script>
    <script type="text/javascript"
    src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
    </script>
';
}
add_shortcode('adsense', 'showads');

Embed YouTube Videos

This shortcode will let you embed YouTube videos into your blog posts.

function youtube($atts) {
   extract(shortcode_atts(array(
      "value" => 'http://',
      "width" => '475',
      "height" => '350',
      "name"=> 'movie',
      "allowFullScreen" => 'true',
      "allowScriptAccess"=>'always',
      "controls"=> '1',
   ), $atts));
   return '<object style="height: '.$height.'px; width: '.$width.'px"><param name="'.$name.'" value="'.$value.'"><param name="allowFullScreen" value="'.$allowFullScreen.'"><param name="allowScriptAccess" value="'.$allowScriptAccess.'"><embed src="'.$value.'" type="application/x-shockwave-flash" allowfullscreen="'.$allowFullScreen.'" allowScriptAccess="'.$allowScriptAccess.'" width="'.$width.'" height="'.$height.'"></object>';
}
add_shortcode("youtube", "youtube");

Usage:

// Optional attributes: width, height, name, allowFullScreen, allowScriptAccess, controls  
[youtube value="http://www.youtube.com/watch?v=1aBSPn2P9bg"]

Paypal Donation Shortcode

This shortcode helps you create donation links to your Paypal account.

function donate_shortcode( $atts, $content = null) {
    global $post;extract(shortcode_atts(array(
        'account' => 'your-paypal-email-address',
        'for' => $post->post_title,
        'onHover' => '',
    ), $atts));
    
    if(empty($content)) {
        $content='Make A Donation';
    }
    
    return '<a href="https://www.paypal.com/cgi-bin/webscr?cmd=_xclick&business='.$account.'&item_name=Donation for '.$for.'" title="'.$onHover.'">'.$content.'</a>';
}
add_shortcode('donate', 'donate_shortcode');

Usage:

[donate]
[donate]Donate Now[/donate]
[donate account="you@yoursite.com" onHover="Thanks" for="Title"]
[donate account="you@yoursite.com" onHover="Thanks" for="Title"]Donate Now[/donate]

Private Note to Authors

This last one is clever. With this shortcode, you can create notes in your posts that only the authors can see.

function sc_note( $atts, $content = null ) {
    if ( current_user_can( 'publish_posts' ) )
      return '<div class="note">'.$content.'</div>';
   return '';
}
add_shortcode( 'note', 'sc_note' );

After reading this article, I hope you love WordPress shortcodes as much as I do, and I hope you’ll start implementing them in your own blog.

The post Getting Started with WordPress Shortcodes & Sample Snippets appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/getting-started-with-wordpress-shortcodes-examples/feed/ 0
Simple WordPress Snippets to Enhance Your Secondary Navigation https://speckyboy.com/wordpress-snippets-secondary-navigation/ https://speckyboy.com/wordpress-snippets-secondary-navigation/#comments Tue, 16 Mar 2021 20:05:44 +0000 https://speckyboy.com/?p=94921 Using these WordPress snippets can further help users get where they need to go and discover content they may have otherwise missed.

The post Simple WordPress Snippets to Enhance Your Secondary Navigation appeared first on Speckyboy Design Magazine.

]]>
One of the great things about WordPress is the ability to reuse snippets of code over and over again within your themes. With that, you can build in ways to make websites easier to use.

In this article, we’re going to explore ways to enhance secondary navigation. In other words, navigation that is in addition to your site’s main menu. Adding these extra elements can further help users get where they need to go and discover content they may have otherwise missed.

Here are four such snippets you can use in your WordPress themes. While they’ll work as-is, it’s a good idea to add your own custom styles to ensure a perfect fit with your site.

Where to Place the Code Snippets: The snippets below can be placed directly into your theme’s template files. The exact file may depend on your particular theme (check the Template Hierarchy for ideas). And, to some degree, it’s a matter of personal preference. Use them where you think they’ll best serve your users.

It may also be a good idea to use conditional statements so that snippets are only displayed when certain conditions are met. For example, you might not want a particular snippet to run on your site’s home page.



1. Easily Navigate Within a Section of Pages

<?php 
if (  $post->post_parent ) { 
    $children =  wp_list_pages( array( 
        'title_li' =>  '',
        'child_of' =>  $post->post_parent, 
        'echo'     => 0 
    )  ); 
} else { 
    $children =  wp_list_pages( array( 
        'title_li' =>  '', 
        'child_of' =>  $post->ID, 
        'echo'     => 0 
    )  );
} 
if (  $children ) : ?> 
    <ul> 
        <?php  echo $children; ?> 
    </ul> 
<?php endif; ?>

Source:  WordPress Code Reference

This code makes for a great secondary navigation menu that could be used, for example, within a sidebar. It automatically displays the pages within the current section you’re browsing.

As an example, let’s say your site has an About Us page, with subpages for History, Mission Statement, and Staff. Users will be able to more easily navigate between the various pages within this section as a bulleted list of links.

2. Breadcrumb Style Page Titles

<h1  class="entry-title">
<?php
//  Conditional Statement to Check for a Parent Post
if($post->post_parent)  {
$parent_title = get_the_title($post->post_parent);
$parent_link = get_page_link($post->post_parent);
// Display Parent Post Link, Title and Separator
echo '<span  class="parent-title"><a target="_blank" href="' . $parent_link .  '">' . $parent_title . '</a></span>' . '&nbsp;<span  class="title-arrow">&#8250;</span>&nbsp; ';
}
// Display  the Current Page Title
the_title();
?>
</h1>

This snippet will check to see if the current page has a parent. If so, the parent page’s link and title are displayed within the H1 tag at the top of the page. An arrow character is also displayed between the parent and current page title to complete the breadcrumb look.

Note that this breadcrumb effect only goes one level deep. So you’ll have to adjust the code if you want to link to multiple levels (Parent » Level 1 » Level 2).

3. JS Dropdown Menu of Tags

<?php
// Show a  Drop Down Menu of Tags
echo  "<select  onChange=\"document.location.href=this.options[this.selectedIndex].value;\">";
echo  "<option>Choose a Tag:</option>\n";
foreach (get_tags() as $tag) {
echo '<option value="' . get_tag_link($tag->term_id) .  '">' . $tag->name . '</option>\n';
}
echo  "</select>";
?>

If your site takes advantage of WordPress post tags, it may be useful to provide a simple way for users to navigate between them. This is particularly effective for sites with a lot of tags.

For example, a project I worked on used tags to filter posts by a relevant geographic region (of which there were dozens). This dropdown menu utilizes JavaScript to direct the user to whichever tag they choose instantly. You can also do something similar with categories.

4. Post Archive Pagination

<?php
the_posts_pagination(  array(
'mid_size' => 5, // The number of pages displayed in the menu.
'prev_text' => __( '&laquo; Go Back', 'textdomain' ), // Previous  Posts text.
'next_text' => __( 'Move Forward &raquo;', 'textdomain' ), // Next  Posts text.
) );
?>

Source: WordPress Code Reference

While many WordPress themes have a simple back and forth navigation for post archives, it’s a nice touch to add individual page numbers to the mix. It allows for navigating to a specific page and gives the user a sense of your content depth.

Note the 'mid_size' argument in the code above. The number placed there will determine the number of pages seen between the Next and Previous text links.

Give Users a Helping Hand

Each of the snippets above can bring some measure of organization to how users access your content. This is especially important on sites that have a lot of subpages or blog posts. In the case of subpages, primary navigation can become overwhelming if you try to display every subpage. Adding secondary navigation elements provide a more straightforward way for users to find what they’re looking for.

It’s also worth noting that these snippets are meant to be used as starting points. The flexibility of PHP and CSS allows you to add your own custom functionality and look. In many ways, you’re limited only by your own imagination.

The post Simple WordPress Snippets to Enhance Your Secondary Navigation appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wordpress-snippets-secondary-navigation/feed/ 7
How to Style Wide & Full-Width Gutenberg Blocks in WordPress https://speckyboy.com/styling-wide-full-width-gutenberg-blocks-wordpress/ https://speckyboy.com/styling-wide-full-width-gutenberg-blocks-wordpress/#respond Sat, 27 Feb 2021 08:44:48 +0000 https://speckyboy.com/?p=118019 A quick WordPress tutorial that will show you how to add wide alignment support to Gutenberg Blocks and how to style them via CSS.

The post How to Style Wide & Full-Width Gutenberg Blocks in WordPress appeared first on Speckyboy Design Magazine.

]]>
The Gutenberg block editor for WordPress has changed how we create content within the CMS. But it’s also opened up some new possibilities on the front end as well.

One of the more interesting developments in this area is the ability to add “full” or “wide” blocks to a page or post. This feature adds the potential for a Gutenberg block to break out from the default width of a theme’s content – something that was nearly impossible in the old Classic Editor.

There are several possible uses for a full or wide-aligned block. You could, for instance, introduce new page sections with a full-width cover block that overlays text on an image background. Or you might leverage the feature to build a can’t-miss call-to-action area. Just about any content could be added here, which is part of the appeal.

However, there is one small caveat: Your theme must support full and wide-aligned blocks. Thankfully, it’s rather easy to do. The following is a quick tutorial for adding wide alignment support to your WordPress theme and styling the blocks via CSS.



Adding Theme Support

The first step involves adding a single line of code to your active theme’s functions.php file. Download this file from your website if you haven’t already done so (it can be found in the /wp-content/themes/yourtheme/ folder – substituting “yourtheme” for the actual name of the folder). Then, copy and paste the following PHP snippet:

add_theme_support( 'align-wide' );

Once you’ve added the code, upload the changed functions.php file back into your theme’s folder.

This code will signify that you want to turn on full and wide-aligned blocks. Now, when you log into WordPress and go to the page/post editor, you should notice that some blocks (not all) have the new “Full” and “Wide” alignment options.

Block alignments within WordPress.

Using a Commercial or Default Theme?
If you’re using a commercial or default WordPress theme, you’ll want to make sure you’re utilizing a child theme. This will let you make changes to the theme without potentially losing them after an update.

Basic Block Styling

Styling a wide or full-aligned block can be a little tricky. And there are a number of different techniques floating around. The one we’ll use here came from this example on CodePen.

@media screen and (min-width: 960px) {
     .alignwide, .alignfull {
          width:  100vw;
          max-width:  100vw;
          margin-left:  calc(50% - 50vw);
     }
}

Notice that we’re using a CSS media query to only integrate this style when the screen size is 960 pixels or wider. That’s because we won’t necessarily want this effect on smaller screens.

In this case, we have used the same styles for both block alignments. Of course, it’s entirely possible to style them separately so that they each offer a unique look on the front end.

It’s also worth noting a potential drawback: A horizontal scrollbar may appear on some layouts when using this technique. That can be taken care of via CSS with the following added to the body element:

body {
     overflow-x:  hidden;
}

The Results

Now that we’ve turned on the ability for full and wide-aligned blocks, it’s time to test things out. Here, we’ve created a page with a cover block, set to a wide alignment.

Creating a wide aligned block within WordPress.

When looking at the front end of the website, the cover block works as intended. The element spans the entire width of the page, while the content below stays within the theme’s predefined 960-pixel width.

The wide-aligned cover block displays on the front end.

Using just the default styles, this element really stands out. Still, there are plenty of opportunities to do more with the design.

By adding extra CSS classes or targeting specific blocks, we have a full arsenal of design possibilities at our disposal. Things like backgrounds, borders or clipping paths can add a unique touch.

Going Wide with WordPress Themes

In a default installation, Gutenberg doesn’t provide all the bells and whistles of a page builder plugin. But block alignments do allow us to dabble in that territory.

That’s a good thing because web design has evolved from the days when the Classic Editor first appeared. Back then, websites tended to use a uniform content width throughout.

These days, full-width sections are among the more popular and useful layout choices. The ability to take advantage of this without plugins or theme hacks makes WordPress better for designers.

The post How to Style Wide & Full-Width Gutenberg Blocks in WordPress appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/styling-wide-full-width-gutenberg-blocks-wordpress/feed/ 0
How to Avoid Common WordPress Theme Development Mistakes https://speckyboy.com/avoid-common-wordpress-theme-development-mistakes/ https://speckyboy.com/avoid-common-wordpress-theme-development-mistakes/#respond Tue, 16 Feb 2021 00:12:03 +0000 https://speckyboy.com/?p=100338 We take a look at five of the most common mistakes found in WordPress theme development and offer alternatives solutions.

The post How to Avoid Common WordPress Theme Development Mistakes appeared first on Speckyboy Design Magazine.

]]>
WordPress is known for being incredibly flexible, especially when it comes to theme and plugin development. If you ever want to see proof, just ask a group of developers how they’d implement a specific feature. The chances are that you’ll receive several different methods for accomplishing the same result. Support forums are littered with these kinds of examples.

But with that flexibility also is the reality that it’s easy to do things the “wrong” way. Now, in this case, “wrong” means that something is either inefficient or a bit of a pain to maintain down the road. While it may work in the sense of being functional, there are usually better ways to get things done.

Let’s have a look at five of the more common mistakes found in theme development, along with alternatives that will save you future headaches.



1. Using Absolute URLs in Templates

If you’ve ever looked at the HTML code a WordPress page or post produces, you’ll notice that both images and internal links use absolute (full) URLs. But this isn’t the best way to get things done when adding code to your theme templates.

As an example, let’s say you are developing a website that is using a temporary URL. A hardcoded absolute URL in a template means that you’ll have to manually make code changes when you are ready to launch the site on its permanent domain. While this can be done, it’s too easy to forget all of the spots where this type of code could be lurking.

WordPress has built-in ways to determine the correct URL – pulled right from the Settings > General area of the Dashboard.

For a link, echoing esc_url( home_url() ) will provide a full path to the home page. So, instead of explicitly placing the URL in your code, you could add a simple link back to your home page like so:

<a href="<?php echo esc_url( home_url() ); ?>" />Home</a>

What’s more, you can also use this to point to secondary pages. For example, if we wanted to link to our site’s About Us page, we could use the following code:

<a href="<?php echo esc_url( home_url() ); ?>/about-us/" />About Us</a>

A similar snippet also works for images. This example pulls an image from our active theme’s /images/ subfolder:

<img src="<?php echo esc_url( get_stylesheet_directory_uri() ) ; ?>/images/hello.png" />

2. Adding Scripts and Styles Directly to a Template

Using third-party scripts and styles with WordPress is a world of its own. When you first start out in building themes, you may be tempted to simply place <script> or <style> tags, or even a Google Font embed code directly into your theme’s header. This is generally how things are done with static HTML sites, so it makes sense to do the same here.

But, like just about everything else in WordPress, there is a better way to go about it. Instead, take advantage of wp_enqueue_script() and wp_enqueue_style() – which add scripts and stylesheets to the correct spots for you. It also makes managing assets that much easier, as everything is called from your theme’s functions.php file.

Rather than reinvent the wheel here, the WordPress Theme Handbook has a fantastic guide on how properly add scripts and styles to your theme.

Make smart development decisions

3. Calling Outside Instances of jQuery

In a related note, one of the hidden secrets of WordPress is that it already includes a copy of jQuery, along with several popular UI features. So, you don’t need to install jQuery or call it remotely. This makes it easy to take advantage of the popular JavaScript library and implement elements such as tabs, datepickers, dialogs and a whole lot more.

The only catch is that you have to specifically enable the items you want to use through your theme’s functions.php file. While that creates a bit of a learning curve, it also cuts down on bloat.

And, truth be told, it’s not overly difficult to implement a desired jQuery UI element. For example, to enable the use of jQuery UI Tabs, just add the following snippet to your functions.php:

function my_jquery_elements() {
   wp_enqueue_script( 'jquery-ui-tabs', array('jquery'));
add_action( 'template_redirect', my_jquery_elements ', 10 );

This tells WordPress to load in the element from its already-existing library. From there, design your tabs and define them as specified in the jQuery UI documentation.

4. Taking Customization Too Far

The ability to add custom fields and custom post types can make life for both developers and site content editors much easier. They offer convenience, better content organization and a more intuitive UX. But sometimes we take it too far.

I’m a huge fan of custom fields, for example. But even I admit that there have been times when I’ve customized a theme to the point of inflexibility. Fields are great for setups where we know exactly what content will need to be input – like the fields of a staff member profile.

However, it can get messy when there are inconsistencies in the types of content someone wants to add. Clients are notorious for having “minor” exceptions in content that can make using customizations more difficult. Conditional logic can account for some of this, but you can only take it so far before the UI gets out of hand.

There are no hard and fast rules for this type of customization. The only thing we can really do is use our best judgment about what should be customized and what can be better left to either the WordPress content editor or even a niche plugin. When we do add fields or post types, just know that things could change down the road and try to build with that in mind.

5. Failing to Comment Code

I’m going to make another admission here: Commenting code is not one of my strong points. It’s not that I don’t use comments at all, but it’s more that they aren’t very articulate. Usually, I’ll point out the start and end of particular items with not a ton of insight in-between. Should I be doing more? Probably so.

Commenting is important because it at least provides some reference points within the code. When digging through PHP or JS files that contain more than one thing, you’ll want to know where to find a particular item.

Even if you’re the only one who will ever edit that code, comments are highly recommended. If, for instance, you need to change something six months from now, it’s unlikely that you’re going to remember the exact spot you placed a snippet of code.

So, I’m not going to be a huge hypocrite and implore you to comment everything with great depth. But I will say that even a minimal effort here makes future maintenance easier for you or another developer that has to comb through your work.

Minimally commented code

Better Techniques Over Time

Building your own WordPress theme can be a great experience. But it does take a good bit of practice to pick up on the finer details of creating a well-coded theme and easy to maintain. The more experience you gain, the more your techniques will evolve.

I can honestly say that the first few themes I put together were nowhere near as efficient as they are now. And I’m also certain that they still might not be up-to-snuff when viewed by a truly expert developer. In that sense, our evolution is a constant one.

Finally, I’d like to note that I have personally made every one of the mistakes mentioned above. It’s only through trial and error, along with several visits to the Codex, that I found out how to start doing things the “WordPress Way.”

The lesson is that we’re all going to make mistakes. But each one provides us with a chance to learn and improve.

The post How to Avoid Common WordPress Theme Development Mistakes appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/avoid-common-wordpress-theme-development-mistakes/feed/ 0
20 Time-Saving WordPress SQL Query Snippets https://speckyboy.com/wordpress-sql-query-snippets/ https://speckyboy.com/wordpress-sql-query-snippets/#comments Thu, 22 Oct 2020 11:02:03 +0000 http://speckyboy.com/?p=72089 WordPress stores every single scrap of information within a MySQL database. Posts, pages, comments, shortcodes, plugin settings… absolutely everything. The WordPress backend is fantastic and does allow you to manage...

The post 20 Time-Saving WordPress SQL Query Snippets appeared first on Speckyboy Design Magazine.

]]>
WordPress stores every single scrap of information within a MySQL database. Posts, pages, comments, shortcodes, plugin settings… absolutely everything. The WordPress backend is fantastic and does allow you to manage and edit everything with ease, but only up to a certain point.

Say you have hundreds or even thousands of posts within your database, and you need to make site-wide global changes. Making each edit via the WordPress Dashboard can be time-consuming and does open up the possibility of mistakes occurring. If you do need to make site-wide edits, then it’s time to roll up your sleeves and delve directly into the WordPress MySQL database.



Always Backup WordPress First!

Your WordPress database stores every single one of your carefully written posts, every comment from your loyal readers, and every setting you have used to personalize your site. No matter how confident you are in your ability to use SQL queries, always remember to backup your WordPress database first!

Here are some resources to help you backup WordPress:

  • WordPress Backups – Here you will find detailed instructions to backup your WordPress Site and your WordPress database as well as resources for automatic WordPress backups (plugins).
  • Free WordPress Backup Solutions – These free WordPress backup plugins cater to every need and website.

You might also like these useful .htaccess snippets or these snippets that make WordPress user-friendly for your clients.

Add a Custom Field to All WordPress Posts & Pages

This snippet will add a custom field to every post and page found in your WP database. All you have to do is replace the UniversalCutomField to whatever Custom Field name you like to create, and then change MyCustomFieldValue to the value of your choice.

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'UniversalCustomField'
AS meta_key 'MyCustomFieldValue AS meta_value FROM wp_posts
WHERE ID NOT IN (SELECT post_id FROM wp_postmeta WHERE meta_key = 'UniversalCustomField');

For posts only, use this snippet…

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'UniversalCustomField'
AS meta_key 'MyCustomFieldValue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'UniversalCustomField')
'' AND post_type = 'post';

…and for pages only, use this code…

INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT ID AS post_id, 'UniversalCustomField'
AS meta_key 'MyCustomFieldValue AS meta_value
FROM wp_posts WHERE ID NOT IN
(SELECT post_id FROM wp_postmeta WHERE meta_key = 'UniversalCustomField')
AND 'post_type' = 'page';

Delete WordPress Post Meta

When you install or remove plugins, they use the post meta to store data. After you have removed a plugin, the data will remain in the post_meta table, which of course, is no longer needed. Remember and change YourMetaKey to your own value before running this query.

DELETE FROM wp_postmeta WHERE meta_key = 'YourMetaKey';

Identify Unused WordPress Tags

In a WordPress database, if you run a query to delete old posts, like the one above, the old tags will remain. This query allows you to identify all of the unused tags.

SELECT * From wp_terms wt
INNER JOIN wp_term_taxonomy wtt ON wt.term_id=wtt.term_id WHERE wtt.taxonomy='post_tag' AND wtt.count=0;

Batch Delete WordPress Spam Comments

This little snippet is a life-saver. All you have to do to delete them all is run this SQL command:

DELETE FROM wp_comments WHERE wp_comments.comment_approved = 'spam';

Batch Delete All Unapproved WordPress Comments

This SQL query will remove all unapproved comments and not touch the approved comments.

DELETE FROM wp_comments WHERE comment_approved = 0

Disable WordPress Comments on Older Posts

For this query, specify the comment_status as either open, closed, or registered_only. Also, specify the date by editing the 2016-01-01 to suit your needs.

UPDATE wp_posts SET comment_status = 'closed' WHERE post_date < '2016-01-01' AND post_status = 'publish';

Disabling & Enabling WordPress Trackbacks & Pingbacks

For this query, specify the comment_status as either open, closed, or registered_only.

Globally enable pingbacks/trackbacks for all users:

UPDATE wp_posts SET ping_status = 'open';

Globally disable pingbacks/trackbacks for all users:

UPDATE wp_posts SET ping_status = 'closed';

For this query, specify the ping_status as either open or closed. Also, specify the date by editing the 2016-01-01 to suit your needs.

UPDATE wp_posts SET ping_status = 'closed' WHERE post_date < '2016-01-01' AND post_status = 'publish';

Delete WordPress Comments With a Specific URL

If you have spam comments that all contain the same URL, then this query allows you to remove them in one go. The following query will delete all comments with a particular URL. The '%' means that any URL containing the string within the '%' signs will be deleted.

DELETE from wp_comments WHERE comment_author_url LIKE "%nastyspamurl%" ;

Identify & Delete WordPress Posts that are over 'X' Days Old

If you ever need to identify and delete posts over a certain number of days old, this snippet will help.

To identify any posts that are over 'X' amount of days, run this query, remembering to replace the 'X' with the number of days you are looking for:

SELECT * FROM 'wp_posts'
WHERE 'post_type' = 'post'
AND DATEDIFF(NOW(), 'post_date') > X

To delete any posts that are over 'X' amount of days, run this query:

DELETE FROM 'wp_posts'
WHERE 'post_type' = 'post'
AND DATEDIFF(NOW(), 'post_date') > X

Removing Unwanted WordPress Shortcodes

WordPress shortcodes are great, but if you decide to stop using them, their code will stay within your post content. Here is a simple SQL query to run on your database to get rid of any unwanted shortcodes. Replace unusedshortcodes with your own shortcode name.

UPDATE wp_post SET post_content = replace(post_content, '[unusedshortcodes]', '' ) ;

Change Your WordPress Posts Into Pages and Vice-Versa

Changing posts to pages is very easy. All you have to do is run this short SQL query:

UPDATE wp_posts SET post_type = 'page' WHERE post_type = 'post'

… and if you want to change pages to posts use this snippet:

UPDATE wp_posts SET post_type = 'post' WHERE post_type = 'page'

Change Author Attribution On All WordPress Posts

The first thing you will need to do for this snippet is retrieve the IDs of the WordPress author. You can find this out by using the following SQL command:

SELECT ID, display_name FROM wp_users;

Once you have the old and new IDs, insert the command below, remembering to replace NEW_AUTHOR_ID with the new author ID and OLD_AUTHOR_ID with the old.

UPDATE wp_posts SET post_author=NEW_AUTHOR_ID WHERE post_author=OLD_AUTHOR_ID;

Batch Deleting WordPress Post Revisions

Post revisions can be very useful, but they also considerably increase the size of your MySQL database. You could manually delete post revisions, but a much quicker method would be to use this SQL query.

DELETE FROM wp_posts WHERE post_type = "revision";

Disable or Enable All WordPress Plugins

If you have ever encountered the white screen of death and found yourself unable to login to the WordPress Admin after activating a new plugin, then this snippet will certainly help you. It will disable all plugins instantly, allowing you to log back in.

UPDATE wp_options SET option_value = 'a:0:{}' WHERE option_name = 'active_plugins';

Changing the Destination URL of a WordPress Site

Once you've moved your blog (template files, uploads & database) from one server to another, the next thing you will then need to do is to tell WordPress your new address.

Remember and change http://www.old-site.com to your old URL, and the http://www.new-site.com to your new URL.

The first command to use is:

UPDATE wp_options SET option_value = replace(option_value, 'http://www.old-site.com', 'http://www.new-site.com') WHERE option_name = 'home' OR option_name = 'siteurl';

Then you will have to change the url from the table wp_posts with this snippet:

UPDATE wp_posts SET guid = replace(guid, 'http://www.old-site.com','http://www.new-site.com);

And finally, you'll need to search the content of your posts to be sure that your new URL link is not messing with the old URL:

UPDATE wp_posts SET post_content = replace(post_content, ' http://www.ancien-site.com ', ' http://www.nouveau-site.com ');

Change the Default 'Admin' WordPress Username

Every WordPress installation will create an account with the default Admin username. Being able to change this default username will give your WordPress admin panel additional security.

Change YourNewUsername to your new name:

UPDATE wp_users SET user_login = 'YourNewUsername' WHERE user_login = 'Admin';

Manually Reset your WordPress Password

If you have only a single user on your WordPress installation, and the login name is 'admin,' you can reset your password with this simple SQL query. Once executed, it will replace PASSWORD with your new password.

UPDATE 'wordpress'.'wp_users' SET 'user_pass' = MD5('PASSWORD') WHERE 'wp_users'.'user_login' ='admin' LIMIT 1;

Search & Replace WordPress Post Content

To search and replace post content, use the following code. Replace OriginalText with the current text and replace NewText with your new text.

UPDATE wp_posts SET 'post_content'
= REPLACE ('post_content',
'OriginalText',
'NewText');

Changing the URL of WordPress Images

If you need to change the paths of your images, you can use this SQL command:

UPDATE wp_posts
SET post_content = REPLACE (post_content, 'src=”http://www.myoldurl.com', 'src=”http://www.mynewurl.com');

The post 20 Time-Saving WordPress SQL Query Snippets appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wordpress-sql-query-snippets/feed/ 4
10 Useful Snippets for Improving WordPress Search https://speckyboy.com/10-useful-wordpress-search-code-snippets/ https://speckyboy.com/10-useful-wordpress-search-code-snippets/#comments Sun, 19 Jan 2020 23:32:24 +0000 http://speckyboy.com/?p=7581 It is no secret that the standard search within WordPress is not the greatest. The problem is that WordPress takes your search term far too literally. In this post, we...

The post 10 Useful Snippets for Improving WordPress Search appeared first on Speckyboy Design Magazine.

]]>
It is no secret that the standard search within WordPress is not the greatest. The problem is that WordPress takes your search term far too literally.

In this post, we have ten useful WordPress search code snippets that will help improve the search accuracy for your readers. Just copy and paste.

You might also like these useful .htaccess snippets & hacks, these WordPress SQL Query Snippets, or these snippets that make WordPress user-friendly for your clients.



How To Exclude Posts or Pages from WordPress Search Results

If you would like to be able to control which posts or pages should be excluded from WordPress search results, all you have to do is copy and paste the code below into your functions.php file.

In this snippet, posts with the IDs 0 and 1 will be excluded. Edit accordingly to suit your needs.

function SearchFilter($query) {
    if ($query->is_search) {
        $query->set('cat','0,1');
    }
    return $query;
}
add_filter('pre_get_posts','SearchFilter');

WordPress Drop-Down Category Search Form

A useful function you could give to your WordPress search would be to allow your readers to filter the search results by targeting a specific category. This can be achieved by using a simple drop-down containing all of the category titles.

All you have to do is replace the standard WordPress search form (found within the searchform.php) with the snippet below:

<form role="search" method="get" id="searchform" action="<?php bloginfo('siteurl'); ?>">
  <div>
    <label class="screen-reader-text" for="s">Search for:</label>
    <input type="text" value="" name="s" id="s" /> 
    in <?php wp_dropdown_categories( 'show_option_all=All Categories' ); ?> 
    <input type="submit" id="searchsubmit" value="Search" />
  </div>
</form>

Search Within a Specific WordPress Post Type

WordPress gives you the ability to search specific post types by using this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

function SearchFilter($query) {
  if ($query->is_search) {
    // Insert the specific post type you want to search
    $query->set('post_type', 'feeds');
  }
  return $query;
}
// This filter will jump into the loop and arrange our results before they're returned
add_filter('pre_get_posts','SearchFilter');

Display the Number of Search Results Returned

If you would like to show your readers how many results have been found per search term, you could use this helpful snippet.

Open search.php and locate the following:

<h2 class="pagetitle">Search Results</h2>

And replace it with this code:

Search Result for post_count; _e(''); _e(''); echo $key; _e(''); _e(' &mdash; '); echo $count . ' '; _e('articles'); wp_reset_query(); ?>

Highlight WordPress Search Terms with jQuery

To help make your search results that little bit clearer to your readers, you could use this snippet which will highlight the searched term within the results.

Copy and paste the following code into your theme’s functions.php file:

function hls_set_query() {
  $query  = attribute_escape(get_search_query());
  if(strlen($query) > 0){
    echo '
      <script type="text/javascript">var hls_query  = "'.$query.'";</script>
    ';
  }
}
function hls_init_jquery() {
  wp_enqueue_script('jquery');
}
add_action('init', 'hls_init_jquery');
add_action('wp_print_scripts', 'hls_set_query');

And then add this code into your header.php file, just before the /head tag:

<style type="text/css" media="screen">
    .hls { background: #D3E18A; }
  </style>
  <script type="text/javascript">
  jQuery.fn.extend({
    highlight: function(search, insensitive, hls_class){
      var regex = new RegExp("(<[^>]*>)|(\\b"+ search.replace(/([-.*+?^${}()|[\]\/\\])/g,"\\$1") +")", insensitive ? "ig" : "g");
      return this.html(this.html().replace(regex, function(a, b, c){
        return (a.charAt(0) == "<") ? a : "<strong class=\""+ hls_class +"\">" + c + "";
      }));
    }
  });
  jQuery(document).ready(function($){
    if(typeof(hls_query) != 'undefined'){
      $("#post-area").highlight(hls_query, 1, "hls");
    }
  });
  </script>

Disable WordPress Search

If you are looking for a way to disable all of WordPress’s search functionality, you could use this small snippet.

All you have to do is copy and paste the code below into your functions.php file.

function fb_filter_query( $query, $error = true ) {
  if ( is_search() ) {
    $query->is_search = false;
    $query->query_vars[s] = false;
    $query->query[s] = false;

    // to error
    if ( $error == true )
      $query->is_404 = true;
  }
}
add_action( 'parse_query', 'fb_filter_query' );
add_filter( 'get_search_form', create_function( '$a', "return null;" ) );

Make your WordPress Search Results Unlimited

Sometimes you may not want your search results to be limited by the confines of the standard WordPress Loop. This snippet allows your search to return unlimited results.

In search.php you can add the following code above the loop for this functionality.

First of all find this code within search.php:

<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

And then add this code:

<?php $posts=query_posts($query_string . '&posts_per_page=-1'); ?>
<?php if (have_posts()) : ?>
<?php while (have_posts()) : the_post(); ?>

The post 10 Useful Snippets for Improving WordPress Search appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/10-useful-wordpress-search-code-snippets/feed/ 12
20 Code Snippets for Extending the Functionality of WordPress https://speckyboy.com/wordpress-snippets-extend-wordpress/ https://speckyboy.com/wordpress-snippets-extend-wordpress/#comments Tue, 27 Mar 2018 23:01:51 +0000 http://speckyboy.com/?p=11869 When coding WordPress themes, especially if you do it regularly, its really useful to have a selection of code snippets in your toolbox to just ‘copy-n-paste’ as and when the...

The post 20 Code Snippets for Extending the Functionality of WordPress appeared first on Speckyboy Design Magazine.

]]>
When coding WordPress themes, especially if you do it regularly, its really useful to have a selection of code snippets in your toolbox to just ‘copy-n-paste’ as and when the functionality needs. Not just your most commonly used code, but also some snippets that can, when required, extend WordPress even further.

Today, we have code snippets that focus on extending the functionality of WordPress even further. Just like the previous post, there are 20 very useful snippets in total, covering many areas of theme development, including tracking page-views, custom shortcodes and widgets, custom title lengths and excerpts, and much, much more.

You might also like these useful .htaccess snippets & hacks, these WordPress SQL Query Snippets, or these snippets that make WordPress user-friendly for your clients.



Automatically Add Twitter & Facebook Buttons to WordPress Posts

This snippet will add Twitter and Facebook buttons to the bottom of all your posts. All you have to do is paste the code below into your functions.php file:

function share_this($content){
    if(!is_feed() && !is_home()) {
        $content .= '<div class="share-this">
                    <a href="http://twitter.com/share"
class="twitter-share-button"
data-count="horizontal">Tweet</a>
                    <script type="text/javascript"
src="http://platform.twitter.com/widgets.js"></script>
                    <div class="facebook-share-button">
                        <iframe
src="http://www.facebook.com/plugins/like.php?href='.
urlencode(get_permalink($post->ID))
.'&amp;layout=button_count&amp;show_faces=false&amp;width=200&amp;action=like&amp;colorscheme=light&amp;height=21"
scrolling="no" frameborder="0" style="border:none;
overflow:hidden; width:200px; height:21px;"
allowTransparency="true"></iframe>
                    </div>
                </div>';
    }
    return $content;
}
add_action('the_content', 'share_this');

Track WordPress Post Views by Using Post Meta

For a simple way to keep track of the number of post views, paste this snippet into the functions.php, and then follow steps 1 and 2.

function getPostViews($postID){
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
        return "0 View";
    }
    return $count.' Views';
}
function setPostViews($postID) {
    $count_key = 'post_views_count';
    $count = get_post_meta($postID, $count_key, true);
    if($count==''){
        $count = 0;
        delete_post_meta($postID, $count_key);
        add_post_meta($postID, $count_key, '0');
    }else{
        $count++;
        update_post_meta($postID, $count_key, $count);
    }
}

Step 1: Paste the code below within the single.php within the loop:

<?php
          setPostViews(get_the_ID());
?>

Step 2: Paste the snippet below anywhere within the template where you would like to display the number of views:

<?php
          echo getPostViews(get_the_ID());
?>

Track WordPress Post View Amount by Using Post Meta

This snippet will create a list of your most popular posts based on page views. Please note that this will only work if you have already implemented the ‘Track Post View Amount by Using Post Meta’ from above.
Place this snippet just before the loop within the index.php template and WordPress will use the post views to order your posts from highest to lowest.

<?
query_posts('meta_key=post_views_count&orderby=post_views_count&order=DESC');
?>

WordPress Breadcrumbs Without a Plugin

Breadcrumbs can be a useful navigation technique that offers link to the previous page the user navigated through to arrive at the current post/page. There are plugins you could use, but the code snippet below could be an easier solution.

Paste this code into your functions.php file.

function the_breadcrumb() {
echo '<ul id="crumbs">';
if (!is_home()) {
echo '<li><a href="';
echo get_option('home');
echo '">';
echo 'Home';
echo "</a></li>";
if (is_category() || is_single()) {
echo '<li>';
the_category(' </li><li> ');
if (is_single()) {
echo "</li><li>";
the_title();
echo '</li>';
}
} elseif (is_page()) {
echo '<li>';
echo the_title();
echo '</li>';
}
}
elseif (is_tag()) {single_tag_title();}
elseif (is_day()) {echo"<li>Archive for "; the_time('F jS, Y'); echo'</li>';}
elseif (is_month()) {echo"<li>Archive for "; the_time('F, Y'); echo'</li>';}
elseif (is_year()) {echo"<li>Archive for "; the_time('Y'); echo'</li>';}
elseif (is_author()) {echo"<li>Author Archive"; echo'</li>';}
elseif (isset($_GET['paged']) && !empty($_GET['paged'])) {echo "<li>Blog Archives"; echo'</li>';}
elseif (is_search()) {echo"<li>Search Results"; echo'</li>';}
echo '</ul>';
}

Then paste the calling code below, wherever you would like the breadcrumbs to appear (typically above the title tag).

<?php the_breadcrumb(); ?>

Display the Number of Facebook Fans

Facebook is a must site for sharing your blogs articles. Here is a method for showing your visitors the total number of Facebook ‘Likes’ your blog currently has.

To use this code all you have to do is replace the YOUR PAGE-ID with your own Facebook page id.

<?php
$page_id = "YOUR PAGE-ID";
$xml = @simplexml_load_file("http://api.facebook.com/restserver.php?method=facebook.fql.query&query=SELECT%20fan_count%20FROM%20page%20WHERE%20page_id=".$page_id."") or die ("a lot");
$fans = $xml->page->fan_count;
echo $fans;
?>

Display an External RSS Feed in WordPress

This snippet will fetch the latest entries of any specified feed url.

<?php include_once(ABSPATH.WPINC.'/rss.php');
wp_rss('http://wpforums.com/external.php?type=RSS2', 5); ?>

This code takes the rss.php file that is built into WordPress (used for widgets). It is set to display the most recent 5 posts from the RSS feed ‘http://example.com/external.php?type=RSS2’.

WordPress Shortcode to Display External Files

If you are looking for a quick way to automatically include external page content within your post, this snippet will create a shortcode allowing you to do it.

Paste this code into your themes functions.php file:

function show_file_func( $atts ) {
  extract( shortcode_atts( array(
    'file' => ''
  ), $atts ) );
 
  if ($file!='')
    return @file_get_contents($file);
}
 
add_shortcode( 'show_file', 'show_file_func' );

And then post this shortcode, editing the URL, into your post or page.

[show_file file="https://speckyboy.com/2010/12/09/20-plugin-replacing-tutorials-tips-snippets-and-solutions-for-wordpress/"]

Create Custom WordPress Widgets

WordPress provides many widgets, but if you want to create custom widgets tailored to your blog, then this snippet may help you.

Paste the code below into your functions.php file.

    class My_Widget extends WP_Widget {  
        function My_Widget() {  
            parent::WP_Widget(false, 'Our Test Widget');  
        }  
    function form($instance) {  
            // outputs the options form on admin  
        }  
    function update($new_instance, $old_instance) {  
            // processes widget options to be saved  
            return $new_instance;  
        }  
    function widget($args, $instance) {  
            // outputs the content of the widget  
        }  
    }  
    register_widget('My_Widget'); 
	

Create Custom WordPress Shortcodes

Shortcodes are a handy way of using code functions within your theme. The advantage of shortcodes is that they can be easily used with the WordPress post editor.

Add this code to your functions.php:

function helloworld() {
return 'Hello World!';
}
add_shortcode('hello', 'helloworld');

You can then use [hello] wherever you want to display the content of the shortcode.

Custom Title Length

This snippet will allow you to customise the length (by the number of characters) of your post title.

Paste this code into the functions.php:

    
function ODD_title($char)
    {
    $title = get_the_title($post->ID);
    $title = substr($title,0,$char);
    echo $title;
    }

To use this function all you have to do is paste the below code into your theme files, remembering to change the ’20’ to what ever character amount you require:

<?php ODD_title(20); ?>

Custom WordPress Excerpts

Sometimes you may need to limit how many words are in the excerpt, with this snippet you can create your own custom excerpt (my_excerpts) replacing the original.

Paste this code in functions.php.

    
<?php add_filter('the_excerpt', 'my_excerpts');
function my_excerpts($content = false) {
            global $post;
            $mycontent = $post->post_excerpt;
 
            $mycontent = $post->post_content;
            $mycontent = strip_shortcodes($mycontent);
            $mycontent = str_replace(']]>', ']]&gt;', $mycontent);
            $mycontent = strip_tags($mycontent);
            $excerpt_length = 55;
            $words = explode(' ', $mycontent, $excerpt_length + 1);
            if(count($words) > $excerpt_length) :
                array_pop($words);
                array_push($words, '...');
                $mycontent = implode(' ', $words);
            endif;
            $mycontent = '<p>' . $mycontent . '</p>';
// Make sure to return the content
    return $mycontent;
}
?>

Secondly, paste this code within the Loop:

<?php echo my_excerpts(); ?>

Redirect WordPress Post Titles To External Links

This snippet could be useful for anyone with a news submission site, by redirecting your post title to an external URL when clicked via a custom field.

Paste this snippet into your functions.php file:

//Custom Redirection
function print_post_title() {
global $post;
$thePostID = $post->ID;
$post_id = get_post($thePostID);
$title = $post_id->post_title;
$perm  = get_permalink($post_id);
$post_keys = array(); $post_val  = array();
$post_keys = get_post_custom_keys($thePostID);
if (!empty($post_keys)) {
foreach ($post_keys as $pkey) {
if ($pkey=='url') {
$post_val = get_post_custom_values($pkey);
}
}
if (empty($post_val)) {
$link = $perm;
} else {
$link = $post_val[0];
}
} else {
$link = $perm;
}
echo '<h2><a href="'.$link.'" rel="bookmark" title="'.$title.'">'.$title.'</a></h2>';
}

Then you add a custom field named ‘url’ and in the value field put the link to which the title is to be redirected to.

Redirect to Single WordPress Post if There is Only One Post in Category/Tag

If there is only one post within a category or tag, this little snippet will jump the reader directly to the post page.

Paste this code into your themes functions.php file:

function stf_redirect_to_post(){
    global $wp_query;
 
    // If there is one post on archive page
    if( is_archive() && $wp_query->post_count == 1 ){
        // Setup post data
        the_post();
        // Get permalink
        $post_url = get_permalink();
        // Redirect to post page
        wp_redirect( $post_url );
    }  
 
} add_action('template_redirect', 'stf_redirect_to_post');

List Scheduled/Future WordPress Posts

Paste the code anywhere on your template where you want your scheduled posts to be listed, changing the max number or displayed posts by changing the value of showposts in the query.

<?php
$my_query = new WP_Query('post_status=future&order=DESC&showposts=5');
if ($my_query->have_posts()) {
    while ($my_query->have_posts()) : $my_query->the_post();
        $do_not_duplicate = $post->ID; ?>
        <li><?php the_title(); ?></li>
    <?php endwhile;
}
?>

Screenshots of External WordPress Pages Without a Plugin

This is a very simple URL script that will generate a screenshot of any website. Here is the URL:

http://s.wordpress.com/mshots/v1/http%3A%2F%2Fspeckyboy.com%2F?w=500

To see what the link above does, click here.

All you have to do is insert your required URL in the place of the ‘speckyboy.com’ part of the link and resize (‘w=500’) as required.

Add Content to the End of Each RSS Post

Adding some extra content that is only viewable by your RSS subscribers couldn’t be easier with this snippet.
Paste this code into the functions.php:

function feedFilter($query) {
    if ($query->is_feed) {
        add_filter('the_content','feedContentFilter');
    }
    return $query;
}
add_filter('pre_get_posts','feedFilter');
 
function feedContentFilter($content) {
    $content .= '<p>Extra RSS content goes here... </p>';
 
    return $content;
}

Reset Your WordPress Password

What would you do if you forget your WordPress Admin Password and you no longer have access to the admin area? To fix this all you have to do is jump to your PhpMyAdmin Sql-window and run the following command.

UPDATE `wp_users` SET `user_pass` = MD5('NEW_PASSWORD') WHERE `wp_users`.`user_login` =`YOUR_USER_NAME` LIMIT 1;

Detect Which Browser Your WordPress Visitors are Using

If you want to use different stylesheets for different browsers, then this is a snippet you could use. It detects the browser your visitors are using and creates a different class for each browser. You can use that class to create custom stylesheets.

add_filter('body_class','browser_body_class');
function browser_body_class($classes) {
global $is_lynx, $is_gecko, $is_IE, $is_opera, $is_NS4, $is_safari, $is_chrome, $is_iphone;
if($is_lynx) $classes[] = 'lynx';
elseif($is_gecko) $classes[] = 'gecko';
elseif($is_opera) $classes[] = 'opera';
elseif($is_NS4) $classes[] = 'ns4';
elseif($is_safari) $classes[] = 'safari';
elseif($is_chrome) $classes[] = 'chrome';
elseif($is_IE) $classes[] = 'ie';
else $classes[] = 'unknown';
if($is_iphone) $classes[] = 'iphone';
return $classes;
}

Display WordPress Search Terms from Google Users

If a visitor reached your site through Google’s search, this script will display the terms they searched for in order to find your site. Just paste it anywhere outside of the header section.

<?php
$refer = $_SERVER["HTTP_REFERER"];
if (strpos($refer, "google")) {
        $refer_string = parse_url($refer, PHP_URL_QUERY);
        parse_str($refer_string, $vars);
        $search_terms = $vars['q'];
        echo 'Welcome Google visitor! You searched for the following terms to get here: ';
        echo $search_terms;
};
?>

Show Different Content for Mac & Windows

If you ever have the need to display different content to either Mac or Windows users (ie. software download link for different platforms), you can paste the following code into your themes functions.php file. You can easily change the content of the function to your own needs.

<?php
if (stristr($_SERVER['HTTP_USER_AGENT'],"mac")) {
echo ‘Hello, I\’m a Mac.’;
} else {
echo ‘And I\’m a PC.’;
}
?>

The post 20 Code Snippets for Extending the Functionality of WordPress appeared first on Speckyboy Design Magazine.

]]>
https://speckyboy.com/wordpress-snippets-extend-wordpress/feed/ 8