Automatically list wp posts

You can list automatically wordpress posts in your php webpage, based on its tags.

The following php code allow you to list all wp posts with a given tag:

<?php

// --- 1️⃣ Caricamento WordPress (solo se non già caricato) ---
if (!function_exists('get_posts')) {
    $possible_paths = [
        __DIR__."/../[your-wp-path]/wp-load.php",  // standard
        __DIR__."/../../[your-wp-path]/wp-load.php", // if you inclyde subfolders
    ];
    foreach ($possible_paths as $path) {
        if (file_exists($path)) {
            require_once($path);
            break;
        }
    }
}

// --- 2️⃣ Preparazione query ---
global $post;
$args = [
    'posts_per_page' => 200,
];

if (!empty($whatcategory)) {
    $args['category_name'] = $whatcategory; // category slug 
}
if (!empty($whattag)) {
    // $args['tag'] = $whattag; 
    $args['tag_slug__in'] = array_map('trim', explode(',', $whattag)); // tag slug (not shown names)
}

// --- 3️⃣ Cache opzionale (transient WordPress) ---
$cache_key = 'lista_blog_' . ($whatcategory ?? 'none') . '_' . ($whattag ?? 'none');
$myposts = get_transient($cache_key);

if ($myposts === false) {
    $myposts = get_posts($args);
    set_transient($cache_key, $myposts, 3600); // cache 1 ora
}

// --- 4️⃣ Output ---
if (!empty($myposts)) {
    echo '<h2>
        <span lang="en">Our blog posts about this topic</span>
        <span lang="it">Posts del nostro blog su questo tema</span>
    </h2>
    <ul id="blog-posts">';

    foreach ($myposts as $post) {
        // Non dipendiamo dal loop globale
        echo '<li><a href="'.get_permalink($post).'" rel="bookmark">'.get_the_title($post).'</a></li>';
    }

    echo '</ul>';
    wp_reset_postdata();
}
?>

You can put this code in a separate file, and include it in your php webpage, i.g. in the footer, with a code like the following:

<?php
$listablog = "[the-path-of-your-separate-file/the-name-of-your-separate-file";
  if (file_exists($listablog)) {
    if (
        (isset($whatcategory) && !empty($whatcategory)) ||
        (isset($whattag) && !empty($whattag))
    ) {
        include $listablog;
    }
  }
?>

In the header of a webpage where you want add this list, you have to set the value of the tag you want list:
$whattag="your tag,another tag";

Be careful: you has to set, as value, not the visualized tag name, but the “slug”. You can see it also with mouse hover and status bar.

Php variables in WordPress

To set a variable, such as an url, you can use the following steps:

  • add to your wp-config a code with something like
require_once ABSPATH . 'wp-settings.php';
/** variabili */
define('GLOSSARIO_URL', 'yourwebsite/glossario.php');
  • add to functions.php (in your wp theme root) something like
define('GLOSSARIO_URL', 'yourwebsite/glossario.php');

function glossario_link($atts) {
    $atts = shortcode_atts([
        'id' => '',
        'testo' => ''
    ], $atts);

    $url = GLOSSARIO_URL . '#' . $atts['id'];

    return '<a href="' . esc_url($url) . '">' . esc_html($atts['testo']) . '</a>';
}

add_shortcode('glossario', 'glossario_link');
  • in wp editor you will be able to call that code inserting a text like this:
[glossario id="universalismo" testo="universalisticamente"]

where the content of testo="" is what will appears in your wp page (while in the editor you will see that code)

Fix a corrupt innodb

Today happened that mariadb worked almost correctly, but two wordpress db were incorrectly managed. Indeed I could modify a post, but I couldn’t add a new one.

In another PC I, luckily, had the good wp db (perfectlty working with its innodb). So, it was possible to fix this problem. With the following steps:

a) in the well working device dump (from a teminal) the working wp db:

mysqldump -u root -p --single-transaction --routines --triggers your-db-name > dump-yourdbname.sql

b) in the bad working device

  • activate (if not already active) mariadb
  • in a terminal: mysql -u root -p (of course you have to provide your mysql psw)
  • and then, within mysql, you have to delete the old, bad, db, and create a new one:
    • DROP DATABASE IF EXISTS yourdbname;
    • CREATE DATABASE yourdbname CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
    • EXIT;
  • Now you have a new, good but empty db. You have now to import the content of it, with this code: mysql -u root -p yourdbname < dump-yourdbname.sql

Now all should work 🙂.

External markdown file in WordPress

If you want keep an external markdown file and include it in a WordPress page, you can follow these steps:

  • add a js file, such as md-block.js, in your js theme folder (typically /wp-content/themes/your-theme/js/ )
  • modify the functions.php file, in your root theme folder,. adding this code:
// per markdown BEGIN

function carica_md_block() {
    wp_enqueue_script(
        'md-block',
        get_stylesheet_directory_uri() . '/js/md-block.js',
        array(),
        null,
        true
    );
}
add_action('wp_enqueue_scripts', 'carica_md_block');

add_filter('script_loader_tag', function($tag, $handle, $src) {
    if ($handle === 'md-block') {
        return '<script type="module" src="' . esc_url($src) . '"></script>';
    }
    return $tag;
}, 10, 3);

function shortcode_scheda_md($atts) {
    $atts = shortcode_atts(array(
        'file' => ''
    ), $atts);

    $file = basename($atts['file']);

    if (empty($file) || pathinfo($file, PATHINFO_EXTENSION) !== 'md') {
        return '';
    }

    $url = content_url('/uploads/some-path/' . rawurlencode($file));

    return '<md-block src="' . esc_url($url) . '"></md-block>';
}
add_shortcode('scheda_md', 'shortcode_scheda_md');

// per markdown END
  • you can put your md files in the path above set: /uploads/some-path/ . Note that the folder some-path could be a symlinked one, from your local PC.
  • in the wordpress page when you want include a md file you can write,
    • using HTML (customized), [scheda_md file="the-name-of-the-file.md"],
    • or the code visualizaztion: something like[scheda_md]the-name-of-the-file.md[/scheda_md]
  • where that file, obviously, should be in /some-path/ folder.

wp plugins

wp users

An useful wp plugin is wp users that allow you to collect subscriptions from the readers of your blog.

It has add-ons such as captcha that, linked with Google captcha, allow you to select humans from robots (and spam).

Be careful however to set v2 rather than v3, both in Google and in your wp plugin settings, otherwise you couldn’t be more able to login.

Permalink in local wordpress

It could happen that wordpress in localhost doesn’t see textual permalink, such as the article name, or the like, and see only ”simple” permalink with a final suffix such as ?p=123.

The problem is an apache problem. To fix it, you have to:

  • modifying the apache config file, with a name such as apache2.conf or another name, depending of your S.O., by adding something like
<Directory /var/www/your-wordpress-path/>
	Options Indexes FollowSymLinks
	AllowOverride all
	Require all granted
</Directory>
  • then you have to do these bash commands  (in a terminal):
sudo a2enmod rewrite
sudo systemctl restart apache2
  • then you have to put in your (root wordpress) folder an .htaccess file with a content like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
RewriteBase /your-wordpress-path/
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /your-wordpress-path/index.php [L]
</IfModule>

your-wordpress-path is the path following http://localhost, so don't have to write http://localhost

At this point you should be able to set a textual permalink, after setting it, save it, and try.

mysql multiple tables rename

To rename many mysql/mariadb tables with a same prefix, you can uso this script (in a terminal)

mysql -u root -p -N -e " SELECT CONCAT('RENAME TABLE \', table_name, '\ TO \', REPLACE(table_name, 'oldprefix_', 'newprefix_'), '\;') FROM information_schema.tables WHERE table_schema = 'your-database' AND table_name LIKE 'oldprefix_%'; " > renamed.sql 

In this way will created the file renamed.sql (same tables, with different names), that you then can use to replace your database, with

mysql -u root -p yourdatabase < renamed.sql

If you have a wordpress database you have also to check options and meta tables, removing oldprefixes, with:

UPDATE oldprefix_options
SET option_name = REPLACE(option_name, 'oldprefix_', 'newprefix_')
WHERE option_name LIKE 'oldprefix\_%';

and

UPDATE abc_usermeta
SET meta_key = REPLACE(meta_key, 'oldprefix_', 'newprefix_')
WHERE meta_key LIKE 'oldprefix\_%';

And finally, you could check if there are any oldprefix, in options with

SELECT option_name FROM newprefix_options WHERE option_name LIKE 'oldprefix\_%';

same for meta:

SELECT meta_key FROM newprefix_usermeta WHERE meta_key LIKE 'oldprefix\_%';

WordPress in localhost: permalinks

There could be some problems to fix setting wp in localhost.

One is to get permalink working: there are at least two steps:

  • a working .htaccess (in the root of wp installation) with a code that wp itself will provide,
  • and a corrert apache configuration (in apache configuration file, such as apache2.conf or httpd.conf), that is you should set something like the following:
<Directory /var/www/html>
    Options Indexes FollowSymLinks
    AllowOverride None
    Require all granted
</Directory>

<Directory /var/www/html/your-path/to-local-wp>
    Options Indexes FollowSymLinks
    AllowOverride All
    Require all granted
</Directory>
  • furthermore you should do this command: sudo a2enmod rewrite
  • and then sudo systemctl restart apache2

Connecting a wordpress category to a facebook page

IFTT is a good app, but with a free plan you can connect only one wordpress category to one facebook page.

There are many plugins and many web services, such as Zapier, or Activepieces, that can connect wordpress with a facebook page, but if you have a free wordpress plan (with an address like yourdomain.wordpress.com) you can install plugins only upgrading your plan.