{"id":32,"date":"2026-11-05T14:00:00","date_gmt":"2026-11-05T08:00:00","guid":{"rendered":"https:\/\/nazmulrobin.com\/blog\/?p=32"},"modified":"2026-11-10T18:33:36","modified_gmt":"2026-11-10T12:33:36","slug":"reading-time-contents-and-reactions-in-wordpress","status":"publish","type":"post","link":"https:\/\/nazmulrobin.com\/blog\/reading-time-contents-and-reactions-in-wordpress\/","title":{"rendered":"Reading time, a contents list and reactions in WordPress, without a plugin for each"},"content":{"rendered":"\n<p>Every post on this blog now shows three small things: how many minutes it takes to read, a list of its sections, and a row of reaction buttons at the end. Each is one small PHP file in this blog&#8217;s own site plugin, and the reactions add one short JavaScript file.<\/p>\n<p>This is the fourth post about how this blog is built. The earlier ones cover <a href=\"https:\/\/nazmulrobin.com\/blog\/laravel-and-wordpress-on-one-domain\/\">running WordPress at \/blog on a Laravel site<\/a>, <a href=\"https:\/\/nazmulrobin.com\/blog\/share-wordpress-posts-on-linkedin\/\">sharing posts on LinkedIn<\/a> and <a href=\"https:\/\/nazmulrobin.com\/blog\/publish-wordpress-posts-from-markdown\/\">publishing posts from Markdown files<\/a>.<\/p>\n<h2>Why these three<\/h2>\n<p>My posts are how-to posts. People do not read them from top to bottom; they arrive with a problem and look for the part that solves it.<\/p>\n<ul>\n<li><strong>Reading time<\/strong> answers the first question a reader has: is this a two minute tip or a ten minute walkthrough? They can decide to read now or save it.<\/li>\n<li><strong>A contents list<\/strong> lets them jump to the section they came for. It also shows the shape of the post before they commit to it.<\/li>\n<li><strong>Reactions<\/strong> are for me. A comment takes effort, so most readers never leave one. A reaction is one click, with no name and no login, and it tells me which posts were worth writing.<\/li>\n<\/ul>\n<p>There are plugins for all three. I did not want three plugins, each with a settings page, for what turned out to be about 300 lines.<\/p>\n<h2>One rule shared by all three<\/h2>\n<p>Nothing is saved in the post. All three change the page when it is shown, through the <code>the_content<\/code> filter. If I change how the contents list looks, every post has the new one at once, and my Markdown files stay plain.<\/p>\n<p>That filter runs in more places than a post&#8217;s own page: in feeds, in excerpts, and for other posts listed on the same page. So each of the three starts with the same check:<\/p>\n<pre><code class=\"language-php hljs\"><span class=\"hljs-keyword\">if<\/span> ( ! is_singular( <span class=\"hljs-string\">'post'<\/span> ) || ! in_the_loop() || get_the_ID() !== get_queried_object_id() ) {\n    <span class=\"hljs-keyword\">return<\/span> $content;\n}<\/code><\/pre>\n<p>It reads: a single post is being viewed, WordPress is inside its loop, and the content being filtered belongs to the post in the URL.<\/p>\n<h2>Reading time<\/h2>\n<p>Count the words, divide by a reading speed, round up. I use 200 words a minute.<\/p>\n<pre><code class=\"language-php hljs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">myblog_reading_minutes<\/span><span class=\"hljs-params\">( $content )<\/span> <\/span>{\n    <span class=\"hljs-keyword\">return<\/span> max( <span class=\"hljs-number\">1<\/span>, (int) ceil( str_word_count( wp_strip_all_tags( $content ) ) \/ <span class=\"hljs-number\">200<\/span> ) );\n}\n\nadd_filter(\n    <span class=\"hljs-string\">'the_content'<\/span>,\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">( $content )<\/span> <\/span>{\n        <span class=\"hljs-comment\">\/\/ The check from above goes here.<\/span>\n\n        $minutes = myblog_reading_minutes( get_post_field( <span class=\"hljs-string\">'post_content'<\/span>, get_the_ID() ) );\n\n        <span class=\"hljs-keyword\">return<\/span> sprintf(\n            <span class=\"hljs-string\">'&lt;p class=\"myblog-reading-time\"&gt;%s&lt;\/p&gt;'<\/span>,\n            esc_html( sprintf( __( <span class=\"hljs-string\">'%s min read'<\/span>, <span class=\"hljs-string\">'myblog'<\/span> ), number_format_i18n( $minutes ) ) )\n        ) . $content;\n    },\n    <span class=\"hljs-number\">30<\/span>\n);<\/code><\/pre>\n<p>Two details matter. The words are counted in the stored post, not in <code>$content<\/code>, because by then other filters have added their own text to it. And the priority is 30, later than the contents list at 20, so the reading time ends up above the list and not under it.<\/p>\n<p>Later I redesigned the blog and moved the reading time out of the content, to the line beside the date. The theme&#8217;s template now asks for the same number through a block binding, so <code>myblog_reading_minutes()<\/code> stayed and the filter went. If the theme is not yours to edit, the filter above is still the shortest way.<\/p>\n<h2>The contents list<\/h2>\n<p>My posts arrive from Markdown, so a section heading is a bare <code>&lt;h2&gt;<\/code> with no attributes. The filter does two jobs in one pass: it gives each heading an <code>id<\/code>, and it collects a link to that <code>id<\/code>.<\/p>\n<pre><code class=\"language-php hljs\">$items = <span class=\"hljs-keyword\">array<\/span>();\n\n$with_ids = preg_replace_callback(\n    <span class=\"hljs-string\">'\/&lt;h2&gt;(.*?)&lt;\\\/h2&gt;\/s'<\/span>,\n    <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-params\">( $heading )<\/span> <span class=\"hljs-title\">use<\/span> <span class=\"hljs-params\">( &amp;$items )<\/span> <\/span>{\n        $text = wp_strip_all_tags( $heading[<span class=\"hljs-number\">1<\/span>] );\n        $slug = sanitize_title( $text );\n        $slug = $slug ? $slug : <span class=\"hljs-string\">'section'<\/span>;\n        $id   = $slug;\n\n        <span class=\"hljs-keyword\">for<\/span> ( $number = <span class=\"hljs-number\">2<\/span>; <span class=\"hljs-keyword\">isset<\/span>( $items[ $id ] ); $number++ ) {\n            $id = $slug . <span class=\"hljs-string\">'-'<\/span> . $number;\n        }\n\n        $items[ $id ] = sprintf( <span class=\"hljs-string\">'&lt;li&gt;&lt;a href=\"#%s\"&gt;%s&lt;\/a&gt;&lt;\/li&gt;'<\/span>, esc_attr( $id ), esc_html( $text ) );\n\n        <span class=\"hljs-keyword\">return<\/span> sprintf( <span class=\"hljs-string\">'&lt;h2 id=\"%s\"&gt;%s&lt;\/h2&gt;'<\/span>, esc_attr( $id ), $heading[<span class=\"hljs-number\">1<\/span>] );\n    },\n    $content\n);\n\n<span class=\"hljs-keyword\">if<\/span> ( count( $items ) &lt; <span class=\"hljs-number\">3<\/span> ) {\n    <span class=\"hljs-keyword\">return<\/span> $content;\n}\n\n<span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-string\">'&lt;nav class=\"myblog-toc\" aria-label=\"Table of contents\"&gt;&lt;ol&gt;'<\/span> . implode( <span class=\"hljs-string\">''<\/span>, $items ) . <span class=\"hljs-string\">'&lt;\/ol&gt;&lt;\/nav&gt;'<\/span> . $with_ids;<\/code><\/pre>\n<p><code>sanitize_title()<\/code> turns &#8220;Keeping the blog&#8217;s code in git&#8221; into <code>keeping-the-blogs-code-in-git<\/code>, the same way WordPress makes a post slug. The loop adds <code>-2<\/code>, <code>-3<\/code> when two headings have the same text, since an <code>id<\/code> has to be unique on the page. A post with fewer than three sections gets no list; a list of two links is noise.<\/p>\n<p>One line of CSS stops a heading from landing at the very top edge of the window when its link is clicked:<\/p>\n<pre><code class=\"language-css hljs\"><span class=\"hljs-selector-class\">.wp-block-post-content<\/span> <span class=\"hljs-selector-tag\">h2<\/span><span class=\"hljs-selector-attr\">[id]<\/span> { <span class=\"hljs-attribute\">scroll-margin-top<\/span>: <span class=\"hljs-number\">3rem<\/span>; }<\/code><\/pre>\n<h2>Reactions<\/h2>\n<p>Reactions need three parts: somewhere to keep them, a way to send one, and the buttons.<\/p>\n<p><strong>Keeping them.<\/strong> Each post has one post meta value, an array of visitor to reaction. The counts are worked out from it with <code>array_count_values()<\/code>. Keeping who reacted, and not just a number per reaction, is what makes &#8220;one reaction per visitor&#8221; possible, and lets a visitor change their mind.<\/p>\n<p>There is no login, so a visitor is their IP address, passed through <code>wp_hash()<\/code>. That is a salted hash, so the address itself is never stored:<\/p>\n<pre><code class=\"language-php hljs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">myblog_reactions_visitor<\/span><span class=\"hljs-params\">()<\/span> <\/span>{\n    <span class=\"hljs-keyword\">return<\/span> wp_hash( <span class=\"hljs-keyword\">isset<\/span>( $_SERVER[<span class=\"hljs-string\">'REMOTE_ADDR'<\/span>] ) ? sanitize_text_field( wp_unslash( $_SERVER[<span class=\"hljs-string\">'REMOTE_ADDR'<\/span>] ) ) : <span class=\"hljs-string\">''<\/span> );\n}<\/code><\/pre>\n<p><strong>Sending one.<\/strong> A REST route takes the post ID from the URL and the reaction from the request. The <code>enum<\/code> makes WordPress reject anything that is not on the list before my code runs:<\/p>\n<pre><code class=\"language-php hljs\">register_rest_route(\n    <span class=\"hljs-string\">'myblog\/v1'<\/span>,\n    <span class=\"hljs-string\">'\/reactions\/(?P&lt;id&gt;\\d+)'<\/span>,\n    <span class=\"hljs-keyword\">array<\/span>(\n        <span class=\"hljs-string\">'methods'<\/span>             =&gt; <span class=\"hljs-string\">'POST'<\/span>,\n        <span class=\"hljs-string\">'permission_callback'<\/span> =&gt; <span class=\"hljs-string\">'__return_true'<\/span>,\n        <span class=\"hljs-string\">'args'<\/span>                =&gt; <span class=\"hljs-keyword\">array<\/span>(\n            <span class=\"hljs-string\">'reaction'<\/span> =&gt; <span class=\"hljs-keyword\">array<\/span>(\n                <span class=\"hljs-string\">'required'<\/span> =&gt; <span class=\"hljs-keyword\">true<\/span>,\n                <span class=\"hljs-string\">'type'<\/span>     =&gt; <span class=\"hljs-string\">'string'<\/span>,\n                <span class=\"hljs-string\">'enum'<\/span>     =&gt; <span class=\"hljs-keyword\">array<\/span>( <span class=\"hljs-string\">'like'<\/span>, <span class=\"hljs-string\">'love'<\/span>, <span class=\"hljs-string\">'haha'<\/span>, <span class=\"hljs-string\">'wow'<\/span>, <span class=\"hljs-string\">'sad'<\/span>, <span class=\"hljs-string\">'angry'<\/span> ),\n            ),\n        ),\n        <span class=\"hljs-string\">'callback'<\/span>            =&gt; <span class=\"hljs-string\">'myblog_reactions_save'<\/span>,\n    )\n);<\/code><\/pre>\n<p>The callback refuses anything that is not a published, public post, then sets, moves or removes the visitor&#8217;s reaction:<\/p>\n<pre><code class=\"language-php hljs\"><span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> <span class=\"hljs-title\">myblog_reactions_save<\/span><span class=\"hljs-params\">( $request )<\/span> <\/span>{\n    $post = get_post( (int) $request[<span class=\"hljs-string\">'id'<\/span>] );\n\n    <span class=\"hljs-keyword\">if<\/span> ( ! $post || <span class=\"hljs-string\">'post'<\/span> !== $post-&gt;post_type || <span class=\"hljs-string\">'publish'<\/span> !== $post-&gt;post_status || post_password_required( $post ) ) {\n        <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">new<\/span> WP_Error( <span class=\"hljs-string\">'myblog_no_post'<\/span>, <span class=\"hljs-string\">'This post cannot be reacted to.'<\/span>, <span class=\"hljs-keyword\">array<\/span>( <span class=\"hljs-string\">'status'<\/span> =&gt; <span class=\"hljs-number\">404<\/span> ) );\n    }\n\n    $given   = myblog_reactions_given( $post-&gt;ID );\n    $visitor = myblog_reactions_visitor();\n\n    <span class=\"hljs-comment\">\/\/ Choosing the same reaction again takes it back.<\/span>\n    <span class=\"hljs-keyword\">if<\/span> ( <span class=\"hljs-keyword\">isset<\/span>( $given[ $visitor ] ) &amp;&amp; $given[ $visitor ] === $request[<span class=\"hljs-string\">'reaction'<\/span>] ) {\n        <span class=\"hljs-keyword\">unset<\/span>( $given[ $visitor ] );\n    } <span class=\"hljs-keyword\">else<\/span> {\n        $given[ $visitor ] = $request[<span class=\"hljs-string\">'reaction'<\/span>];\n    }\n\n    update_post_meta( $post-&gt;ID, <span class=\"hljs-string\">'_myblog_reactions'<\/span>, $given );\n\n    <span class=\"hljs-keyword\">return<\/span> <span class=\"hljs-keyword\">array<\/span>(\n        <span class=\"hljs-string\">'counts'<\/span> =&gt; array_count_values( $given ),\n        <span class=\"hljs-string\">'mine'<\/span>   =&gt; <span class=\"hljs-keyword\">isset<\/span>( $given[ $visitor ] ) ? $given[ $visitor ] : <span class=\"hljs-string\">''<\/span>,\n    );\n}<\/code><\/pre>\n<p><strong>The buttons.<\/strong> PHP prints them after the content, with the current counts and with <code>aria-pressed=\"true\"<\/code> on the visitor&#8217;s own reaction. The route&#8217;s URL sits in a <code>data-url<\/code> attribute on the wrapper, so the script needs no settings passed to it:<\/p>\n<pre><code class=\"language-js hljs\"><span class=\"hljs-built_in\">document<\/span>.querySelectorAll( <span class=\"hljs-string\">'.myblog-reactions'<\/span> ).forEach( <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"> box <\/span>) <\/span>{\n    box.addEventListener( <span class=\"hljs-string\">'click'<\/span>, <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"> event <\/span>) <\/span>{\n        <span class=\"hljs-keyword\">var<\/span> button = event.target.closest( <span class=\"hljs-string\">'button[data-reaction]'<\/span> );\n\n        <span class=\"hljs-keyword\">if<\/span> ( ! button ) {\n            <span class=\"hljs-keyword\">return<\/span>;\n        }\n\n        fetch( box.dataset.url, {\n            <span class=\"hljs-attr\">method<\/span>: <span class=\"hljs-string\">'POST'<\/span>,\n            <span class=\"hljs-attr\">headers<\/span>: { <span class=\"hljs-string\">'Content-Type'<\/span>: <span class=\"hljs-string\">'application\/json'<\/span> },\n            <span class=\"hljs-attr\">body<\/span>: <span class=\"hljs-built_in\">JSON<\/span>.stringify( { <span class=\"hljs-attr\">reaction<\/span>: button.dataset.reaction } ),\n        } )\n            .then( <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"> response <\/span>) <\/span>{\n                <span class=\"hljs-keyword\">return<\/span> response.ok ? response.json() : <span class=\"hljs-built_in\">Promise<\/span>.reject();\n            } )\n            .then( <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"> data <\/span>) <\/span>{\n                box.querySelectorAll( <span class=\"hljs-string\">'button[data-reaction]'<\/span> ).forEach( <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"> item <\/span>) <\/span>{\n                    <span class=\"hljs-keyword\">var<\/span> name = item.dataset.reaction;\n\n                    item.setAttribute( <span class=\"hljs-string\">'aria-pressed'<\/span>, data.mine === name ? <span class=\"hljs-string\">'true'<\/span> : <span class=\"hljs-string\">'false'<\/span> );\n                    item.querySelector( <span class=\"hljs-string\">'.myblog-reactions__count'<\/span> ).textContent = data.counts[ name ] || <span class=\"hljs-string\">''<\/span>;\n                } );\n            } )\n            .catch( <span class=\"hljs-function\"><span class=\"hljs-keyword\">function<\/span> (<span class=\"hljs-params\"><\/span>) <\/span>{} );\n    } );\n} );<\/code><\/pre>\n<p>The server answers with the new counts and the visitor&#8217;s own reaction, and the script paints exactly that. It never guesses the numbers itself, so the page cannot drift from what is stored.<\/p>\n<h2>Things that caught me<\/h2>\n<ul>\n<li><strong>An IP address is not a person.<\/strong> Everyone in one office or on one home network shares a reaction, and someone whose address changes can react twice. For a personal blog I accept that. The alternatives are a cookie, which is cleared in one click, or a login, which nobody will do for a thumbs up.<\/li>\n<li><strong>Missing post meta is an empty string, not an empty array.<\/strong> <code>get_post_meta( $id, $key, true )<\/code> returns <code>''<\/code> for a post with no reactions, and <code>array_count_values( (array) '' )<\/code> counts one reaction with no name. A small helper returns the value only when it is an array.<\/li>\n<li><strong>No nonce on the route.<\/strong> A WordPress REST nonce proves who a logged-in user is. This route does the same thing for everyone, so there is nothing for it to prove. The worst a forged request can do is place one reaction from that visitor.<\/li>\n<li><strong>A page cache would break the highlight.<\/strong> The visitor&#8217;s own reaction is marked when PHP builds the page. This blog has no full-page cache. With one, the buttons would have to load their state by script.<\/li>\n<li><strong>The first reading time was too high.<\/strong> I counted the words in the filtered content, which already held the contents list, so every heading was counted twice. Counting the stored post fixed it.<\/li>\n<\/ul>\n<p>That is three features in three files, and no settings page for any of them. If you got this far, the buttons are right below.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Every post on this blog shows how long it takes to read, a list of its sections and a row of reaction buttons. Each one is a small PHP file in my site plugin. Here is why I wanted them and the code.<\/p>\n","protected":false},"author":1,"featured_media":178,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_nhrrob_social_share_linkedin_text":"Reading time, a contents list and reaction buttons. Three small things, and the usual answer is three plugins.\n\nOn this blog each one is a small PHP file in my own site plugin, and the reactions add one short script.\n\nThe post has why I wanted them, the code, and the things that caught me.\n\nWhere do you draw the line between a plugin and a few lines of your own code?","_nhrrob_social_share_linkedin_layout":"","_nhrrob_social_share_x_text":"","_nhrrob_social_share_reddit":[],"_nhrrob_social_share_pro_texts":[],"_nhrrob_social_share_pro_x_texts":[],"footnotes":""},"categories":[7],"tags":[8,16,24],"class_list":["post-32","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-wordpress","tag-building-this-blog","tag-plugin-development","tag-rest-api"],"_links":{"self":[{"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/posts\/32","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/comments?post=32"}],"version-history":[{"count":2,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/posts\/32\/revisions"}],"predecessor-version":[{"id":40,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/posts\/32\/revisions\/40"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/media\/178"}],"wp:attachment":[{"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/media?parent=32"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/categories?post=32"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/nazmulrobin.com\/blog\/wp-json\/wp\/v2\/tags?post=32"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}