Skip to content

Instantly share code, notes, and snippets.

@mzdebo
Forked from LeanSeverino1022/readme.md
Created April 28, 2021 12:29
Show Gist options
  • Save mzdebo/a2da1f36b973b54447d772449f7e737f to your computer and use it in GitHub Desktop.
Save mzdebo/a2da1f36b973b54447d772449f7e737f to your computer and use it in GitHub Desktop.
[_Just enough wordpress] just enough stuff I need for now #wordpress

Great reference for functions by Category(Posts, Categories, Custom Post Type, Pages, etc.)

note: I have found out that some functions that are available in some sources may not be available in these resources I have listed.

  1. https://codex.wordpress.org/Function_Reference
  2. https://developer.wordpress.org/reference/

CODING STANDARDS link

Custom Queries - understanding this takes you to a new higher level AHA moment.

Good practice to remember wp_reset_postData() to reset different WP data and global variables back to the state what it was in when it made its default automatic query based on the current url right before we came along and made a custom query.

Famous loop

https://developer.wordpress.org/themes/basics/the-loop/

while (have_posts()) {
	the_permalink()
	the_post()
	the_title(); current title of current post
	the_content()
}

get_theme_file_uri

wp_enqueue_script('academy-js', get_theme_file_uri('/js/scripts-bundled.js'), NULL, '1.0', true);

<div class="page-banner__bg-image" style="background-image: url(<?php echo get_theme_file_uri('images/library-hero.jpg')?>);"></div>

loading js/css

function load_files() {
    wp_enqueue_style('custom-google-font', 'https://fonts.googleapis.com/css?family=Roboto+Condensed:300,300i,400,400i,700,700i|Roboto:100,300,400,400i,700,700i');
    wp_enqueue_style('font-awesome', '//maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css');
    wp_enqueue_style('academy_main_styles', get_stylesheet_uri());
}

add_action('wp_enqueue_scripts', 'load_files');

add_theme_support

Must be called in the theme’s functions.php file to work. If attached to a hook, it must be ‘after_setup_theme’. The ‘init’ hook may be too late for some features.

//functions.php - set page title text (the page tab text)
function academy_features() {
   add_theme_support('title-tag');
}

add_action('after_setup_theme', 'academy_features');
get_header()
get_footer()

Posts functions


get_the_ID() //get the id of the current page 

more from codex

wp_get_post_parent_id( get_the_ID() ) // Returns the ID of the current post's parent.
get_the_title(id) //Allows you to pass an ID number in the parenthesis and it will give you the title of that post  
the_title() // will output the title of the current post
get_permalink(id) //You can pass an id number in the parenthesis and it will give us the permalink for that post or page
wp_list_pages() //similar to get_pages() - difference is that wp_list_pages() will handle ouputting the pages onto the screen while get_pages() will just return the pages in memory

// filter pages to show
wp_list_pages(array(
    'title_li' => NULL, //List heading. Passing a null or empty value will result in no heading,
    'child_of' =>  $findChildrenOf  // Display only the sub-pages of a single page by ID. Default 0 (all pages).
));
get_pages() //similar to wp_list_pages() - difference is that wp_list_pages() will handle ouputting the pages onto the screen while get_pages() will just return the pages in memory
is_page('about-us-slug')
is_category() // will return true if you are on a category archive's screen
is_admin()
is_post_type_archive(string|string[] $post_types = '') // Determines whether the query is for an existing post type archive page.
is_author() // will return true if you are on a author archive's screen
the_author() //Display the name of the author of the current post.
single_cat_title() //Useful for category template files for displaying the category page title. 
the_archive_title() // new function which is really good. displays the archive type and title
the_archive_description() //Display category, tag, term, or author description. The desc text can be modified in the admin dashboard
wp_trim_words() //
wp_trim_words(get_the_content(), 18) // example on how to limit the content to first 18 words only
site_url('/blog')
the_author_posts_link() //Displays an HTML link to the author page of the current post’s author.
get_the_category_list(', ') //RRetrieve category list for a post in either HTML list or custom format. this one is separate cat list with comma
the_time //Displays the time of the current post. To return the time of a post, use get_the_time().
get_post_type();
get_post_type() == 'post' // sample usage
WP_Query property $max_num_pages The total number of pages. Is the result of $found_posts / $posts_per_page
// see  https://developer.wordpress.org/reference/classes/wp_query/#properties
get_post_type_archive_link(postType) // sometimes we would change the slug - so what we can do is to use a wp function that will automatically get the url for a post type archive - 
if (has_excerpt()) {
	the_excerpt();
    or
    echo get_the_excerpt();
}

