#array_merge()
Explore tagged Tumblr posts
Text
PHP / array_merge_recursive
Esta funcion nos permite unir varios arrays pero con un adicional si contiene arrays internos, espero les sea de utilidad!
Bienvenidos sean a este post, hoy veremos una funcion para los arrays. Esta funcion nos permite combinar varios arrays pero a diferencia de array_merge este tiene una caracteristica adicional, pero primero veamos como es su sintaxis: array_merge_recursive(array_1, array_2,..., array_N) Solamente le pasamos todos los arrays que deseamos unir pero como mencionamos tiene una particularidad ya que…
View On WordPress
0 notes
Text
0 notes
Text
0 notes
Text
Array manipulation in PHP
PHP Certification Course, Array manipulation in PHP involves performing various operations on arrays, such as adding or removing elements, sorting, searching, and restructuring. PHP offers a rich set of array functions to facilitate these tasks. Here are some common array manipulation techniques:
Creating Arrays: Arrays in PHP can be created using square brackets [] or the array() construct. For example:phpCopy code$numbers = [1, 2, 3, 4, 5]; $fruits = array('apple', 'banana', 'cherry');
Adding Elements: To add elements to an array, you can use the assignment operator = or the [] notation. For example:phpCopy code$numbers[] = 6; // Adds 6 to the end of the $numbers array array_push($fruits, 'date'); // Adds 'date' to the end of the $fruits array
Removing Elements: Elements can be removed using functions like unset() or array manipulation functions like array_pop() and array_shift(). For example:phpCopy codeunset($numbers[2]); // Removes the element at index 2 $removedFruit = array_shift($fruits); // Removes and returns the first element
Merging Arrays: Arrays can be combined using functions like array_merge() or the + operator. For example:phpCopy code$combinedArray = array_merge($numbers, $fruits); $mergedArray = $numbers + $fruits; // Note: Keys are preserved
Sorting Arrays: Arrays can be sorted using functions like sort(), rsort(), asort(), ksort(), etc., based on different criteria such as value or key. For example:phpCopy codesort($numbers); // Sorts the array in ascending order ksort($fruits); // Sorts the array by keys
Searching in Arrays: Functions like in_array() and array_search() can be used to search for elements in an array. For example:phpCopy code$found = in_array('banana', $fruits); // Checks if 'banana' is in the $fruits array $index = array_search('cherry', $fruits); // Returns the index of 'cherry' in $fruits
Filtering Arrays: Functions like array_filter() allow you to create a new array with elements that meet specific criteria. For example:phpCopy code$filteredNumbers = array_filter($numbers, function($num) { return $num % 2 == 0; // Filters even numbers });
Iterating Over Arrays: Looping constructs like foreach and for are commonly used to iterate through arrays and perform operations on each element.
These are just a few examples of array manipulation techniques in PHP. Understanding these functions and techniques allows developers to effectively work with and manipulate arrays in their applications.
0 notes
Text
Tutorial PHP: Cara Menggabung Array (Array Merge)
Pada saat pembuatan program yang butuh banyak data, kita biasa menggunakan array untuk menampung data-data tersebut. Dalam situasi tertentu, beberapa array juga perlu digabung menjadi array yang lebih besar. Dalam tutorial PHP kali ini kita akan pelajari bagaimana cara menggabung array di bahasa pemrograman PHP. Terdapat setidaknya 2 cara yang bisa dipakai: Menggunakan function array_merge(),…
View On WordPress
0 notes
Photo

Difference between array_merge() and array_combine() function: https://www.troposal.com/array-merge-and-array-combine-function/ #Troposal #PHP #Function #Array #array_merge() #array_combine() #Difference https://www.instagram.com/p/CAVOLuJne3-/?igshid=9payuy4exmvh
0 notes
Link
Check the most useful PHP functions like:
is_array($arr) in_array($search, $arr, $type) sizeof($arr) array_merge($arr1, $arr2) array_keys($arr) array_values($arr) array_push($arr, $val) array_pop($arr) . . . more
#php#php functions#php array functions#array functions#array#is_array()#in_array()#array_merge()#array_keys()#array_values()#array_push()#array_pop()#ksort()#array_rand()#array_filter()#sort()
0 notes
Text
Insert an array into another associative array at a fixed place in PHP
Insert an array into another associative array at a fixed place in PHP
In an associate array, the order does not matter, because we are calling values by keys, but some times when we want keys to be in a particular order then things get complicated.
The Problem
If you have two arrays with random number of keys:
$array = array( 'minusone' => 'e', 'zero' => 'd', 'one' => 'a', 'two' => 'b', );
and then want to insert these two arrays:
$insert =…
View On WordPress
0 notes
Link
PHP Array functions list with description, check variety of built-in functions for working with PHP arrays. The PHP array functions are part of the PHP core and there is no installation needed to use these functions. Some commonly used array functions in PHP are count(), array_push(), array_pop(), array_slice(), array_merge(), array_reverse() among others. The array functions […]
0 notes
Text
【 PHP 】PHP8に入門してみた 111日目 PHPの基本 ( 組み込み関数 配列の結合 )
【 PHP 】PHP8に入門してみた 111日目 PHPの基本 ( 組み込み関数 配列の結合 )
PHP8技術者認定初級試験 が始まるようなので 試験に向けて (できるだけ)勉強しようと思います! 使用する書籍は独習PHP 第4版(山田 祥寛)|翔泳社の本 (shoeisha.co.jp) となります。 組み込み関数 配列の結合 array_merge関数 配列の結合はarray_mergeを使います・・・。 あれ?+演算子でも同じことできましたよね🤔 +演算子との違いは以下の通りです。 キー重複の場合は後勝ち!なので上書きされてしまう +演算子の場合は「先勝ち!」なので上書きされません。 インデックス番号重複時は上書きされない +演算子の場合は上書きされていました <!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport"…
View On WordPress
0 notes
Text
#programming#website optimization#webdesign#blogger#wordpress#developerdiary#ecommerce#interview#jobs near me
0 notes
Text
PHP / array_merge
Esta funcion nos unira dos o mas arrays, espero les sea de utilidad!
Bienvenidos sean a este post, hoy veremos una funcion para los arrays. Esta funcionn nos permite combinar varios arrays, veamos como es su sintaxis: array_merge(array_1, array_2,..., array_N) Solamente le pasamos todos los arrays que deseamos unir, pasemos a analizar un ejemplo y para ello crearemos un nuevo archivo con el nombre de array.php y le agregaremos el siguiente…
View On WordPress
0 notes
Text
0 notes
Text
[Laravel][Testing] Display clearly array not equals error messages
Problem
When assertEqual asserting was failed, I can’t not known where the path of properies is not match.
Example: Assume I have many configs(contains inputs and expected result) With bellow test, I will receive the bellow message.
private const CONFIGS = [ [ 'params' => [ 'level' => JlptRank::N4, 'parts_score' => [ JlptCategoryConstant::JLPT_VOCABULARY__VALUE => 50, JlptCategoryConstant::JLPT_READING__VALUE => 50, JlptCategoryConstant::JLPT_LISTENING__VALUE => 50, ] ], 'expect_return_value' => JlptRank::RANK_A ], // ... ];
Test code:
/** @test */ public function it_returns_expect_results() { foreach (self::CONFIGS as $config) { $this->assertEquals( $config['expect_return_value'], JlptRank::calculate_Jlpt_rank(...array_values($config['params'])) ); } }
Test result:
Failed asserting that two strings are equal. Expected :'C' Actual :'D'
It is hard to find where is the *config that happen don’t match.*
Solution
Merge inputs and expected results in to array, and comparsion it.
/** @test */ public function it_returns_expect_results() { foreach (self::CONFIGS as $config) { $this->assertEquals( json_encode($config), json_encode(array_merge($config, ['expect_return_value' => JlptRank::calculate_Jlpt_rank(...array_values($config['params']))])) ); } }
Test result will be:
Failed asserting that two strings are equal. Expected :'{"params":{"level":4,"parts_score":{"91":10,"93":60,"94":10}},"expect_return_value":"C"}' Actual :'{"params":{"level":4,"parts_score":{"91":10,"93":60,"94":10}},"expect_return_value":"D"}'
Now you can easily see which properties don’t match.
0 notes
Text
Introduction to the Drupal Unit-testing
You have added features to the site a few days later the customer called and told me that nothing works. You have 20 hours stuffing code and a bunch of times and go on klatsaete forms of testing to get everything working, but the brain perceives nothing and end up on the site added a broken piece. Or maybe you have a complex module with a bunch of interconnected functional, well or small, but with a lot of choices. In general, you have millions of reasons to come to the automated testing.
Use of automated testing can get rid of piles of routine operations on a regular functional testing code. To test the available AutoComplete forms and checking the result, control user access to various sections of the site and functionality, and much more.
What can we offer to test Drupal?
Testing modules and functionality in Drupal module by using SimpleTest. And, with version 7 is included in the kernel, so look the other way and do not make much sense.
Installation
To install you need to set Drupal and that the server was accessible library php-curl, with which the module implements parsing of pages. Once the module is copied to the server, you need to patch the kernel, the patch file is located in the root folder of the module. To use it you must click on the server from the root of the site:
patch-p0 <{path-to-folder-with-modules} / simpletest/D6-core-simpletest.patch Then you can just activate it in the tab with modules and you can view a list of available tests on the page admin / build / testing.
How does the SimpleTest?
In the beginning, it scans the folder modules in search of available tests, if it does not matter whether or not the module is active, the user sees and tests themselves and can not fulfill them including the corresponding module.
This is achieved thanks to the fact that, before starting the test SimpleTest creates a virtual installation of Drupal with a later and running. Already it activates the necessary modules and themes, which may differ from the installation of the current site. Further, in the software testing outsourcing services process tested caused a page or function, after which they validate and generate output information about the success or failure of the operation.
By the way, for each function testXXX setUp runs every time before performing the test.
The first test
Thus, we conclude the flood and move on to practice. In the first test we examine the creation of material such as Page, which is available in all installations. To do this we need:
Create a test file with the name imya_modulya.test and save it in the folder with the module. The file name specified in the tough SimpleTest.
Next, create the test itself:
<?php class OurModuleTest extends DrupalWebTestCase { / / Helper function, which we will generate a text with blanks and Blackjack protected function randomText ($ wordCount = 32) { $ Text =”; for ($ i = 0; $ i <$ wordCount; $ i + +) { $ Text .= $ this-> randomString (rand (4, 12)). ”; } return $ text; } / / Information about the test, which is displayed on the page of tests. public static function getInfo () { return array ( ‘Name’ => ‘Page creation test’, ‘Desc’ => ‘Testing page creation’, ‘Group’ => ‘Our tests’, ); } public function setUp () { / / Set the required modules $ Args = func_get_args (); $ Modules = array_merge (array (’help’, ’search’, ‘menu’, ‘node’), $ args); call_user_func_array (array (’parent’, ’setUp’), $ modules); / / Set the right user permissions $ Permissions = array (’access content’, ‘create page content’, ‘delete own page content’, ‘edit own page content’); / / Create a user with these rights and enter into the system $ User = $ this-> drupalCreateUser ($ permissions); $ This-> drupalLogin ($ user); } / / Testing a page public function testPageCreation () { $ Params = array ( ‘Title’ => $ this-> randomName (32) ‘Body’ => $ this-> randomText (), ); / / Call a Page Page $ This-> drupalPost (’node / add / page’, $ params, t (’Save’)); / / Check if the received input $ This-> assertText (t (’Page @ name has been created.’, Array (’@ name’ => $ params ['title'])), t (’ Page creation ‘)); } } ?>
Clear the cache and go to the page admin / build / testing. Now, there we see the drop-down tab "Our tests", which is available in a single test "Page creation test". By putting a tick on him to fulfill it. after the information is available to us "19 passes, 0 fails, and 0 exceptions". The fact that we wanted.
Now log out the user and then try to perform the test. To do this, create another test and call it testAnonymousPageCreation. From the previous test code will be different only in that we run before running $ this-> drupalLogout ()
/ / Test create page anonymous user public function testAnonymousPageCreation () { / / User Razloginivaem $ This-> drupalLogout (); $ Params = array ( ‘Title’ => $ this-> randomName (32) ‘Body’ => $ this-> randomText (), ); / / Call a Page Page $ This-> drupalPost (’node / add / page’, $ params, t (’Save’)); / / Check if the received input $ This-> assertText (t (’Page @ name has been created.’, Array (’@ name’ => $ params ['title'])), t (’ Page creation ‘)); }
Now the result of 29 passes, 5 fails, and 0 exceptions. However, this is not the result, which was worth getting. In this case, you need to check whether the user’s access is blocked to this page, this will be a successful test, this will modify the test:
/ / Test create page anonymous user public function testAnonymousPageCreation () { / / User Razloginivaem $ This-> drupalLogout (); / / Try to get the desired page $ This-> drupalGet (’node / add / page’); / / Check the server response to error 403 (Access denied) $ This-> assertResponse (403, t (’You have no permitions to this page .’)); }
Now the result: 30 passes, 0 fails, and 0 exceptions. Ok, now we know that unauthorized users can not get access to the creation of pages.
Visit here: Mobile app testing services
What’s next?
Next we have to teach myself to write code right away with the tests. SimpleTest provides enough functionality to solve many problems.
First, it helps to formalize the problem, because for the test to prescribe a clear success criteria.
Second mistake will be detected earlier and a fix will be spent significantly less time because there will be the exact information where and under what conditions the error appeared.
Third excluded mass of routine operations, in which to make a mistake and miss something important. And most importantly, always nice to know that everything he wrote is working as intended.
A small bonus
There is a set of small and major problems and issues related to testing with the help of this module, which you or come across or not, but we warn you:)
SimpleTest can not test JavaScript, therefore the functional jQuery, dynamic content spoofing, etc. test will not work :( The list of available tests (Assertions) is available here: http://drupal.org/node/265828 To form the module must be called View $ this-> drupalGet (), instead of drupalPost (). Example:
$ Params = array (’sorting’ => ’sorting_value’); $ This-> drupalGet (’find / wine-ratings’, array (’query’ => $ params));
Tests are available for inactive modules.
Establishment types, etc. should be brought to a separate module, and write all the necessary procedures in module_name.install.
If you create a separate module for testing, then the file should be added module_name.info hidden = TRUE, then the module can be invoked in the tests, but will not be available in the list.
Nodecomment module conflicts with the module comment, so you should edit the profiles \ default \ default.profile and remove it from the default settings.
And finally an extended version of the class DrupalWebTestCase, which added additional functions and features:
class ExtendedDrupalWebTestCase extends DrupalWebTestCase { protected $ admin_user; protected $ users; / / Helper function, which we will generate a text with blanks and Blackjack protected function randomText ($ wordCount = 32) { $ Text =”; for ($ i = 0; $ i <$ wordCount; $ i + +) { $ Text .= $ this-> randomString (rand (4, 12)). ”; } return $ text; } / / Change the current theme protected function setTheme ($ new_theme) { db_query ("UPDATE {system} SET status = 1 WHERE type = ‘theme’ and name = ‘% s’", $ new_theme); variable_set (’theme_default’, $ new_theme); drupal_rebuild_theme_registry (); } / / Generate file name to display a folder that is outside the temporary folder and SimpleTest can view the data after cleaning. protected function getOutputFile () { $ File_dir = file_directory_path (); $ File_dir .= ‘. / Simpletest_output_pages’; if (! is_dir ($ file_dir)) { mkdir ($ file_dir, 0777, TRUE); } return "$ file_dir / $ basename." . $ This-> randomName (10). ‘. Html’; } / / Write page protected function outputAdminPage ($ description, $ basename, $ url) { $ Output_path = $ this-> getOutputFile (); $ This-> drupalGet ($ url); $ Rv = file_put_contents ($ output_path, $ this-> drupalGetContent ()); $ This-> pass ("$ description: Contents of result page are". L (’here’, $ output_path)); } / / Write the last on-screen display protected function outputScreenContents ($ description, $ basename) { $ Output_path = $ this-> getOutputFile (); $ Rv = file_put_contents ($ output_path, $ this-> drupalGetContent ()); $ This-> pass ("$ description: Contents of result page are". L (’here’, $ output_path)); } / / Write variable to file protected function outputVariable ($ description, $ variable) { $ Output_path = $ this-> getOutputFile (); $ Rv = file_put_contents ($ output_path, ‘<html> <body> <pre>’. Print_r ($ variable, true ).’</ pre> </ body> </ html> ‘); $ This-> pass ("$ description: Contents of result page are". L (’here’, $ output_path)); } }
0 notes
Text
The best code snippets Wordpress for your website

Before publishing this post, we already know how to add PHP functions in Wordpress via using tools. However, I want to share with you some useful functions that either you or any web developers need to know for customising website. Furthermore, these functions can make your website more responsive, more security and more cool. In addition, these function can save your money (without using paid plugin), save much time for coding and test. Therefore, I create a list of 20 cool customised functions that can support you to select the most essential FUNCTIONS that you really need for your website. These functions are compatible with most popular themes and most of Wordpress versions. Besides, I will update more functions in this post for easy reviewing. In addition, the table of content on the right sidebar will support you to navigate easily. Before implementing the process, you need to concentrate on some important steps. READ THIS CAREFULLY BEFORE YOU GO Backup you website Separate each function below for testing before officially activating. You can use plugin snippets or other plugins or separated it in function.php. During testing, if it conflicts, incompatible or make errors on your theme, you can remove it, safely. You just copy and paste PHP code to snippet plugin and activate it. It begins with " " I already tested all codes below, It works like a charm. So if you have question or error code that need for support. You can leave your comment below. I will give you feedback asap. It could be including "How to use" and "CSS" parts. " " shows you how to display the function's result in html markup or insert it directly into posts. Therefore, you do not need to copy it into function.php or code snippet. Besides, " " supports you to decorate Html code block. Code snippets compatibility: Wordpress version > 4.6 PHP ~ 7.xx
Snippets index
Enqueue Google Fonts This function will add more style for your google font function google_fonts() { wp_register_style('OpenSans', 'https://fonts.googleapis.com/css?family=Open+Sans:400,400i,600i,700,700i,800'); wp_enqueue_style( 'OpenSans'); } add_action( 'wp_print_styles', 'google_fonts' ); ?> Make jQuery load from Google Library The function support to load google library in front pages. function replace_jquery() { if (!is_admin()) { wp_deregister_script('jquery'); wp_register_script('jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js', false, '1.11.0'); wp_enqueue_script('jquery'); } } add_action('init', 'replace_jquery'); ?> Customize excerpt length and read more characters Sometimes you need a special length of the excerpt for a specific template. The following function can be used to set this length as desired. The good thing is that the excerpt length is not set globally, but each template can have its own length. function ahlbtech_excerpt_length( $length ) { return 50; } add_filter( 'excerpt_length', 'ahlbtech_excerpt_length', 999 ); //Custom Read More Excerpt function ahlbtech_excerpt_more( $more ) { return '...'; } add_filter('excerpt_more', 'ahlbtech_excerpt_more'); ?> // Deleting the original tag: // Exchange with this tag, and enter any length (in brackets): Enable Pagination Links The function enable pagination links in front page. You want the old »Older posts | Newer posts «Replace links with a cool number list? No problem, since the WordPress version 4.1 you need for the well-known plugin WP-PageNavi no longer. Now that's easy with on-board resources. if ( ! function_exists( 'ahlbtech_pagination' ) ) : function ahlbtech_pagination() { global $wp_query; $big = 999999999; // need an unlikely integer echo paginate_links( array( 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ), 'format' => '?paged=%#%', 'current' => max( 1, get_query_var('paged') ), 'total' => $wp_query->max_num_pages, 'prev_text' => 'Newer Posts', 'next_text' => 'Older Posts' ) ); } endif; ?> /*---For the list to get a design, it still needs some CSS. Here are the styles that I use now and then. You still need to adjust it to your blog colors--*/ nav.pagination{position:relative;display:block;margin-top:20px} .page-numbers{margin:0;padding:0} .page-numbers li{list-style:none;margin:0 6px 0 0;padding:0;display:inline-block} .page-numbers li span.current{padding:10px 15px;background:#9FC65D;border:1px solid #9FC65D;display:block;line-height:1;color:#fff} .page-numbers li a{padding:10px 15px;background:#eee;color:#555;text-decoration:none;border:1px solid #eee;display:block;line-height:1} .page-numbers li a:hover{background:#9FC65D;border-color:#9FC65D;color:#fff} .screen-reader-text { clip: rect(1px,1px,1px,1px); position: absolute!important; height: 1px; width: 1px; overflow: hidden; } Replace WP login logo with custom If you feel so boring with old logo login style, you can replace it with your new logo as you want. Furthermore, if you are really proud of your WordPress website and have invested a lot of work in the design? Then go a step further and adjust the logo on the login page. It looks really good together with a background color of its own. function ahlbtech_login_logo() { ?> #login h1 a, .login h1 a { background-image: url(/images/LOGO.png); background-size: 260px 110px; width: 260px; height: 110px; } add_action( 'login_enqueue_scripts', 'ahlbtech_login_logo' ); ?> Displays a custom Dashboard Widget This function supports to customised widget in dashboard. function ahlbtech_custom_dashboard_widgets() { global $wp_meta_boxes; wp_add_dashboard_widget('custom_help_widget', 'Theme Support', 'ahlbtech_custom_dashboard_help'); } function ahlbtech_custom_dashboard_help() { echo ' Custom dashboard widget via functions.php '; } add_action('wp_dashboard_setup', 'ahlbtech_custom_dashboard_widgets'); ?> Allow different file formats in Media Library As you know WP supports some kinds of type format when uploading and downloading process is executed. Moreover, this function will help your website to increase supportive WP function in upload and download activities. In addition, you want to upload special file formats to your WordPress library and get an error message? Then use this code and your problem is solved. The code allows the upload of the file formats ZIP , MOBI , PDF and EPUB . If you need more formats, you will find here the complete list of MIME types . /** * Add further Mime types for the download of the products */ function add_custom_mime_types($mimes){ $new_file_types = array ( 'zip' => 'application/zip', 'mobi' => 'application/x-mobipocket-ebook', 'pdf' => 'application/pdf', 'epub' => 'application/epub+zip' ); return array_merge($mimes,$new_file_types); } add_filter('upload_mimes','add_custom_mime_types'); ?> Turn Off your self-referring Pingbacks Pingbacks and trackbacks are not bad features, tell them whether your articles have been referenced or linked to other websites. Unfortunately, WordPress has the bad ability to inform you about links to your articles on your own website. So you turn off these annoying news. Ping-backs affect negatively your SEO and also speed of loading your website. If you can disable it, you can enhance your speed loading of your website. function ahlbtech_no_self_ping( &$links ) { $home = get_option( 'home' ); foreach ( $links as $l => $link ) if ( 0 === strpos( $link, $home ) ) unset($links); } add_action( 'pre_ping', 'ahlbtech_no_self_ping' ); ?> Inject Post Images Into the RSS Feed By default, WordPress does not include post pictures in the RSS feed. That's the way you can add post images into RSS Feed. /** * Add Post Images to the RSS Feed */ function ahlbtech_featuredtoRSS($content) { global $post; if ( has_post_thumbnail( $post->ID ) ){ $content = ' ' . get_the_post_thumbnail( $post->ID, 'large', array( 'style' => 'margin-bottom: 15px;' ) ) . ' ' . $content; } return $content; } add_filter('the_excerpt_rss', 'ahlbtech_featuredtoRSS'); add_filter('the_content_feed', 'ahlbtech_featuredtoRSS'); ?> Responsive Videos – YouTube and Vimeo If your theme does not support responsive videos, then you can quickly set support for it yourself. A PHP function ensures an automatic embedding in a Div, the CSS specifications ensure the optimal scaling at every resolution. function ahlbtech_wrap_oembed( $html ){ $html = preg_replace( '/(width|height)="\d*"\s/', "", $html ); // Strip width and height #1 return' '.$html.' '; // Wrap in div element and return #3 and #4 } add_filter( 'embed_oembed_html','ahlbtech_wrap_oembed',10,1); ?> .embed-responsive.embed-responsive-16by9 { position: relative; padding-bottom: 56.25%; /* 16:9 */ padding-top: 25px; height: 0; } .embed-responsive.embed-responsive-16by9 iframe { position: absolute; top: 0; left: 0; width: 100%; height: 100%; } /* This indication makes HTML5 videos responsive */ video { width: 100% !important; height: auto !important; } Custom Sidebars This function supports you to customised sidebars area. function custom_sidebar_widgets_init() { //copy from HERE register_sidebar( array( 'name' => esc_html__( 'Sidebar', 'humescores' ), 'id' => 'sidebar-1', 'description' => esc_html__( 'Add widgets here.', 'humescores' ), 'before_widget' => '', 'after_widget' => '', 'before_title' => '
', 'after_title' => '
', ) ); //to HERE } add_action( 'widgets_init', 'custom_sidebar_widgets_init' ); ?> Modifies tag cloud widget arguments to have all tags in the widget same font size function blog_widget_tag_cloud_args( $args ) { $args = 1; $args = 1; $args = 'em'; return $args; } add_filter( 'widget_tag_cloud_args', 'blog_widget_tag_cloud_args' ); ?> Expanding Your User Profile With Further Social Media Accounts The biographical details in your WordPress profile are quite meager. You do not have many options to link to all your social networks. With this code, you can add any of your social media accounts and quickly view them in the theme. /** * Managing contact fields for author bio */ $ahlbtech_pro_Contactfields = new ahlbtech_pro_Contactfields( // Missing accounts can easily be added array ( 'Feed', 'Twitter', 'Facebook', 'GooglePlus', 'Flickr', 'Xing', 'Github', 'Instagram', 'LinkedIn', 'Pinterest', 'Vimeo', 'Youtube' ) ); class ahlbtech_pro_Contactfields { public $new_fields , $active_fields , $replace ; /** * @param array $fields New fields: array ('Twitter', 'Facebook') * @param bool $replace Replace default fields? */ public function __construct($fields, $replace = TRUE) { foreach ( $fields as $field ) { $this->new_fields = $field; } $this->replace = (bool) $replace; add_filter('user_contactmethods', array( $this, 'add_fields' ) ); } /** * Changing contact fields * @param $original_fields Original WP fields * @return array */ public function add_fields($original_fields) { if ( $this->replace ) { $this->active_fields = $this->new_fields; return $this->new_fields; } $this->active_fields = array_merge($original_fields, $this->new_fields); return $this->active_fields; } /** * Helper function * @return array The currently active fields. */ public function get_active_fields() { return $this->active_fields; } } ?> $twitter = get_the_author_meta( 'twitter', $post->post_author ); $facebook = get_the_author_meta( 'facebook', $post->post_author ); echo 'Twitter | Facebook'; ?> Make Post Images Mandatory add_action('save_post', 'evolution_check_thumbnail'); add_action('admin_notices', 'evolution_thumbnail_error'); function evolution_check_thumbnail($post_id) { // change to any custom post type if(get_post_type($post_id) != 'post') return; if ( !has_post_thumbnail( $post_id ) ) { // set a transient to show the users an admin message set_transient( "has_post_thumbnail", "no" ); // unhook this function so it doesn't loop infinitely remove_action('save_post', 'evolution_check_thumbnail'); // update the post set it to draft wp_update_post(array('ID' => $post_id, 'post_status' => 'draft')); add_action('save_post', 'evolution_check_thumbnail'); } else { delete_transient( "has_post_thumbnail" ); } } function evolution_thumbnail_error() { // check if the transient is set, and display the error message if ( get_transient( "has_post_thumbnail" ) == "no" ) { echo " You have to assign a post image. Without a post image, the article can't be published. "; delete_transient( "has_post_thumbnail" ); } } ?> Change the Look of the First Paragraph /** * Auto-Highlighting - Automatic highlighting of a post's first paragraph * @author Andreas Hecht */ function tb_first_paragraph_highlight( $content ) { return preg_replace( '//', '', $content, 1 ); } add_filter( 'the_content', 'tb_first_paragraph_highlight' ); ?> /*----If you want only change in a single post----*/ .single p.opener { color: #165a72; font-weight: 400; font-size: 21px; line-height: 1.5; } /*-----------If you want only change in a single post & pages----------*/ .single p.opener, .page p.opener { color: #165a72; font-weight: 400; font-size: 21px; line-height: 1.5; } Load the Entire JavaScript in the Footer /** * @uses wp_head() and wp_enqueue_scripts() * */ if ( !function_exists( 'evolution_footer_scripts' ) ) { function evolution_footer_scripts() { remove_action('wp_head', 'wp_print_scripts'); remove_action('wp_head', 'wp_print_head_scripts', 9); remove_action('wp_head', 'wp_enqueue_scripts', 1); } } add_action( 'wp_enqueue_scripts', 'evolution_footer_scripts' ); ?> Create a Breadcrumb Navigation Without a Plugin // Copy from here function ah_the_breadcrumb() { echo ' '; if (!is_home()) { echo ' '; echo 'Home'; echo " "; if (is_category() || is_single()) { echo ' '; the_category(' '); if (is_single()) { 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) && !empty($_GET)) {echo " Blog Archives"; echo' ';} elseif (is_search()) {echo" Search Results"; echo' ';} echo ' '; } ?> Related posts filtered by Category, Use in Single.php if ( ! function_exists( 'evolution_related_posts' ) ) : function evolution_related_posts() { global $post; if($post) { $post_id = get_the_ID(); } else { $post_id = null; } $orig_post = $post; $categories = get_the_category($post->ID); if ($categories) { $category_ids = array(); foreach($categories as $individual_category) $category_ids = $individual_category->term_id; $args=array( 'category__in' => $category_ids, 'post__not_in' => array($post->ID), 'posts_per_page'=> 3, // Number of related posts that will be shown. 'ignore_sticky_posts'=>1 ); $my_query = new wp_query( $args ); if( $my_query->have_posts() ) { echo ' '; echo ' '; _e('Related Posts','evolution'); echo ' '; echo ' '; $c = 0; while( $my_query->have_posts() ) { $my_query->the_post(); $c++; if( $c == 3) { $style = 'third'; $c = 0; } else $style=''; ?> echo ' ' . esc_html( $categories->name ) . ''; } ?> } echo ' '; echo ''; } } $post = $orig_post; wp_reset_postdata(); } endif; ?> /*----------ADD CSS-----------*/ .related-posts { display: flex; } .related-posts .entry-title { font-size: 1rem; } .related-posts .cat { color: #ba9e30; font-size: 0.85rem; } .related-posts .entry-item { width: 31%; margin-right: 3.5%; position: relative; float: left; } .related-posts .entry-item.third { margin-right: 0; } .related-posts a img:hover { opacity: .85; } .entry-related { padding-bottom: 10px; border-bottom: 1px solid #ddd; margin-bottom: 20px } .related-wrap { margin-bottom: 70px; } Hide Plugin from dashboard. Place in functions.php, replace path from edit plugins pathname. function hide_plugin_ahlbtech() { global $wp_list_table; $hidearr = array('really-simple-ssl/rlrsssl-really-simple-ssl.php'); $myplugins = $wp_list_table->items; foreach ($myplugins as $key => $val) { if (in_array($key,$hidearr)) { unset($wp_list_table->items); } } } add_action('pre_current_active_plugins', 'hide_plugin_ahlbtech'); ?> 'really-simple-ssl/rlrsssl-really-simple-ssl.php' is an example of 1 plugin. You can add more plugins that you want to hide when visitors use "view source from browsers like Chrome or FF. The first part before "/" is the plugin folder and after "/" is the core file of your plugin .php. Ex: " array('really-simple-ssl/rlrsssl-really-simple-ssl.php' , "socialshare/socialshare.php" , ....); " Hide Username & Administrator count. Place in functions.php function hide_user_count(){ ?> table.wp-list-table tr#user-9, .subsubsub li.administrator span.count{display: none;} } Remove Inline Styles of WordPress Tag Cloud The WordPress Tag Cloud is the popular widget for our website. Therefore, using this widget, your visitors can find what they are looking for faster. However, WordPress displays tags in different sizes, which is not always a desired property of this widget. Thus, using this snippet, you can remove the inline styles or you can use CSS to hide its style. function drweb_remove_tagcloud_inline_style($input){ return preg_replace('/ style=("|\')(.*?)("|\')/','',$input); } add_filter('wp_generate_tag_cloud', 'drweb_remove_tagcloud_inline_style',10,1); ?> Turn off WordPress emojis The colourful emojis are not for everyone. In contrast, If you do not want to use emojis in your posts, you can disable this feature completely. The performance of your blog will be better. /** * Disable the emoji's */ function disable_emojis() { remove_action( 'wp_head', 'print_emoji_detection_script', 7 ); remove_action( 'admin_print_scripts', 'print_emoji_detection_script' ); remove_action( 'wp_print_styles', 'print_emoji_styles' ); remove_action( 'admin_print_styles', 'print_emoji_styles' ); remove_filter( 'the_content_feed', 'wp_staticize_emoji' ); remove_filter( 'comment_text_rss', 'wp_staticize_emoji' ); remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' ); add_filter( 'tiny_mce_plugins', 'disable_emojis_tinymce' ); add_filter( 'wp_resource_hints', 'disable_emojis_remove_dns_prefetch', 10, 2 ); } add_action( 'init', 'disable_emojis' ); /** * Filter function used to remove the tinymce emoji plugin. * * @param array $plugins * @return array Difference betwen the two arrays */ function disable_emojis_tinymce( $plugins ) { if ( is_array( $plugins ) ) { return array_diff( $plugins, array( 'wpemoji' ) ); } else { return array(); } } /** * Remove emoji CDN hostname from DNS prefetching hints. * * @param array $urls URLs to print for resource hints. * @param string $relation_type The relation type the URLs are printed for. * @return array Difference betwen the two arrays. */ function disable_emojis_remove_dns_prefetch( $urls, $relation_type ) { if ( 'dns-prefetch' == $relation_type ) { /** This filter is documented in wp-includes/formatting.php */ $emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/2/svg/' ); $urls = array_diff( $urls, array( $emoji_svg_url ) ); } return $urls; } ?> Turn off the jQuery Migrate Script jQuery Migrate is a script intended to provide backward compatibility with older jQuery applications. However, the "old" and new jQuery version no longer supports all old applications. Furthermore, this case will certainly not affect more than 5% of all WordPress sites, and yet the not-so-small script will be set default to WordPress. Therefore, this is how you switch it off: /** * jQuery Migrate Script in WordPress. */ if ( ! function_exists( 'evolution_remove_jquery_migrate' ) ) : function evolution_remove_jquery_migrate( &$scripts) { if(!is_admin()) { $scripts->remove( 'jquery'); $scripts->add( 'jquery', false, array( 'jquery-core' ), '1.12.4' ); } } add_filter( 'wp_default_scripts', 'evolution_remove_jquery_migrate' ); endif; ?> Turn off WordPress oEmbed function The WordPress version 4.4 brought the new feature "oEmbed" with it, which is primarily intended to be able to embed external articles or pages using a simple link in posts. So, If you do not need this feature or if you are just uncomfortable with your articles being displayed in external articles at any time, simply disable this feature. /** * Disable embeds on init. * * - Removes the needed query vars. * - Disables oEmbed discovery. * - Completely removes the related JavaScript. * * @since 1.0.0 */ function evolution_disable_embeds_init() { /* @var WP $wp */ global $wp; // Remove the embed query var. $wp->public_query_vars = array_diff( $wp->public_query_vars, array( 'embed', ) ); // Remove the REST API endpoint. remove_action( 'rest_api_init', 'wp_oembed_register_route' ); // Turn off oEmbed auto discovery. add_filter( 'embed_oembed_discover', '__return_false' ); // Don't filter oEmbed results. remove_filter( 'oembed_dataparse', 'wp_filter_oembed_result', 10 ); // Remove oEmbed discovery links. remove_action( 'wp_head', 'wp_oembed_add_discovery_links' ); // Remove oEmbed-specific JavaScript from the front-end and back-end. remove_action( 'wp_head', 'wp_oembed_add_host_js' ); add_filter( 'tiny_mce_plugins', 'evolution_disable_embeds_tiny_mce_plugin' ); // Remove all embeds rewrite rules. add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); // Remove filter of the oEmbed result before any HTTP requests are made. remove_filter( 'pre_oembed_result', 'wp_filter_pre_oembed_result', 10 ); } add_action( 'init', 'evolution_disable_embeds_init', 9999 ); /** * Removes the 'wpembed' TinyMCE plugin. * * @since 1.0.0 * * @param array $plugins List of TinyMCE plugins. * @return array The modified list. */ function evolution_disable_embeds_tiny_mce_plugin( $plugins ) { return array_diff( $plugins, array( 'wpembed' ) ); } /** * Remove all rewrite rules related to embeds. * * @since 1.0.0 * * @param array $rules WordPress rewrite rules. * @return array Rewrite rules without embeds rules. */ function evolution_disable_embeds_rewrites( $rules ) { foreach ( $rules as $rule => $rewrite ) { if ( false !== strpos( $rewrite, 'embed=true' ) ) { unset( $rules ); } } return $rules; } /** * Remove embeds rewrite rules on plugin activation. * * @since 1.0.0 */ function evolution_disable_embeds_remove_rewrite_rules() { add_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); flush_rewrite_rules( false ); } register_activation_hook( __FILE__, 'evolution_disable_embeds_remove_rewrite_rules' ); /** * Flush rewrite rules on plugin deactivation. * * @since 1.0.0 */ function evolution_disable_embeds_flush_rewrite_rules() { remove_filter( 'rewrite_rules_array', 'disable_embeds_rewrites' ); flush_rewrite_rules( false ); } register_deactivation_hook( __FILE__, 'evolution_disable_embeds_flush_rewrite_rules' ); ?> Remove unnecessary entries from the WordPress header WordPress loads a lot of stuff via the wp_head() hook into the header of WordPress themes. Some of them are very useful, others less. Some things just inflate the website unnecessarily. Here comes a little snippet that clears up a lot. The code below will remove the following from being output through the wp_head hook. Really Simple Discovery (RSD) linkWindows Live Writer linkWordPress generator noticePost relational linksFeed LinksShortlinks /** * AHLBTech add more file formats */ function add_custom_mime_types($mimes){ $new_file_types = array ( 'zip' => 'application/zip', 'mobi' => 'application/x-mobipocket-ebook', 'pdf' => 'application/pdf', 'epub' => 'application/epub+zip' ); return array_merge($mimes,$new_file_types); } add_filter('upload_mimes','add_custom_mime_types'); ?> User login only with e-mail and password Since WordPress Version 4.5, a user login is also possible with an e-mail address and the password. In addition, to annoy hackers and make WordPress a bit safer, you can only sign up with this code using email and password. // AHLBTech //WordPress Authentication remove_filter('authenticate', 'wp_authenticate_username_password', 20); // Authentication with E-Mail und Passwort add_filter('authenticate', function($user, $email, $password){ //Check for empty fields if(empty($email) || empty ($password)){ //create new error object and add errors to it. $error = new WP_Error(); if(empty($email)){ //No email $error->add('empty_username', __('ERROR: Email field is empty.')); } else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email $error->add('invalid_username', __('ERROR: Email is invalid.')); } if(empty($password)){ //No password $error->add('empty_password', __('ERROR: Password field is empty.')); } return $error; } //Check if user exists in WordPress database $user = get_user_by('email', $email); //bad email if(!$user){ $error = new WP_Error(); $error->add('invalid', __('ERROR: Either the email or password you entered is invalid.')); return $error; } else{ //check password if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password $error = new WP_Error(); $error->add('invalid', __('ERROR: Either the email or password you entered is invalid.')); return $error; }else{ return $user; //passed } } }, 20, 3); Stop users from changing their passwords The administration section of WordPress is the heart and the lungs of your website. You always ensure that the passwords given are very strong, so that attacks have no chance. Users, however, like to change the passwords given in very easy to remember and thus cracking variants. You can prevent this successfully! /** * * Stop Users changing password * */ class Password_Reset_Removed { function __construct() { add_filter( 'show_password_fields', array( $this, 'disable' ) ); add_filter( 'allow_password_reset', array( $this, 'disable' ) ); } function disable() { if ( is_admin() ) { $userdata = wp_get_current_user(); $user = new WP_User($userdata->ID); if ( !empty( $user->roles ) && is_array( $user->roles ) && $user->roles == 'administrator' ) return true; } return false; } } $pass_reset_removed = new Password_Reset_Removed(); Show ads after the xx paragraph If you want to earn money with your blog, then you can not avoid the use of advertising. You can use the popular Google Adsense for example. This snippet will display your ad units according to the paragraph you specify. /** * Show ads after the xx paragraph * */ add_filter( 'the_content', 'tb_insert_post_ads' ); function tb_insert_post_ads( $content ) { $ad_code = 'Here comes the promotional code. Either static advertising or Google Adsense.'; if ( is_single() && ! is_admin() ) { // The number before content determines where the code appears. Here after the second paragraph of an article. return tb_insert_after_paragraph( $ad_code, 2, $content ); } return $content; } // Parent Function that makes the magic happen function tb_insert_after_paragraph( $insertion, $paragraph_id, $content ) { $closing_p = ''; $paragraphs = explode( $closing_p, $content ); foreach ($paragraphs as $index => $paragraph) { if ( trim( $paragraph ) ) { $paragraphs .= $closing_p; } if ( $paragraph_id == $index + 1 ) { $paragraphs .= $insertion; } } return implode( '', $paragraphs ); } ?> View category list with RSS feeds Sometimes it can be handy to see all categories with the associated RSS feed addresses. It gets even better if you can use a WordPress shortcode to display the list everywhere - even in the text widgets. function tb_categories_with_feed() { $args = array( 'orderby' => 'name', 'feed' => 'RSS', 'echo' => false, 'title_li' => '', ); $string .= ' '; $string .= wp_list_categories($args); $string .= ' '; return $string; } // add shortcode add_shortcode('categories-feed', 'tb_categories_with_feed'); // Add filter to execute shortcodes in text widgets add_filter('widget_text', 'do_shortcode'); //------How to add ShortCode +The shortcode: lets you show the list where you want it. It also works within widgets. +In your theme, you can also use the shortcode:
Conclusion
I hope you have discovered some useful snippets of code for you and your WordPress. These functions have been used for our website. Therefore, I can ensure the codes are work like a charm without errors. If you need question, you can add to comments section below for our support. Read the full article
0 notes