Web Development

How to use PHP to connect to SQL Server

php
$myServer = "10.85.80.229";
$myUser = "root";
$myPass = "pass";
$myDB = "testdb";

$dbhandle = mssql_connect($myServer, $myUser, $myPass)
  or die("Couldn't connect to SQL Server on $myServer"); 
?>

 

php  
$serverName = "ServerName"; 
$uid = "sqlusername";   
$pwd = "sqlpassword";  
$databaseName = "DBName"; 

$connectionInfo = array( "UID"=>$uid,                            
                         "PWD"=>$pwd,                            
                         "Database"=>$databaseName); 

/* Connect using SQL Server Authentication. */  
$conn = sqlsrv_connect( $serverName, $connectionInfo);  

$tsql = "SELECT id, FirstName, LastName, Email FROM tblContact";  

/* Execute the query. */  

$stmt = sqlsrv_query( $conn, $tsql);  

if ( $stmt )  
{  
     echo "Statement executed.
\n";  
}   
else   
{  
     echo "Error in statement execution.\n";  
     die( print_r( sqlsrv_errors(), true));  
}  

/* Iterate through the result set printing a row of data upon each iteration.*/  

while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_NUMERIC))  
{  
     echo "Col1: ".$row[0]."\n";  
     echo "Col2: ".$row[1]."\n";  
     echo "Col3: ".$row[2]."
\n";  
     echo "-----------------
\n";  
}  

/* Free statement and connection resources. */  
sqlsrv_free_stmt( $stmt);  
sqlsrv_close( $conn);  
?>  

Hide all WordPress update notifications in dashboard

WordPress has a build-in upgrade system. This system automatically informs you when there is an upgrade available for WordPress, or one of the themes or plugins that are installed on your WordPress installation.

To disable this update notification, there is no switch in the settings menu or anywhere else in the admin dashboard. To prevent WordPress from showing these information snippets on top of your WordPress dashboard, you shall need to add a PHP code snippet to your functions.php file.

So head over to your theme’s folder (/wp-content/themes/your-theme) and open the functions.php file.

Now past the following code at the bottom of that file:

Disable WordPress update notification
1
2
3
4
5
6
7
// hide update notifications
function remove_core_updates(){
global $wp_version;return(object) array('last_checked'=> time(),'version_checked'=> $wp_version,);
}
add_filter('pre_site_transient_update_core','remove_core_updates'); //hide updates for WordPress itself
add_filter('pre_site_transient_update_plugins','remove_core_updates'); //hide updates for all plugins
add_filter('pre_site_transient_update_themes','remove_core_updates'); //hide updates for all themes

Remove any of the last three lines if you only want to hide core updates, themes updates or plugin updates.

Save your file and the update notification in your WordPress admin area should be gone. If you work with clients, this may be an elegant solution for you to keep the interface of your client’s dashboard as simple as possible.

101 WordPress Tips, Tricks and Hacks Every Serious Blogger Must Know

We all want to get the most out of every website we run – and WordPress is no exception. When we first started this site, there were many things we couldn’t figure out and we had to go it alone.The authors of this website want to make sure you jumpstart your learning process and get the most out of WordPress right now! With WordPress being the CMS of choice for 30% of ALL websites on the internet, 40% of the top 10K sites, and with it being the CMS of choice for 50% of websites which use a CMS, we’re sure we speak for many people when we say these WordPress tips will help you push WordPress blog to its full potential!The great thing about WordPress is that its popularity has led to a large number of tips and tutorials available which can show you how to do lots of stuff, small WordPress tricks which push your website to its maximum potential.

WordPress has matured significantly over the years, from a humble blog to a CMS that is so flexible that it allows you to create any kind of website today. From a personal blog to an e-commerce site to a niche social network, you can count on WordPress and all kinds of WordPress themes to allow you to create a great website. Themes of note including the best-selling items, Divi and Avada which we’ve looked at and reviewed fully in separate posts here and here. We’ve got a full listing of themes and roundups we’ve looked and reviewed in detail in a specific section for this purpose here.

And with the growth comes the need for WordPress tricks or “hacks” – small changes in the WordPress code to optimize the performance and display of WordPress.

However, most users are not developers and do not have much experience with code. Thus, many people are not able to use WordPress tricks to tweak and optimize their sites to add more functionality.

In this article we’ll show you how to do some cool WordPress tips without hiring a developer – these are a few simple WordPress tricks (or small tweaks/changes in WordPress code) which allow you to get more, much more from your WordPress website installation.