wp_localize_script() is often used to pass generic data from PHP to JavaScript

formatting date and time

Check if the current page has children, if it has, then the function will return a collection of any and all children

$testArray = get_pages(array(
	'child_of' => get_the_ID(); 
))

Display a list of pages ( you can then sort and filter items)

default behavior of wp_list_pages() is to output links to all of the pages on your site

wp_list_pages(array(
    'title_li' => NULL, 
    'child_of' =>  $findChildrenOf,// id
	'sort_column' => 'menu_order' // then make changes as admin. go to pages -? page attributes -> order
));

important code to add in your header.php

<html <?php language_attributes(); ?> >
<head>
    <meta charset="<?php bloginfo('charset'); ?>"
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <?php wp_head(); ?>
</head>
<body <?php body_class(); ?> >

one of favorite wp functions

<?php body_class(); ?> the classes added in the body can be used for css styling

<body <?php body_class(); ?> > //example usage in header.php

CONTROL NAVIGATION FROM WITHIN WORDPRESS ADMIN SCREENS OR DIRECTLY FROM HTML? rule of thumb - if I am making a custom site for a client, I prefer to keep navigation links in the HTML code. For generic themes for many people to use, it's mandatory that your theme is flexible and in that case make nav menus controllable from the wordpress admin...

get the the id of the parent of the current page

wp_get_post_parent_id(0) wordpress will understand the 0 to mean look up the current page. 

note: index.php file is really just supposed be a generic fallback, and not WP's first choice

Custom queries

<?php
 
$args = array(
    // Arguments for your query.
);
 
// Custom query.
$query = new WP_Query( $args );
 
// Check that we have query results.
if ( $query->have_posts() ) {
 
    // Start looping over the query results.
    while ( $query->have_posts() ) {
 
        $query->the_post();
 
        // Contents of the queried post results go here.
 
    }
 
}
 
// Restore original post data.
wp_reset_postdata();
 
?>

How to create / register a custom post type

https://www.cloudways.com/blog/how-to-create-custom-post-types-in-wordpress/

above works but ideal way is to use Must-use plugins. Must-use plugins are a way to add features to the WordPress core by adding files into the wp-content directory. Must use plugins live in their own special dedicated folder and you cannot deactivate them. As long as the php file exists in the must use plugins folder, wordpress will use it.

note: functions.php is not where the best place to put custom post types code because we don't want access to our data to be reliant on a certain theme being activated/ Plugin is not okay too because they can easily be activated/deactivated

see Udemy Unlocking the power of code section 8 - Events Post Types EX:

   function university_post_types() {
    register_post_type( 'event',
    // CPT Options
    array(
        'public' => true,
        'rewrite' => array( 'slug' => 'events'),
        'has_archive' => true,
        'labels' => array(
            'name' => 'Events',
            'add_new_item' => 'Add new Event',
            'edit_item' => 'Edit Event',
            'all_items' => 'All Events',
            'singular_name' => 'Event'
        ),
        'menu_icon' => 'dashicons-calendar'
        )
    );
}

// Hooking up our function to theme setup
add_action( 'init', 'university_post_types' );

Display post types

  • search gist 'Display post types'

Custom Fields

  • just use the plugin Advanced Custom Fields (ACF)
  • another good one is CMB2 (Custom Metaboxes 2)
  • Good developers normally would not use plugins as much as possible but these plugins are just this good.

ACF - Displaying field values is ACF’s party piece! Any field value can be returned as a PHP variable or output as HTML via the magical functions get_field() and the_field(). These functions (alongside many others) provide a developer friendly way to customize your WordPress theme without spending hours reading our docs! link

PHP DateTime Class - use this if you are working with date and time

WP_Query Arguments

Customizing the WordPress Query – using pre_get_posts for the main query

Custom WordPress Queries – For generating custom queries

Pagination in a custom query -

The solution is to make your custom query override the global $wp_query variable, which tricks the WordPress functions into thinking it is the main query.

Another way I learned from Unlocking Power With Code...

This seems interesting but I haven't checked it deeply. I might be able to create a helper function from this source - https://prokashit.com/use-wp_query-to-create-pagination-in-wordpress/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment