Internal linking in Wordpress - wordpress

If I have lots of pages... page_ids 1-100... how do I link between the two in the editor?? I guess I can use Link but that's not user friendly... I want to do something like Link but that doesn't work either. Is there a handy plugin?

Use a shortcode.
Add the following to your themes’ functions.php:
if ( ! function_exists('toscho_id_to_link') )
{
/**
* Creates a link from the post id.
*
* Usage: [link id=42 title="The Meaning of Life?" class="pseudophilosphical"]Guess![/link]
*
* Inspired by Sergej Müller
* #see http://playground.ebiene.de/2388/wordpress-shortcode-links/
* #param array $atts id (numeric) and additional HTML attributes
* #param string $data
* #return string
*/
function toscho_id_to_link($atts, $data)
{
// incomplete
if ( ! isset ( $atts['id'] ) or ! is_numeric($atts['id']) )
{
return $data;
}
// test
$url = get_permalink($atts['id']);
// No entry with this ID.
if ( ! $url )
{
return $data;
}
unset ( $atts['id'] );
$attributes = '';
// more attributes?
if ( ! empty ($atts) )
{
foreach ($atts as $key => $value )
{
$attributes .= " $key='$value'";
}
}
return "<a href='$url'$attributes>$data</a>";
}
add_shortcode('link', 'toscho_id_to_link');
}
You may find this plugin helpful: Simply show IDs.

We use RB-Internal-Links. It allows you to link using a shortcode and slug, or even has a WYSIWYG interface.

There are plugins that you can use to insert PHP in your posts or pages. Maybe using one of those will let you use your second suggestion.

You should really use complete and full URLs for all links in WordPress. http://example.com/index.php?page_id=123 , for example.
Using partial links will result in strange behaviors in feeds, on category archives, etc.

Related

How to add a custom class to an element in a WordPress post using WP hooks via Snippets?

I'm trying to add a single class (my-class) to an element in a WordPress post (LearnDash Theme). I fount out that it can be done using a hook via add_filter, but no how I could figure it out.
The sample code that I found looks like this:
add_filter( 'body_class', 'custom_body_class' );
/**
* Add custom field body class(es) to the body classes.
*
* It accepts values from a per-page custom field, and only outputs when viewing a singular static Page.
*
* #param array $classes Existing body classes.
* #return array Amended body classes.
*/
function custom_body_class( array $classes ) {
$new_class = is_page() ? get_post_meta( get_the_ID(), 'body_class', true ) : null;
if ( $new_class ) {
$classes[] = $new_class;
}
return $classes;
}
In this sample code the class is added to pages only but I need to add it to "posts". I tried is_post() but it didn't work out. I even tried it on a page, but didn't work also.
In my case I want to add a class to an element with ID learndash-page-content.
Existing code:
<div id="learndash-page-content">...</div>
What I'm struggling to do:
<div id="learndash-page-content" class="my-class">...</div>
What do I need to do to get it working?
If that is indeed the syntax of the element, you might want to try string manipulation on the output (which you will capture like this:)
function start_modify_html() {
ob_start();
}
function end_modify_html() {
$html = ob_get_clean();
$html = str_replace( '<div id="learndash-page-content">', '<div id="learndash-page-content" class="my-class">', $html );
echo $html;
}
add_action( 'wp_head', 'start_modify_html' );
add_action( 'wp_footer', 'end_modify_html' );

Stop logo appearing on wordpress