Why do we call these tricks or hacks? Wikipedia defines a programming hack as “an inelegant but effective solution to a computing problem”. So since we are changing the WP files – we are calling these changes hacks – essentially it’s just WordPress tips and tricks which you should use to make your overall WP experience healthier without having to go through a huge amount of tutorials.

Note: This article assumes you know that some basic HTML/CSS coding. If you’re not ready to do any of these changes yourself, why don’t you have a try and hire a WordPress developer from the top 3% of talent from Toptal? This way you’ll all of the benefits without any of the hassle of coding involved.

You’ll find that many of these tips involve changes to one of the template files, such as functions.php, single.php, headers or another file. Make sure you back up the files before making any tweaks on any of these files because errors might break your site and you will need to revert to a working version of the file.

Contents[Show]

Add new features to your WP site using the following tricks tips and tweaks. If you’d like to get more of these, we have a whole list here.

Not every website support footer widgets. So this tweak will help you add multiple footer widgets into your WordPress theme. Read the tutorial here.

2. Customize log in page

Adding a few tweaks on your functions file will let you customize your login page. Here’s what you need to do.
a) In your current theme directory (../wp-content/themes/your-theme-name), add a folder called “login”. Create a CSS file inside the login folder and name it custom-login-styles.css
b) Next, add the following code into your functions.php file

function my_custom_login() {
echo ”;
}
add_action(‘login_head’, ‘my_custom_login’);

Simply customize your CSS file, custom-login-styles.css. This will reflect on the login page.

Wordpress hack custom login page

To change the logo which appears you can use the following, remember to tweak the values of the logo image to the ones on your own site. The size of the logo should be 80px by 80px

function my_login_logo() { ?>
    


 

It is possible to custom design a page with simple HTML/CSS and installs it on your site. All that needed is to simply add the following code into the top of your custom HTML page.

php /* Template Name: Squeeze */ ?>

After adding the code, save the page as squeeze.php and upload it to your current theme folder (../wp-content/themes/your-theme-name)

Once the file is uploaded, create a new page and choose the template Squeeze under ‘Page Attributes’. Publish the page to see it live.

4. Add infinite scroll WordPress trick

Automatically load new content when the reader scrolls down and approaches the bottom of the page. Infinite scroll is a Jetpack plugin feature. If you’re using a well-coded theme like the default WordPress theme, your theme will support infinite scroll.

Install the Jetpack plugin, enable infinite scroll feature and add the following code to your functions file.

add_theme_support( ‘infinite-scroll’, array(
‘container’ => ‘content’,
‘footer’ => ‘page’,
) );

5. Disable post revisions

‘Post revisions’ is one of the best features of WordPress. However, some users might not need this feature especially for those who have limited database space. This tip will enable you to save on space-related to storing of revisions

To disable the feature, add the following code to wp-config.php file

define(‘AUTOSAVE_INTERVAL’, 120 ); // seconds
define(‘WP_POST_REVISIONS’, false );

This code will disable all the future revisions, and it extends the autosave interval from 60 to 120 seconds. It means your post will be autosaving every 120 seconds. If you want to learn more about WordPress autosave, check out our full article here: https://www.collectiveray.com/wordpress-autosave

6. Add a customized CSS file

Add a customized CSS file with the name ‘custom.css’ to your theme by adding the following code to your functions file.

function custom_style_sheet() {
wp_enqueue_style( ‘custom-styling’, get_stylesheet_directory_uri() . ‘/custom.css’ );
}
add_action(‘wp_enqueue_scripts’, ‘custom_style_sheet’);

Make sure the new CSS file is located in the same directory as that of the main CSS file.

7. Install a child theme

To create a child theme add the below code to the CSS file of your child theme.

/*
Theme Name: Child Theme Name
Template: parenttheme
*/
@import url(“../parenttheme/style.css”);

Make sure you change to the actual name of the parent theme and call the parent theme’s CSS file within your child theme’s CSS file. Use normal quotes instead of curly quotes. We also have a detailed tutorial on how to add a child theme and widget area here.

8. Use normal quotes instead of curly quotes

If you have ever shared a code snippet on WordPress, you might have noted that by default, WordPress turns normal quotes to smart codes, which could break the code snippet you’re about to publish.

To disable this feature, insert the following code snippet to your functions.php file – another of those WordPress tips which seems small but is quite essential

remove_filter(‘the_content’, ‘wptexturize’);

9. Display random image header

If you are a person who would love to display random image headers on your blog, this trick is for you.

Name your image 1.jpg, 2.jpg, 3.jpg, and so on. Upload those images to images folder inside your theme directory. Then, paste the following code to the header file.

Optimize Images 300% in WordPress with These 17 Free Tools and Plugins.

10. Delete existing post revisions

If you want not only to disable the post revision but also to delete all the existing revisions saved in your database, simply run the following SQL query from your PHPMyAdmin.

DELETE FROM wp_posts WHERE post_type = ‘revision’;

Wordpress hack featured content

If you would like to add a featured box inside your post that stands out from the rest of the content, add the following code to the theme’s functions file.

function make_yellowbox($atts, $content = null) {
return ‘

‘ . do_shortcode($content) . ‘

‘;
}
add_shortcode(‘yellowbox’, ‘make_yellowbox’);

Once the code is added, any text wrapped inside the shortcode will appear in a featured yellow colored box.
[yellowbox]Your featured content here[/yellowbox]

Insert the below code to single file to show related posts without havint to install a plugin. This function uses tags to search for related posts and selects the first five (5) and displays their title.

        

      

      

No related posts found!

    

13. Erase thousands of unfiltered spam comments in seconds

Often, spam comments survive the spam filters and reach your ‘awaiting moderation’ list. Deleting it manually could be time-consuming. Follow the procedure to instantly delete thousands of such spam comments.
Log in to phpMyAdmin, select your website’s database, click SQL and paste the code given below in the SQL command window.

DELETE from wp_comments WHERE comment_approved = ‘0’;

And now your site is.

Wordpress hack delete spam

This is one of those WordPress tips which can really save you a ton of time!

There are plenty of other tricks you can use to make your installation leaner, cleaner and hence faster. For example, a couple of simple tricks you should enable:

Read More: 3 Ways to Enable WordPress GZip Compression (faster website)

Read More: [How to] Leverage Browser Caching in WordPress with or without a plugin [5 ways]

14. Separate both comments and trackbacks

comments trackbacks

By default, WordPress combines both comments and trackbacks. Separating both can make things look more organized.

Step 1: Find the below code in the comments.php file.

Paste the below code after it.

Step 2: Then, look for the below code

Paste the below code before it

Step 3: Then, look for the following code

Paste the below code before it

 

Trackbacks

 

 

 

 

 

 

 

 

15. Increase PHP memory

If you were activating a huge plugin and found an error that says memory exhausted just add the following line of code to your wp-config.php file.

define(‘WP_MEMORY_LIMIT’, ’64M’);

The above code will increase the memory limit to 64M, but you can change the value to whatever your hosting server can support. You should check whether the memory has increased to 64M by checking phpinfo() on your WordPress.

If you see that the memory did not change, contact your hosting to check whether you are allowed to reconfigure the memory and ask them to increase it for you.

16. Disable checking for plugin updates

WordPress automatically checks if plugins updates are available.

The below trick comes in handy, in some cases such as if you worry that updating plugins might break your site. Paste the following code to your functions file and disable checking for plugin updates.

WARNING: Disabling plugin updates could lead to your WordPress website being compromised. Enable this again once you’re ready from your testing.

remove_action( ‘load-update-core.php’, ‘wp_update_plugins’ );

add_filter( ‘pre_site_transient_update_plugins’, create_function( ‘$a’, “return null;” ) );

17. Increase/decrease maximum upload size through media uploader

Depending on the host, you’ll see a limit for the file size that you can upload through your Media uploader page in WP.

Add the below code to your .htaccess file to increase the upload limit to 64MB

php_value upload_max_filesize 64M

php_value post_max_size 64M

php_value max_execution_time 300

php_value max_input_time 300

We’re not sure what files you need to upload which are larger than 64M, but if you do, WordPress tips like this can quickly solve your issue.

Conversely, if you need to decrease the size of files which can be uploaded, all you need to do is lower the value to something like 2M or whatever you prefer.

18. Redirect to a maintenance page

Redirect wordpress under maintenance page

Sometimes you may need to redirect the site to a maintenance page. Create a maintenance page and name it as maintenance.html. Upload it to the root directory. Add the below code to .htacess and redirect all traffic to maintenance.html

# Redirect all traffic to maintenance.html file

RewriteEngine on

RewriteCond %{REQUEST_URI} !/maintenance.html$

RewriteCond %{REMOTE_ADDR} !^123\.123\.123\.123

RewriteRule $ /maintenance.html [R=302,L]

Don’t forget to remove this once you are ready. Keep this for as short a time as possible because search engine crawlers such as Google will also be seeing this page instead of your regular content.

19. Custom error pages

Wordpress 404 error

Create error pages for 403, 404 and 500 errors and upload it to your base WordPress installation. Then, add the following code snippet to your .htaccess file to enable the custom error pages.

# Custom error page for error 403, 404 and 500
ErrorDocument 404 /404-error.html
ErrorDocument 403 / 403-error.html
ErrorDocument 500 / 500-error.html

20. Highlight author comments

To highlight the author’s comments, find the following code in your CSS file.

.bypostauthor { background: #eee; }

highlight post author comments wordpress trick

21. Stay logged in for a long(er) period

By default, WordPress keeps you logged in for 2 weeks if you check the “Remember me” option while logging in.

Add the following code snippet to the functions within your theme so you can stay logged in to your site for a year. You can convert any time to seconds and update accordingly if you want to be longer or shorter.

We would suggest going for a month: 2629746 seconds

Of course, with this WordPress tip, you can choose whatever value you want, just find the number of seconds add replace the value.

add_filter( ‘auth_cookie_expiration’, ‘stay_logged_in_for_1_year’ );
function stay_logged_in_for_1_year( $expire ) {
return 31556926; // 1 year in seconds
}

Add the following code to functions file to customize the footer text on the WordPress dashboard.

function remove_footer_admin () {

  echo “Your own text”;

add_filter(‘admin_footer_text’, ‘remove_footer_admin’);

23. Enable shortcodes on widgets

By default, WordPress widgets aren’t enabled to manage shortcodes. Add the following to functions file and empower your widgets to support shortcodes.

define(‘widget_text’, ‘do_shortcode’);

24. Change the length of excerpts

By default, length of the excerpts in WordPress is 55 words. Tweak the functions by adding the following commands to customize the length so it can fit the layout.

function custom_excerpt_length( $length ) {
  return 20;
}
add_filter( ‘excerpt_length’, ‘custom_excerpt_length’, 999 );

25. Display most commented posts

Add the following lines of code to enable another from the plenty of WordPress tips which uses hooks and the functions.php file of your theme

function wpb_most_commented_posts() {

ob_start();?>

Add the following code to your theme’s functions.php to customize the text before the comment form. Replace the text with your own preferred text.

function collectiveray_comment_text_after($arg) {

$arg[‘comment_notes_after’] = “We enjoy your constructive comments but please comment responsibly. Trolling, harassment or otherwise abusive behaviour will not be tolerated and further action will be taken as necessary.”;

return $arg; }

add_filter(‘comment_form_defaults’, ‘collectiveray_comment_text_after’);

27. Identify unused tags

If you delete old posts manually from MySQL, the tags you used on the posts will remain unused. Run the following SQL query to identify such unused tags. This is one of those WordPress tips which needs a bit of attention, because deleting stuff which is necessary can break your site.

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;

28. Redirect mobile users to mobile site

mobile user

This trick comes in handy if you like to keep a mobile version of your site to the responsive version. Add the following commands to the .htaccess file to redirect the mobile users to a mobile version of the site.

RewriteEngine On

# Check for mime types commonly accepted by mobile devices

RewriteCond %{HTTP_ACCEPT} “text\/vnd\.wap\.wml|application\/vnd\.wap\.xhtml\+xml” [NC]

RewriteCond %{REQUEST_URI} ^/$

RewriteRule ^ https://m.domain.com%{REQUEST_URI} [R,L]

29. Remove help and screen options from dashboard

This WordPress tip cleans your admin dashboard from unnecessary clutter. You can see the options “help” and “screen” on the top right hand side of your WP dashboard. Add the following code to functions to remove these options from the dashboard.

add_filter( ‘contextual_help’, ‘wpse_25034_remove_dashboard_help_tab’, 999, 3 );

add_filter( ‘screen_options_show_screen’, ‘wpse_25034_remove_help_tab’ );

function wpse_25034_remove_dashboard_help_tab( $old_help, $screen_id, $screen )

  {

     if( ‘dashboard’ != $screen->base )

     return $old_help;

     $screen->remove_help_tabs();

     return $old_help;

  }

function wpse_25034_remove_help_tab( $visible )

  {

     global $current_screen;

     if( ‘dashboard’ == $current_screen->base )

     return false;

     return $visible;

  }

popular posts

To show the 5 most popular posts according to the comments count, place the below lines in the sidebar.php file. Of course, if you want to show more or less than 5, just change from 5 to another value you prefer in the $result line.

Popular Posts

   

    • 31. Add breadcrumbs to your theme

      To add breadcrumbs, add the following lines to your functions file.

      function the_breadcrumb() {

              echo ‘

        • ‘;

          if (!is_home()) {

              echo ‘

         

      •    

          • “;                the_title();                echo ‘

        ‘;

                    }

                } elseif (is_page()) {

                    echo ‘

           

          • ‘;            echo the_title();            echo ‘

        ‘;

                }

            }

            elseif (is_tag()) {single_tag_title();}

            elseif (is_day()) {echo”

           

          • Archive for “; the_time(‘F jS, Y’); echo’

        ‘;}

            elseif (is_month()) {echo”

           

          • Archive for “; the_time(‘F, Y’); echo’

        ‘;}

            elseif (is_year()) {echo”

           

          • Archive for “; the_time(‘Y’); echo’

        ‘;}

            elseif (is_author()) {echo”

           

          • Author Archive”; echo’

        ‘;}

            elseif (isset($_GET[‘paged’]) && !empty($_GET[‘paged’])) {echo “

           

          • Blog Archives”; echo’

        ‘;}

            elseif (is_search()) {echo”

           

          • Search Results”; echo’

        ‘;}

            echo ‘

        ‘;

        }

        After that, add this line of code to your theme’s template where you would like the breadcrumbs to show up (e.g. single.php, archives.php, etc.).

        < ?php the_breadcrumb(); ?>

        32. Customize your sidebar for individual posts

        Display customized sidebar content for individual posts using custom fields. At first, find the following line of code in your single.php, index.php and page.php file.

        php get_sidebar(); ?>

        Replace it with the following code snippet.

        php $sidebar = get_post_meta($post->ID, “sidebar”, true);
        get_sidebar($sidebar);
        ?>

        When writing a post, create new custom fields named sidebar. In the value section, mention the name of the sidebar you want to display so if you built two different sidebar files (e.g. sidebar-category.php and sidebar-promotion.php) and wanted to show the sidebar-category.php, you’d use the key as “sidebar” and value as “sidebar-category“.

        33. Define how individual posts should be displayed on the homepage

        Most of the themes display all of your posts in the same way on the homepage. That is, on the homepage, either it shows excerpts only or it shows the full post. However, you may not want to display all of your posts in the same way on the homepage.

        Find the loop in your index.php file and replace it with the following so that you can define how each post should be displayed.

        In the above WordPress tips, by default excerpts are displayed on the homepage. To show posts fully on the homepage, create a custom field ‘full’ from the post editor and give it any value.

        34. Link to external links from your post titles

        Usually, titles of blog posts in the homepage are linked to the original post URL.

        However, if the sole purpose of publishing a particular blog post is to share a particular external link, you may not want to entice the users to open up your post. Instead, the users can visit the external link by simply clicking the blog post title from the homepage itself. Add the following code to functions.php file.

        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==’url1′ || $pkey==’title_url’ || $pkey==’url_title’) {

        $post_val = get_post_custom_values($pkey);

        }

        }

        if (empty($post_val)) {

        $link = $perm;

        } else {

        $link = $post_val[0];

        }

        } else {

        $link = $perm;

        }

        echo ‘

        ‘.$title.’

        ‘;

        }

        Then, open your index.php and find the following code

        Replace it with the below code and you’re done!

        ‘Featured images’ is one of the most popular features of WordPress.

        It is supported in most of the themes available today. However, if your theme doesn’t support this feature, you can add support for this feature by tweaking the theme’s functions file

        add_theme_support( ‘post-thumbnails’ );

        36. Custom CSS for individual posts

        You may need to use custom stylesheet for individual posts. Insert the following code in header.php betweenand

        Wrapping Up

        Of course, we've included these 101 WordPress tips tricks and tweaks in this article because we believe these are some of the best optimizations for WordPress which you can implement quickly and easily without having to hire a developer.

        These are small changes in the code which you can quickly achieve yourself without risking breaking your website or your WordPress template 😉

Free Web Hosting