I'm using the wpjobmanager plugin.
There's a field called 'company logo' that displays a default logo on every job. I'm trying to disable it and only show a logo when a user has specifically uploaded one.
I created this IF statement, but for some reason, the default logo is not considered empty so it continues to display it. I've tried null too and get the same result.
$is_logo = get_post($post->ID, '_company_logo', true);
if (!empty($is_logo)) {
the_company_logo();
}
Could someone point me in the right direction here? I'm at a loss.
Thanks
Here is the code for get_the_company_logo which returns empty string if not set.
/**
* Gets the company logo.
*
* #since 1.0.0
* #param int|WP_Post $post (default: null).
* #param string $size
* #return string Image SRC.
*/
function get_the_company_logo( $post = null, $size = 'thumbnail' ) {
$post = get_post( $post );
if ( has_post_thumbnail( $post->ID ) ) {
$src = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), $size );
return $src ? $src[0] : '';
} elseif ( ! empty( $post->_company_logo ) ) {
// Before 1.24.0, logo URLs were stored in post meta.
return apply_filters( 'the_company_logo', $post->_company_logo, $post );
}
return '';
}
So if you did
if (!empty(get_the_company_logo($post->ID)){
the_company_logo();
}
This would seem like it should work. I am not using this plugin, so I can't really test this.
Try this the_company_logo() function:
if(!empty(the_company_logo())) {
get_the_company_logo()
}
I read this function here -> https://wpjobmanager.com/document/template-tags/.
Say me if you need some help.

Wordpress - Custom Archive Page without pre-posts?

Is it possible to disable preloaded posts on a Archive-Page like archive-computers.php?
Example (archive-computers.php):
<?php
/**
* The archive template file
*
* #link http://codex.wordpress.org/Template_Hierarchy
* #package WordPress
* #subpackage mydomain.de
*/
var_dump($posts);
?>
Yes, here i have already posts in $posts. In my case the default posts_per_page => 10.
The problem is i dont need this because iam using here custom-queries on this page. So, how i can disable/prevent this "unused" query. Its waste performance.
Thats solves my issue!
function _cancel_query( $query ) {
if ( !is_admin() && is_post_type_archive( 'computer' ) ) {
$query = false;
}
return $query;
}
add_action( 'posts_request', '_cancel_query' );

add_filter('wp_title') doesn't replace my title tag (WordPress plugin)

I am trying to change the title of my detail page to the name of the car.
I have made a plugin that fills the detail page with the car information. But now I can't get the add_filter('wp_title') to work in my plugin.
Here is the code I tried:
function init() {
hooks();
}
add_action('wp', 'init');
function hooks() {
if(get_query_var('car_id') != "") {
add_filter('wp_title', 'addTitle', 100);
add_action('wp_head', 'fillHead');
}
add_shortcode('showCar', 'showCar');
}
function addTitle() {
$api_url_klant = API_URL . '/gettitle/' . get_option("ac") . '/' . get_query_var('car_id');
$title = getJSON($api_url_klant);
return $title['merk'] . " " . $title['model'] . " - " . $title['bedrijf'];
}
The addTitle() function works just fine. It returns the right name. Also the add_action('wp_head') works as well. I only can't get the wp_title filter not to work.
Am I executing this filter at the wrong moment or what am I doing wrong?
If anyone else is having problems with this, it may be due to the Yoast plugin. Use:
add_filter( 'pre_get_document_title', function( $title ){
// Make any changes here
return $title;
}, 999, 1 );
I can't tell from the code you have provided, but are you using:
<title><?php wp_title(); ?></title>
in your <head>, under header.php?
UPDATE
Apparently a change was made to the way titles are handled as of 4.4. Here is a link that explains how to use the new code:
https://www.developersq.com/change-page-post-title-wordpress-4-4/
/*
* Override default post/page title - example
* #param array $title {
* The document title parts.
*
* #type string $title Title of the viewed page.
* #type string $page Optional. Page number if paginated.
* #type string $tagline Optional. Site description when on home page.
* #type string $site Optional. Site title when not on home page.
* }
* #since WordPress 4.4
* #website: www.developersq.com
* #author: Aakash Dodiya
*/
add_filter('document_title_parts', 'dq_override_post_title', 10);
function dq_override_post_title($title){
// change title for singular blog post
if( is_singular( 'post' ) ){
// change title parts here
$title['title'] = 'EXAMPLE';
$title['page'] = '2'; // optional
$title['tagline'] = 'Home Of Genesis Themes'; // optional
$title['site'] = 'DevelopersQ'; //optional
}
return $title;
}
I posted this answer to another question but since it is relevant and more up-to-date, I though it might be useful.
How document title is generated has changed since Wordpress v4.4.0. Now wp_get_document_title dictates how title is generated:
/**
* Displays title tag with content.
*
* #ignore
* #since 4.1.0
* #since 4.4.0 Improved title output replaced `wp_title()`.
* #access private
*/
function _wp_render_title_tag() {
if ( ! current_theme_supports( 'title-tag' ) ) {
return;
}
echo '<title>' . wp_get_document_title() . '</title>' . "\n";
}
Here is the code from v5.4.2. Here are the filters you can use to manipulate title tag:
function wp_get_document_title() {
/**
* Filters the document title before it is generated.
*
* Passing a non-empty value will short-circuit wp_get_document_title(),
* returning that value instead.
*
* #since 4.4.0
*
* #param string $title The document title. Default empty string.
*/
$title = apply_filters( 'pre_get_document_title', '' );
if ( ! empty( $title ) ) {
return $title;
}
// --- snipped ---
/**
* Filters the separator for the document title.
*
* #since 4.4.0
*
* #param string $sep Document title separator. Default '-'.
*/
$sep = apply_filters( 'document_title_separator', '-' );
/**
* Filters the parts of the document title.
*
* #since 4.4.0
*
* #param array $title {
* The document title parts.
*
* #type string $title Title of the viewed page.
* #type string $page Optional. Page number if paginated.
* #type string $tagline Optional. Site description when on home page.
* #type string $site Optional. Site title when not on home page.
* }
*/
$title = apply_filters( 'document_title_parts', $title );
// --- snipped ---
return $title;
}
So here are two ways you can do it.
First one uses pre_get_document_title filter which short-circuits the title generation and hence more performant if you are not going make changes on current title:
function custom_document_title( $title ) {
return 'Here is the new title';
}
add_filter( 'pre_get_document_title', 'custom_document_title', 10 );
Second way uses document_title_separator and document_title_parts hooks for the title and the title seperator that are executed later in the function, after title is generated using functions like single_term_title or post_type_archive_title depending on the page and about to be outputted:
// Custom function should return a string
function custom_seperator( $sep ) {
return '>';
}
add_filter( 'document_title_separator', 'custom_seperator', 10 );
// Custom function should return an array
function custom_html_title( $title ) {
return array(
'title' => 'Custom Title',
'site' => 'Custom Site'
);
}
add_filter( 'document_title_parts', 'custom_html_title', 10 );
I have trawled through each and every solution on the web trying 100s of examples.
In the end... Well Done joemaller As putting this first solved everything!
add_filter('wpseo_title', '__return_empty_string');
The simple answer is using this variable.
document_title_parts();
For example:
add_filter( 'document_title_parts', function( $title ){
// Customize here
return clean( $title );
}, 10 );
Output before:
#Page Title
After Output:
Page Title
Thanks.

How to create multiple content blocks in wordpress?

thanks in advance for explaining the idea of creating multiple content blocks in Wordpress post editor in the admin panel. I tried searching for similar thread before asking and couldn't find any answer.
What I need is to create an additional content field along with the default one. What functions do I need to implement please? I found a plugin "Multiple Content Blocks" in wordpress plugin library but I believe this simple task will require fewer codes. I hope I have explained well what I need. Thanks again!
Oldish question, but since it was the first hit on my google search I'll add my method - there are a few major issues with the accepted answer, primarily:
using a meta box, when the documentation clearly states that it is not safe for wp_editor().
using sanitize_text_field() to sanitize html (which removes all html!)
This file can be dropped into your theme folder or at the bottom of your functions.php, and all posts and pages will get an additional editor.
If using a separate file just remember to include it from your functions.php:
include __DIR__ . '/my_extra_content.php';
Obviously you should do a search for "my_" and replace with something meaningful - "extra_content" may also be a tad too generic, so come up with something more exotic.
<?php
//Use a class to avoid conflicts
class my_extra_content {
/**
* Called on instantiation, this is where we hook functions
*/
function __construct() {
/* Using add_meta_box seems like the correct way to do this, but since
* we're inserting a TinyMCE editor we cannot (should not) - from codex:
* ---
* Once instantiated, the WYSIWYG editor cannot be moved around in the
* DOM. What this means in practical terms, is that you cannot put it in
* meta-boxes that can be dragged and placed elsewhere on the page.
* Instead use 'edit_page_form' (for pages) or 'edit_form_advanced'
* (for other post types).
*/
add_action( 'edit_page_form', array($this, 'my_extra_content_custom_box') );
add_action( 'edit_form_advanced', array($this, 'my_extra_content_custom_box') );
/* This one saves the content */
add_action( 'save_post', array($this, 'save_postdata' ));
}
/**
* This actually outputs the tinyMCE box
*/
function my_extra_content_custom_box( $post ) {
/* Always use a nonce */
wp_nonce_field( 'my_extra_content_custom_box', 'my_extra_content_custom_box_nonce' );
/* Get the content */
$content = self::get_content($post);
/* Insert the editor */
wp_editor( $content, "my_extra_content");
}
/**
* Saves the content
*/
function save_postdata( $post_id ) {
/* Check that nonce was sent */
if ( ! isset( $_POST['my_extra_content_custom_box_nonce'] ) ) {
return $post_id;
}
/* Check that nonce is valid */
if ( ! wp_verify_nonce( $_POST['my_extra_content_custom_box_nonce'], 'my_extra_content_custom_box' ) ) {
return $post_id;
}
/* Don't try to do anything on autosave (custom fields aren't included) */
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) {
return $post_id;
}
/* Check permissions */
if ( 'page' === get_post_type( $post_id ) ) {
if ( ! current_user_can( 'edit_page', $post_id ) ) {
return $post_id;
}
} else {
if ( ! current_user_can( 'edit_post', $post_id ) ) {
return $post_id;
}
}
/* Sanitize content - we don't use sanitize_text_field() as it strips all
* HTML, which is clearly not wanted with a wysiwyg - wp_kses_post()
* should do what we want */
$sane_content = wp_kses_post( $_POST['my_extra_content'] );
/* Save content - notice the underscore in the meta name - it hides the
* field from the "normal" custom field editor */
update_post_meta( $post_id, '_my_extra_content_content', $sane_content );
}
/**
* Static function makes it easy to get the value wherever you need it.
* - for example:
* $my_extra_content = my_extra_content::get_content()
*/
static function get_content($post_or_post_id = null) {
/* First find the post id */
$post_id = false;
if ($post_or_post_id === null) {
/* If nothing was passed, try to get it from global post object */
global $post;
$post_or_post_id = $post->ID;
}
if (is_a($post_or_post_id, 'WP_Post')) {
/* If a post object was passed, or we're using the global $post */
$post_id = $post_or_post_id->ID;
} elseif (is_numeric($post_or_post_id)) {
/* If a number (hopefully a post id) was passed */
$post_id = intval($post_or_post_id);
}
/* Try to get the value */
$value = get_post_meta($post_id, '_my_extra_content_content', true );
/* If we didn't get a valid string return an empty one */
if (!is_string($value)) {
return '';
}
return $value;
}
/**
* Static function to very easily output the content in a template
* - for example:
* my_extra_content::echo_content()
*/
static function echo_content( $post_or_post_id = null ) {
$output = self::get_content($post_or_post_id);
/* do_shortcode makes sure we support shortcodes (if that is wanted) */
// $output = do_shortcode($output);
/* the_content filter will apply all normal filters (including
* do_shortcode) to the content (not required!) */
$output = apply_filters( 'the_content', $output);
/* print it */
echo $output;
}
}
/* Instantiate the class - because of the static functions used to fetch the
* content we won't need to ever use this variable, we just need __construct()
* to be called, so our hooks are added */
$extra_content_throwaway_var = new my_extra_content();
First of all adding content editors to Wordpress edit pages is a lot harder than it sounds, so if you are not familiar with the save/update cycle and metaboxes then I would recommend using a plugin. I like "Advanced Custom Fields" but I'm sure "Multiple Content Blocks" is good too.
In any case I have outlined a general Custom Meta Box solution here. So here we go:
The wp_editor() function is what we use to create an editor instance. http://codex.wordpress.org/Function_Reference/wp_editor
However, I would call this within a meta box.
http://codex.wordpress.org/add_meta_box
Here is some sample code that creates a meta box with a content editor in it.
This plugin stores the value of the content editor in a custom field called _hurtigtech_extra_content that gets saved when the post/page is updated update.
You can drop this plugin into the plugins folder /wp-content/plugins/ and play with it there. Feel free to leave comments if you need help with this, I know it is a lot of code so again the plugins might be best, but this is also a good baseline if you feel confident.
<?php
/**
* Plugin Name: Extra Metabox Content Editor
*/
/**
* Adds a box to the main column on the Post and Page edit screens.
*/
function hurtigtech_add_custom_box() {
$screens = array( 'post', 'page' );
foreach ( $screens as $screen ) {
add_meta_box(
'hrutigtech_extra_content_section',
__( 'My Post Extra Content', 'hurtigtech_translations' ),
'hurtigtech_inner_custom_box',
$screen
);
}
}
add_action( 'add_meta_boxes', 'hurtigtech_add_custom_box' );
/**
* Prints the box content.
*
* #param WP_Post $post The object for the current post/page.
*/
function hurtigtech_inner_custom_box( $post ) {
// Add an nonce field so we can check for it later.
wp_nonce_field( 'hurtigtech_inner_custom_box', 'hurtigtech_inner_custom_box_nonce' );
/*
* Use get_post_meta() to retrieve an existing value
* from the database and use the value for the form.
*/
$value = get_post_meta( $post->ID, '_hurtigtech_extra_content', true );
echo '<br />';
wp_editor( $value, "hurtigtech_extra_content_editor");
}
/**
* When the post is saved, saves our custom data.
*
* #param int $post_id The ID of the post being saved.
*/
function hurtigtech_save_postdata( $post_id ) {
/*
* We need to verify this came from the our screen and with proper authorization,
* because save_post can be triggered at other times.
*/
// Check if our nonce is set.
if ( ! isset( $_POST['hurtigtech_inner_custom_box_nonce'] ) )
return $post_id;
$nonce = $_POST['hurtigtech_inner_custom_box_nonce'];
// Verify that the nonce is valid.
if ( ! wp_verify_nonce( $nonce, 'hurtigtech_inner_custom_box' ) )
return $post_id;
// If this is an autosave, our form has not been submitted, so we don't want to do anything.
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
return $post_id;
// Check the user's permissions.
if ( 'page' == $_POST['post_type'] ) {
if ( ! current_user_can( 'edit_page', $post_id ) )
return $post_id;
} else {
if ( ! current_user_can( 'edit_post', $post_id ) )
return $post_id;
}
/* OK, its safe for us to save the data now. */
// Sanitize user input.
$mydata = sanitize_text_field( $_POST['hurtigtech_extra_content_editor'] );
// Update the meta field in the database.
update_post_meta( $post_id, '_hurtigtech_extra_content', $mydata );
}
add_action( 'save_post', 'hurtigtech_save_postdata' );
NOTE: There is a style issue with the content box background. This needs to be added to an editor-style.css file to fix it.
.hurtigtech_extra_content_editor {
background: #fff;
}

Resources