qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
311,158
<p>How do I make my single-work page show on my <code>front-page.php</code>?</p> <p>So I want to show my <code>work</code> page on the homepage. For example, my work page link is <code>www.example.com/work</code> but I want to show the work page in <code>www.example.com</code>. Should I use gettemplate code?</p>
[ { "answer_id": 311159, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 1, "selected": false, "text": "<p>No CODE is necessary for this.</p>\n\n<p>Go to WordPress Admin Panel → <code>Settings</code> → <code>Reading</code>.</p>\n\n<p>Then from the option <code>Your homepage displays</code>, select <code>A static page (select below)</code> &amp; then in the <code>Homepage:</code> dropdown menu, select your <code>Work</code> page &amp; <kbd>Save Changes</kbd>.</p>\n\n<p>Like the screenshot below:</p>\n\n<p><a href=\"https://i.stack.imgur.com/eSIyy.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/eSIyy.png\" alt=\"Select a static page as home page\"></a>.</p>\n\n<p>Of course, once you've done this, your <code>Work</code> page content will be loaded on the site home page (e.g. <code>www.example.com</code>) with proper home page template (e.g. <code>front-page.php</code>) of your theme.</p>\n\n<p>Check the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/#home-page-display\" rel=\"nofollow noreferrer\">Template Hierarchy document</a> to learn which theme template will handle the home page in different situations.</p>\n\n<h2>Custom Home Page Template</h2>\n\n<p>Say you have a <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">template file</a> (within the theme) named <code>single-work.php</code> and another template file <code>front-page.php</code>. According to WordPress template hierarchy, <code>front-page.php</code> will load the home page, regardless of the setting <code>Your latest posts</code> or <code>A static Page</code>.</p>\n\n<p>You can change that if you choose <code>A static page</code>. Let's say you have a static page named <code>Work</code> &amp; you select this page as your <code>Homepage</code>. Now, first, put the following CODE at the top of <code>single-work.php</code> template file:</p>\n\n<pre><code>&lt;?php\n /* Template Name: Work Template */\n</code></pre>\n\n<p>Then edit <code>work</code> page and you'll see the Template selection option under <code>Page Attributes</code>:</p>\n\n<p><a href=\"https://i.stack.imgur.com/5lLf4.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5lLf4.png\" alt=\"custom template\"></a></p>\n\n<p>From there, select <code>Work Template</code> and save. That way, the home page will load using <code>single-work.php</code> template instead of <code>front-page.php</code>.</p>\n\n<blockquote>\n <p><strong>Note:</strong> if you don't see the <code>Page Attributes</code> meta box, then select <code>Page Attributes</code> from top right <code>Screen Options</code> drop down menu.</p>\n</blockquote>\n" }, { "answer_id": 311165, "author": "wpdev", "author_id": 133897, "author_profile": "https://wordpress.stackexchange.com/users/133897", "pm_score": 0, "selected": false, "text": "<p>Create a new file as named <code>work.php</code> in your theme directory folder and add this code top of the file:</p>\n\n<pre><code>&lt;?php \n/*\nTemplate Name: Work\nTemplate Post Type: page\n*/\n?&gt;\n\nYour codes here...\n</code></pre>\n\n<p>Go -> Pages, edit your Work page. And select page template as <code>Work</code></p>\n\n<p>And go reading settings. Select front page as <code>Work</code></p>\n" } ]
2018/08/11
[ "https://wordpress.stackexchange.com/questions/311158", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/82064/" ]
How do I make my single-work page show on my `front-page.php`? So I want to show my `work` page on the homepage. For example, my work page link is `www.example.com/work` but I want to show the work page in `www.example.com`. Should I use gettemplate code?
No CODE is necessary for this. Go to WordPress Admin Panel → `Settings` → `Reading`. Then from the option `Your homepage displays`, select `A static page (select below)` & then in the `Homepage:` dropdown menu, select your `Work` page & `Save Changes`. Like the screenshot below: [![Select a static page as home page](https://i.stack.imgur.com/eSIyy.png)](https://i.stack.imgur.com/eSIyy.png). Of course, once you've done this, your `Work` page content will be loaded on the site home page (e.g. `www.example.com`) with proper home page template (e.g. `front-page.php`) of your theme. Check the [Template Hierarchy document](https://developer.wordpress.org/themes/basics/template-hierarchy/#home-page-display) to learn which theme template will handle the home page in different situations. Custom Home Page Template ------------------------- Say you have a [template file](https://developer.wordpress.org/themes/template-files-section/page-template-files/) (within the theme) named `single-work.php` and another template file `front-page.php`. According to WordPress template hierarchy, `front-page.php` will load the home page, regardless of the setting `Your latest posts` or `A static Page`. You can change that if you choose `A static page`. Let's say you have a static page named `Work` & you select this page as your `Homepage`. Now, first, put the following CODE at the top of `single-work.php` template file: ``` <?php /* Template Name: Work Template */ ``` Then edit `work` page and you'll see the Template selection option under `Page Attributes`: [![custom template](https://i.stack.imgur.com/5lLf4.png)](https://i.stack.imgur.com/5lLf4.png) From there, select `Work Template` and save. That way, the home page will load using `single-work.php` template instead of `front-page.php`. > > **Note:** if you don't see the `Page Attributes` meta box, then select `Page Attributes` from top right `Screen Options` drop down menu. > > >
311,199
<p>I am new in WordPress Development. How can I get <code>Menus</code> in Admin Panel like below ?</p> <p><a href="https://i.stack.imgur.com/e68P7.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/e68P7.png" alt="enter image description here"></a></p> <p>I am trying to develop a theme. But I couldn't display that.</p> <p><a href="https://i.stack.imgur.com/gBMD2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/gBMD2.png" alt="enter image description here"></a></p>
[ { "answer_id": 311200, "author": "John Doe", "author_id": 78806, "author_profile": "https://wordpress.stackexchange.com/users/78806", "pm_score": 2, "selected": false, "text": "<p>You can refer to <a href=\"https://codex.wordpress.org/Navigation_Menus\" rel=\"nofollow noreferrer\">this link</a> for more information.</p>\n\n<p>Basically, for Menus to show up, you need to use the WordPress function <code>register_nav_menu()</code> to register that your theme supports at least 1 menu. Each registered menu corresponds to a checkbox under the <em>Display location</em> (which is under the <strong>Menu Settings</strong> header) section at the bottom of the Menu page.</p>\n\n<p><a href=\"https://i.stack.imgur.com/AVqXx.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/AVqXx.jpg\" alt=\"Display location menus\"></a></p>\n" }, { "answer_id": 311201, "author": "Will Chiswick", "author_id": 148567, "author_profile": "https://wordpress.stackexchange.com/users/148567", "pm_score": 3, "selected": true, "text": "<p>You need to register custom menus in your theme - <a href=\"https://codex.wordpress.org/Function_Reference/register_nav_menu\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_nav_menu</a> </p>\n\n<p>You first need to register your menu in functions.php like so: </p>\n\n<pre><code>add_action( 'after_setup_theme', 'register_my_menu' );\nfunction register_my_menu() {\n register_nav_menu( 'primary', __( 'Primary Menu', 'theme-slug' ) );\n}\n</code></pre>\n\n<p>Then, where you want your menu to appear - usually header.php - you call the function: </p>\n\n<pre><code>wp_nav_menu()\n</code></pre>\n" } ]
2018/08/12
[ "https://wordpress.stackexchange.com/questions/311199", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/104698/" ]
I am new in WordPress Development. How can I get `Menus` in Admin Panel like below ? [![enter image description here](https://i.stack.imgur.com/e68P7.png)](https://i.stack.imgur.com/e68P7.png) I am trying to develop a theme. But I couldn't display that. [![enter image description here](https://i.stack.imgur.com/gBMD2.png)](https://i.stack.imgur.com/gBMD2.png)
You need to register custom menus in your theme - <https://codex.wordpress.org/Function_Reference/register_nav_menu> You first need to register your menu in functions.php like so: ``` add_action( 'after_setup_theme', 'register_my_menu' ); function register_my_menu() { register_nav_menu( 'primary', __( 'Primary Menu', 'theme-slug' ) ); } ``` Then, where you want your menu to appear - usually header.php - you call the function: ``` wp_nav_menu() ```
311,209
<p>I've created a custom post-type along with a custom taxonomy and everything is fine, apart from one particular thing.</p> <p>First off, my use case: I need it to <em>act</em> like a category system, <em>however</em> <strong>not</strong> be hierarchical (one level only), so I left both to the default setting of <code>false</code> for the <code>hierarchical</code> setting.</p> <p>This has been fine, apart from one problem where it allows me to add a "sub-level" within the metabox.</p> <p><strong>First, the code:</strong></p> <pre><code>register_post_type( 'letter', array( 'labels' =&gt; array( 'name' =&gt; __( 'Letters' ), 'singular_name' =&gt; __( 'Letter' ), //.......... ), 'public' =&gt; true, 'taxonomies' =&gt; array('letter'), //........ ) ); // Our args for the custom taxonomy below $args = array( 'labels' =&gt; array( 'name' =&gt; __('Recipients'), 'singular_name' =&gt; __('Recipient'), //..... ), 'meta_box_cb' =&gt; 'post_categories_meta_box', ); // Register a custom taxonomy for our letter categories register_taxonomy( 'recipient', 'letter', $args ); // Connect the post type and taxonomy together to be safe register_taxonomy_for_object_type( 'recipient', 'letter' ); </code></pre> <p>Now, as you can see I needed to set the <code>meta_box_cb</code> to <code>post_categories_meta_box</code> otherwise it would end up having the functionality of the <strong>tag</strong> metabox, so, now it looks like this:</p> <p><a href="https://i.stack.imgur.com/RSH81.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RSH81.png" alt="enter image description here"></a></p> <p>So this is good, I get the category functionality that I like, however I also get the "Add New Recipient" where when you open it up it allows you to add a new "recipient" and select a <strong>parent</strong> recipient; <em>this</em> I do <strong>not</strong> want.</p> <p>Is my only option to create a new callback function based on the <code>post_categories_meta_box</code> function and <em>remove</em> the respective code to get rid of that parent functionality?</p> <p>I don't particularly want to do that as then it would break future updates to this function.</p> <p>Is there another option?</p>
[ { "answer_id": 313441, "author": "benny-ben", "author_id": 135157, "author_profile": "https://wordpress.stackexchange.com/users/135157", "pm_score": 0, "selected": false, "text": "<p>Given that it's a dirty option you could try this way:</p>\n\n<pre><code>function dirty_admin_customization() {\n\n // #newtaxonomy_parent\n $style = '&lt;style type=\"text/css\"&gt;#newrecipient_parent { display: none !important; }&lt;/style&gt;';\n\n echo $style . \"\\n\";\n\n}\nadd_action( 'admin_head-post.php', 'dirty_admin_customization' );\nadd_action( 'admin_head-post-new.php', 'dirty_admin_customization' );\n</code></pre>\n" }, { "answer_id": 373890, "author": "jerclarke", "author_id": 175, "author_profile": "https://wordpress.stackexchange.com/users/175", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://www.gazchap.com/posts/enable-checkbox-lists-non-hierarchical-taxonomies-wordpress/\" rel=\"nofollow noreferrer\">This blog post by &quot;Gazchap&quot;</a> deals with exactly the situation you are, and they updated it after publishing to your follow-up problem:</p>\n<blockquote>\n<p>Fortunately, version 4.4 of WordPress introduced a filter – post_edit_category_parent_dropdown_args – that could be used to control the parent terms shown in these meta boxes. It’s designed to let the developer change the terms listed, for example excluding certain categories, or only showing “top level” parent terms and not their descendants. There is no control that is designed to stop the menu being shown at all, but there is one that allows us to trick WordPress into hiding the parent drop-down select.</p>\n<p>Here’s the filter that you need:</p>\n</blockquote>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'post_edit_category_parent_dropdown_args', 'hide_parent_dropdown_select' );\n\nfunction hide_parent_dropdown_select( $args ) {\n if ( 'YOUR_TAXONOMY_SLUG' == $args['taxonomy'] ) {\n $args['echo'] = false;\n }\n return $args;\n}\n</code></pre>\n<blockquote>\n<p>Why does this work? The echo argument is set to true by default, and makes WordPress echo the dropdown select into the meta box. By setting this to false, WordPress instead returns the HTML instead, so it doesn’t get rendered to the browser.</p>\n</blockquote>\n<p>Note that of course <code>YOUR_TAXONOMY_SLUG</code> should be replaced with the slug of your custom taxonomy.</p>\n<p>Anyone attempting this hack should definitely read the blog post in full, it also has some other useful tips.</p>\n" } ]
2018/08/12
[ "https://wordpress.stackexchange.com/questions/311209", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1839/" ]
I've created a custom post-type along with a custom taxonomy and everything is fine, apart from one particular thing. First off, my use case: I need it to *act* like a category system, *however* **not** be hierarchical (one level only), so I left both to the default setting of `false` for the `hierarchical` setting. This has been fine, apart from one problem where it allows me to add a "sub-level" within the metabox. **First, the code:** ``` register_post_type( 'letter', array( 'labels' => array( 'name' => __( 'Letters' ), 'singular_name' => __( 'Letter' ), //.......... ), 'public' => true, 'taxonomies' => array('letter'), //........ ) ); // Our args for the custom taxonomy below $args = array( 'labels' => array( 'name' => __('Recipients'), 'singular_name' => __('Recipient'), //..... ), 'meta_box_cb' => 'post_categories_meta_box', ); // Register a custom taxonomy for our letter categories register_taxonomy( 'recipient', 'letter', $args ); // Connect the post type and taxonomy together to be safe register_taxonomy_for_object_type( 'recipient', 'letter' ); ``` Now, as you can see I needed to set the `meta_box_cb` to `post_categories_meta_box` otherwise it would end up having the functionality of the **tag** metabox, so, now it looks like this: [![enter image description here](https://i.stack.imgur.com/RSH81.png)](https://i.stack.imgur.com/RSH81.png) So this is good, I get the category functionality that I like, however I also get the "Add New Recipient" where when you open it up it allows you to add a new "recipient" and select a **parent** recipient; *this* I do **not** want. Is my only option to create a new callback function based on the `post_categories_meta_box` function and *remove* the respective code to get rid of that parent functionality? I don't particularly want to do that as then it would break future updates to this function. Is there another option?
[This blog post by "Gazchap"](https://www.gazchap.com/posts/enable-checkbox-lists-non-hierarchical-taxonomies-wordpress/) deals with exactly the situation you are, and they updated it after publishing to your follow-up problem: > > Fortunately, version 4.4 of WordPress introduced a filter – post\_edit\_category\_parent\_dropdown\_args – that could be used to control the parent terms shown in these meta boxes. It’s designed to let the developer change the terms listed, for example excluding certain categories, or only showing “top level” parent terms and not their descendants. There is no control that is designed to stop the menu being shown at all, but there is one that allows us to trick WordPress into hiding the parent drop-down select. > > > Here’s the filter that you need: > > > ```php add_filter( 'post_edit_category_parent_dropdown_args', 'hide_parent_dropdown_select' ); function hide_parent_dropdown_select( $args ) { if ( 'YOUR_TAXONOMY_SLUG' == $args['taxonomy'] ) { $args['echo'] = false; } return $args; } ``` > > Why does this work? The echo argument is set to true by default, and makes WordPress echo the dropdown select into the meta box. By setting this to false, WordPress instead returns the HTML instead, so it doesn’t get rendered to the browser. > > > Note that of course `YOUR_TAXONOMY_SLUG` should be replaced with the slug of your custom taxonomy. Anyone attempting this hack should definitely read the blog post in full, it also has some other useful tips.
311,218
<pre><code>&lt;?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $args = array( 'posts_per_page' =&gt; 6, 'offset'=&gt; 0, 'category' =&gt; 1, 'paged' =&gt; $paged ); $custom_query = new WP_Query( $args ); while($custom_query-&gt;have_posts()) : $custom_query-&gt;the_post(); ?&gt; </code></pre> <p>My Html code</p> <pre><code>&lt;?php endwhile; ?&gt; &lt;?php previous_posts_link('&amp;laquo; Newer posts'); next_posts_link( 'Older posts &amp;raquo;', $the_query-&gt;max_num_pages ); wp_reset_postdata(); ?&gt; </code></pre> <p>What's wrong?</p>
[ { "answer_id": 313441, "author": "benny-ben", "author_id": 135157, "author_profile": "https://wordpress.stackexchange.com/users/135157", "pm_score": 0, "selected": false, "text": "<p>Given that it's a dirty option you could try this way:</p>\n\n<pre><code>function dirty_admin_customization() {\n\n // #newtaxonomy_parent\n $style = '&lt;style type=\"text/css\"&gt;#newrecipient_parent { display: none !important; }&lt;/style&gt;';\n\n echo $style . \"\\n\";\n\n}\nadd_action( 'admin_head-post.php', 'dirty_admin_customization' );\nadd_action( 'admin_head-post-new.php', 'dirty_admin_customization' );\n</code></pre>\n" }, { "answer_id": 373890, "author": "jerclarke", "author_id": 175, "author_profile": "https://wordpress.stackexchange.com/users/175", "pm_score": 2, "selected": true, "text": "<p><a href=\"https://www.gazchap.com/posts/enable-checkbox-lists-non-hierarchical-taxonomies-wordpress/\" rel=\"nofollow noreferrer\">This blog post by &quot;Gazchap&quot;</a> deals with exactly the situation you are, and they updated it after publishing to your follow-up problem:</p>\n<blockquote>\n<p>Fortunately, version 4.4 of WordPress introduced a filter – post_edit_category_parent_dropdown_args – that could be used to control the parent terms shown in these meta boxes. It’s designed to let the developer change the terms listed, for example excluding certain categories, or only showing “top level” parent terms and not their descendants. There is no control that is designed to stop the menu being shown at all, but there is one that allows us to trick WordPress into hiding the parent drop-down select.</p>\n<p>Here’s the filter that you need:</p>\n</blockquote>\n<pre class=\"lang-php prettyprint-override\"><code>add_filter( 'post_edit_category_parent_dropdown_args', 'hide_parent_dropdown_select' );\n\nfunction hide_parent_dropdown_select( $args ) {\n if ( 'YOUR_TAXONOMY_SLUG' == $args['taxonomy'] ) {\n $args['echo'] = false;\n }\n return $args;\n}\n</code></pre>\n<blockquote>\n<p>Why does this work? The echo argument is set to true by default, and makes WordPress echo the dropdown select into the meta box. By setting this to false, WordPress instead returns the HTML instead, so it doesn’t get rendered to the browser.</p>\n</blockquote>\n<p>Note that of course <code>YOUR_TAXONOMY_SLUG</code> should be replaced with the slug of your custom taxonomy.</p>\n<p>Anyone attempting this hack should definitely read the blog post in full, it also has some other useful tips.</p>\n" } ]
2018/08/12
[ "https://wordpress.stackexchange.com/questions/311218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148575/" ]
``` <?php $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1; $args = array( 'posts_per_page' => 6, 'offset'=> 0, 'category' => 1, 'paged' => $paged ); $custom_query = new WP_Query( $args ); while($custom_query->have_posts()) : $custom_query->the_post(); ?> ``` My Html code ``` <?php endwhile; ?> <?php previous_posts_link('&laquo; Newer posts'); next_posts_link( 'Older posts &raquo;', $the_query->max_num_pages ); wp_reset_postdata(); ?> ``` What's wrong?
[This blog post by "Gazchap"](https://www.gazchap.com/posts/enable-checkbox-lists-non-hierarchical-taxonomies-wordpress/) deals with exactly the situation you are, and they updated it after publishing to your follow-up problem: > > Fortunately, version 4.4 of WordPress introduced a filter – post\_edit\_category\_parent\_dropdown\_args – that could be used to control the parent terms shown in these meta boxes. It’s designed to let the developer change the terms listed, for example excluding certain categories, or only showing “top level” parent terms and not their descendants. There is no control that is designed to stop the menu being shown at all, but there is one that allows us to trick WordPress into hiding the parent drop-down select. > > > Here’s the filter that you need: > > > ```php add_filter( 'post_edit_category_parent_dropdown_args', 'hide_parent_dropdown_select' ); function hide_parent_dropdown_select( $args ) { if ( 'YOUR_TAXONOMY_SLUG' == $args['taxonomy'] ) { $args['echo'] = false; } return $args; } ``` > > Why does this work? The echo argument is set to true by default, and makes WordPress echo the dropdown select into the meta box. By setting this to false, WordPress instead returns the HTML instead, so it doesn’t get rendered to the browser. > > > Note that of course `YOUR_TAXONOMY_SLUG` should be replaced with the slug of your custom taxonomy. Anyone attempting this hack should definitely read the blog post in full, it also has some other useful tips.
311,220
<p>I have created a <em>custom post type</em> as well as a <em>custom taxonomy</em>, however when I added my first item and selected a category/recipient something weird happened, it automatically created an additional numeric category and changed the selection to that.</p> <p>eg;</p> <p><a href="https://i.stack.imgur.com/y9bXK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/y9bXK.png" alt="enter image description here"></a></p> <p>The <em>only</em> recipients I had entered were "John" and "Michael", I selected <em>John</em> and when the page reloaded it had added "13" and had it selected, and every time I update it it adds a <em>new</em> number and selects this new number as the recipient.</p> <p>It seems the only time it <em>doesn't</em> add a new number is when I <em>don't</em> select <strong>any</strong> recipient.</p> <p><strong>The code:</strong></p> <pre><code>add_action( 'after_setup_theme', 'blm_theme_setup' ); function blm_theme_setup() { //......... // Add our custom post type add_action( 'init', 'blm_letter_post_type' ); //........ } function blm_letter_post_type() { register_post_type( 'letter', array( 'labels' =&gt; array( 'name' =&gt; __( 'Letters' ), 'singular_name' =&gt; __( 'Letter' ), //.......... ), 'public' =&gt; true, 'taxonomies' =&gt; array( 'recipient' ), 'supports' =&gt; array('title', 'editor', 'revisions'), 'has_archive' =&gt; true, 'rewrite' =&gt; array('slug' =&gt; 'letters'), //........ ) ); // Our args for the custom taxonomy below $args = array( 'labels' =&gt; array( 'name' =&gt; __( 'Recipients' ), 'singular_name' =&gt; __( 'Recipient' ), //..... ), 'meta_box_cb' =&gt; 'post_categories_meta_box', ); // Register a custom taxonomy for our letter categories register_taxonomy( 'recipient', 'letter', $args ); // Connect the post type and taxonomy together to be safe register_taxonomy_for_object_type( 'recipient', 'letter' ); } </code></pre> <p><strong>Note:</strong> I tried to only include relevant information to reduce fluff, any non-included arguments were either labels or irrelevant arguments such as <em>description, menu position and menu icon</em>.</p> <p><strong>Edit:</strong> I have just noticed that the "category" it creates matches the term id of the "category" I selected. So if the <code>term id</code> of John is say <code>24</code> and I select that, then it will create a new "category" with that number and select it.</p> <p>What is going on here and how do I fix it?</p>
[ { "answer_id": 311224, "author": "Alex P", "author_id": 134728, "author_profile": "https://wordpress.stackexchange.com/users/134728", "pm_score": 0, "selected": false, "text": "<p>You are using incorrect syntax - try like this:</p>\n\n<pre><code>add_action( 'after_setup_theme', 'blm_theme_setup' );\n\nfunction blm_theme_setup() {\n\n // Add our custom post type\n add_action( 'init', 'blm_letter_post_type' );\n\n}\n\nfunction blm_letter_post_type() {\n\nregister_post_type( 'letter',\n array(\n 'labels' =&gt; array(\n 'name' =&gt; __( 'Letters' ),\n 'singular_name' =&gt; __( 'Letter' ),\n //..........\n ),\n 'public' =&gt; true,\n 'taxonomies' =&gt; array( 'letter' ),\n //........\n )\n);\n\n// Our args for the custom taxonomy below\n$args = array(\n 'labels' =&gt; array(\n 'name' =&gt; __( 'Recipients' ),\n 'singular_name' =&gt; __( 'Recipient' ),\n //.....\n ),\n 'meta_box_cb' =&gt; 'post_categories_meta_box',\n);\n\nregister_taxonomy('recipient', 'letter', $args);\n\n}\n</code></pre>\n" }, { "answer_id": 311290, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 0, "selected": false, "text": "<p>The problem comes from this line in the custom post type definition :</p>\n\n<pre><code> 'taxonomies' =&gt; array( 'letter' ),\n</code></pre>\n\n<p>I don't have searched in code where is the bug but it looks like that creating a taxonomy with the same slug that the custom post type creates the kind of bug.</p>\n" }, { "answer_id": 311298, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 3, "selected": true, "text": "<p>This is a bug in wordpress core when there is a mismatch between the type of taxonomy the taxonomy and the metabox type you use to display it. you must use hierarchical display for hierarchical taxonomy, and \"tag like\" display for non hierarchical taxonomies. \nIf you have to have a mix you will need to write your own metabox. This bug is very old, and it doesn't seem like it will be solved any time soon.</p>\n" } ]
2018/08/12
[ "https://wordpress.stackexchange.com/questions/311220", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/1839/" ]
I have created a *custom post type* as well as a *custom taxonomy*, however when I added my first item and selected a category/recipient something weird happened, it automatically created an additional numeric category and changed the selection to that. eg; [![enter image description here](https://i.stack.imgur.com/y9bXK.png)](https://i.stack.imgur.com/y9bXK.png) The *only* recipients I had entered were "John" and "Michael", I selected *John* and when the page reloaded it had added "13" and had it selected, and every time I update it it adds a *new* number and selects this new number as the recipient. It seems the only time it *doesn't* add a new number is when I *don't* select **any** recipient. **The code:** ``` add_action( 'after_setup_theme', 'blm_theme_setup' ); function blm_theme_setup() { //......... // Add our custom post type add_action( 'init', 'blm_letter_post_type' ); //........ } function blm_letter_post_type() { register_post_type( 'letter', array( 'labels' => array( 'name' => __( 'Letters' ), 'singular_name' => __( 'Letter' ), //.......... ), 'public' => true, 'taxonomies' => array( 'recipient' ), 'supports' => array('title', 'editor', 'revisions'), 'has_archive' => true, 'rewrite' => array('slug' => 'letters'), //........ ) ); // Our args for the custom taxonomy below $args = array( 'labels' => array( 'name' => __( 'Recipients' ), 'singular_name' => __( 'Recipient' ), //..... ), 'meta_box_cb' => 'post_categories_meta_box', ); // Register a custom taxonomy for our letter categories register_taxonomy( 'recipient', 'letter', $args ); // Connect the post type and taxonomy together to be safe register_taxonomy_for_object_type( 'recipient', 'letter' ); } ``` **Note:** I tried to only include relevant information to reduce fluff, any non-included arguments were either labels or irrelevant arguments such as *description, menu position and menu icon*. **Edit:** I have just noticed that the "category" it creates matches the term id of the "category" I selected. So if the `term id` of John is say `24` and I select that, then it will create a new "category" with that number and select it. What is going on here and how do I fix it?
This is a bug in wordpress core when there is a mismatch between the type of taxonomy the taxonomy and the metabox type you use to display it. you must use hierarchical display for hierarchical taxonomy, and "tag like" display for non hierarchical taxonomies. If you have to have a mix you will need to write your own metabox. This bug is very old, and it doesn't seem like it will be solved any time soon.
311,227
<p>I need to order the first three posts by a custom field, and subsequent posts by <code>post_date</code> in one query - for example:</p> <ul> <li>Post 4 (<code>field_order</code>: 1)</li> <li>Post 3 (<code>field_order</code>: 2)</li> <li>Post 2 (<code>field_order</code>: 3)</li> <li>Post 1 (<code>field_order</code>: null) </li> <li>Post 0 (<code>field_order</code>: null)</li> </ul> <p><code>Post 1</code> and <code>Post 0</code> need to be ordered by <code>post_date</code>.</p> <p>I can order by custom field easily enough, but when I add a post without the custom field (Post 1 &amp; 0), it doesn't appear in the query.</p> <p>Below is the query I am currently trying:</p> <pre><code> $args = array( 'post_type' =&gt; 'insights', 'posts_per_page' =&gt; '9', 'meta_query' =&gt; array( array( 'key' =&gt; 'field_order', 'value' =&gt; '0', 'compare' =&gt; '&gt;' ) ), 'orderby' =&gt; array( 'field_order' =&gt; 'ASC', 'post_date' =&gt; 'ASC', ), 'order' =&gt; 'ASC' ); </code></pre>
[ { "answer_id": 311241, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": -1, "selected": false, "text": "<p>I'm not sure if it can be done on <code>WP_Query</code>, but this should work:</p>\n\n<pre><code>global $wpdb;\n$sql = \"SELECT p.* FROM {$wpdb-&gt;posts} p \"\n . \" LEFT JOIN {$wpdb-&gt;postmeta} pm ON p.id=pm.post_id AND pm.meta_key='field_order' \"\n . \" WHERE p.post_type='insights' AND p.post_status='publish' \"\n . \" AND (pm.meta_value &gt; 0 OR pm.meta_value IS NULL) \"\n . \" ORDER BY -pm.meta_value DESC, p.post_date ASC LIMIT 9\";\n$posts = $wpdb-&gt;get_results($sql);\n</code></pre>\n" }, { "answer_id": 311256, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<h2>Multiple <code>meta_query</code> arguments with <code>OR</code></h2>\n<p>You may use the <code>'relation' =&gt; 'OR'</code> argument in <code>meta_query</code> with two sets of <code>field_order</code> arguments: one with <code>meta_value &gt;= '0'</code> and the other one with <code>NOT EXISTS</code> to generate the main query.</p>\n<pre><code> 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n field_order' =&gt; array(\n 'key' =&gt; 'field_order',\n 'value' =&gt; '0',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'NUMERIC'\n ), \n 'field_order_withnulls' =&gt; array(\n 'key' =&gt; 'field_order',\n 'compare' =&gt; 'NOT EXISTS',\n 'type' =&gt; 'NUMERIC'\n )\n )\n</code></pre>\n<h2>Proper Order by</h2>\n<p>We can use <code>'field_order_withnulls' =&gt; 'ASC'</code>, however, because of the LEFT JOIN, there will be rows with <code>null</code> <code>field_order</code> values &amp; those will come before numeric <code>field_order</code> values in <code>ASC</code> orderby.</p>\n<p>To fix that, we will use the <code>ORDER BY -field_order DESC</code> trick as described <a href=\"https://stackoverflow.com/a/8174026/854549\">here</a>.</p>\n<p>This will correct the ordering by inverting <code>DESC</code> to <code>ASC</code>, but keeping the rows with <code>null</code> values after the numeric values.</p>\n<h2>Implementing the <code>-</code> (inverse) operator in <code>orderby</code></h2>\n<p>The problem is, WordPress doesn't provide any direct way of setting the <code>-</code> (inverse) operator in <code>orderby</code>. So we will introduce a custom <code>WP_Query</code> attribute named <code>_inverse_order</code> and then use the <code>posts_orderby</code> filter to implement it.</p>\n<h2>Sample CODE:</h2>\n<pre><code> // posts_orderby filter callback function\n // place this function in theme's functions.php file or in a custom plugin\n function wpse311227_inverse_orderby( $orderby, $query ) {\n remove_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 );\n $idx = (int) $query-&gt;get( '_inverse_order' ) - 1;\n if( $idx &gt;= 0 ) {\n $orders = preg_split( &quot;/(?&lt;=ASC|DESC),[\\s]*/i&quot;, $orderby );\n if( $idx &lt; count( $orders ) ) {\n $orders[$idx] = '-' . $orders[$idx];\n }\n return implode( $orders, ', ' );\n }\n\n return $orderby;\n }\n\n\n // adding the posts_orderby filter to implement the custom '_inverse_order' attribute\n // this should be placed just before the WP_Query call\n add_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 );\n $args = array(\n 'post_type' =&gt; 'insights',\n 'posts_per_page' =&gt; '9',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n field_order' =&gt; array(\n 'key' =&gt; 'field_order',\n 'value' =&gt; '0',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'NUMERIC'\n ), \n 'field_order_withnulls' =&gt; array(\n 'key' =&gt; 'field_order',\n 'compare' =&gt; 'NOT EXISTS',\n 'type' =&gt; 'NUMERIC'\n )\n ),\n 'orderby' =&gt; array(\n 'field_order_withnulls' =&gt; 'DESC',\n 'post_date' =&gt; 'ASC'\n ),\n // this custom attribute is implemented in wpse311227_inverse_orderby() function\n // to correct the ordering by placing a '-' operator\n // value of _inverse_order attribute is the position of the\n // orderby attribute to be be inversed,\n // (position starts with 1)\n // in this case, since: 'field_order_withnulls' =&gt; 'DESC'\n // is in position 1 of 'orderby' attribute array, so:\n '_inverse_order' =&gt; 1\n );\n $query = new WP_Query( $args );\n</code></pre>\n<p>This will produce all posts with <code>field_order &gt; 0</code> and the posts that don't have <code>field_order</code> meta data with the expected order.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> You'll need to pass a non-empty <code>value</code> in <code>meta_query</code> for a <code>NOT EXISTS</code> check if the WordPress version is below 3.9. Check this <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">note from codex</a>:</p>\n<blockquote>\n<p>Due to bug #23268, value is required for NOT EXISTS comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or NULL will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using NOT EXISTS.</p>\n</blockquote>\n</blockquote>\n<hr />\n<blockquote>\n<p><em><strong>Warning:</strong></em> This <code>WP_Query</code> will use two <code>LEFT JOIN</code>, which is <em>not very efficient</em>. Although, for even a few thousand posts, this is tolerable. I've tested with 15,000+ posts &amp; the query takes approximately 0.3 second on a average. However, if you have Millions or even hundreds of thousands of posts, then you'll have to optimize the query or find a more efficient method to achieve the same result.</p>\n</blockquote>\n" } ]
2018/08/12
[ "https://wordpress.stackexchange.com/questions/311227", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148581/" ]
I need to order the first three posts by a custom field, and subsequent posts by `post_date` in one query - for example: * Post 4 (`field_order`: 1) * Post 3 (`field_order`: 2) * Post 2 (`field_order`: 3) * Post 1 (`field_order`: null) * Post 0 (`field_order`: null) `Post 1` and `Post 0` need to be ordered by `post_date`. I can order by custom field easily enough, but when I add a post without the custom field (Post 1 & 0), it doesn't appear in the query. Below is the query I am currently trying: ``` $args = array( 'post_type' => 'insights', 'posts_per_page' => '9', 'meta_query' => array( array( 'key' => 'field_order', 'value' => '0', 'compare' => '>' ) ), 'orderby' => array( 'field_order' => 'ASC', 'post_date' => 'ASC', ), 'order' => 'ASC' ); ```
Multiple `meta_query` arguments with `OR` ----------------------------------------- You may use the `'relation' => 'OR'` argument in `meta_query` with two sets of `field_order` arguments: one with `meta_value >= '0'` and the other one with `NOT EXISTS` to generate the main query. ``` 'meta_query' => array( 'relation' => 'OR', field_order' => array( 'key' => 'field_order', 'value' => '0', 'compare' => '>=', 'type' => 'NUMERIC' ), 'field_order_withnulls' => array( 'key' => 'field_order', 'compare' => 'NOT EXISTS', 'type' => 'NUMERIC' ) ) ``` Proper Order by --------------- We can use `'field_order_withnulls' => 'ASC'`, however, because of the LEFT JOIN, there will be rows with `null` `field_order` values & those will come before numeric `field_order` values in `ASC` orderby. To fix that, we will use the `ORDER BY -field_order DESC` trick as described [here](https://stackoverflow.com/a/8174026/854549). This will correct the ordering by inverting `DESC` to `ASC`, but keeping the rows with `null` values after the numeric values. Implementing the `-` (inverse) operator in `orderby` ---------------------------------------------------- The problem is, WordPress doesn't provide any direct way of setting the `-` (inverse) operator in `orderby`. So we will introduce a custom `WP_Query` attribute named `_inverse_order` and then use the `posts_orderby` filter to implement it. Sample CODE: ------------ ``` // posts_orderby filter callback function // place this function in theme's functions.php file or in a custom plugin function wpse311227_inverse_orderby( $orderby, $query ) { remove_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 ); $idx = (int) $query->get( '_inverse_order' ) - 1; if( $idx >= 0 ) { $orders = preg_split( "/(?<=ASC|DESC),[\s]*/i", $orderby ); if( $idx < count( $orders ) ) { $orders[$idx] = '-' . $orders[$idx]; } return implode( $orders, ', ' ); } return $orderby; } // adding the posts_orderby filter to implement the custom '_inverse_order' attribute // this should be placed just before the WP_Query call add_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 ); $args = array( 'post_type' => 'insights', 'posts_per_page' => '9', 'meta_query' => array( 'relation' => 'OR', field_order' => array( 'key' => 'field_order', 'value' => '0', 'compare' => '>=', 'type' => 'NUMERIC' ), 'field_order_withnulls' => array( 'key' => 'field_order', 'compare' => 'NOT EXISTS', 'type' => 'NUMERIC' ) ), 'orderby' => array( 'field_order_withnulls' => 'DESC', 'post_date' => 'ASC' ), // this custom attribute is implemented in wpse311227_inverse_orderby() function // to correct the ordering by placing a '-' operator // value of _inverse_order attribute is the position of the // orderby attribute to be be inversed, // (position starts with 1) // in this case, since: 'field_order_withnulls' => 'DESC' // is in position 1 of 'orderby' attribute array, so: '_inverse_order' => 1 ); $query = new WP_Query( $args ); ``` This will produce all posts with `field_order > 0` and the posts that don't have `field_order` meta data with the expected order. > > ***Note:*** You'll need to pass a non-empty `value` in `meta_query` for a `NOT EXISTS` check if the WordPress version is below 3.9. Check this [note from codex](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters): > > > > > > > Due to bug #23268, value is required for NOT EXISTS comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or NULL will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using NOT EXISTS. > > > > > > > > > --- > > ***Warning:*** This `WP_Query` will use two `LEFT JOIN`, which is *not very efficient*. Although, for even a few thousand posts, this is tolerable. I've tested with 15,000+ posts & the query takes approximately 0.3 second on a average. However, if you have Millions or even hundreds of thousands of posts, then you'll have to optimize the query or find a more efficient method to achieve the same result. > > >
311,244
<p>I am getting the error: Error establishing a database connection. I go to localhost, and it brings up the wampserver homepage (I am using wamp obviously) I click on my project which is called wordpress-first and it just says this site cant be reached. if I go to localhost/wordpress-first it gives me the error establishing a database connection. I documented every step I took because I had a feeling I was going to have an issue. So here is the steps that I took installing WAMP, wordpress and filezilla.<br></p> <p><h2><strong>downloading wamp</strong></h2> <br> • Download wampserver from wampserver.com/en/<br> • Following this video: <a href="https://www.youtube.com/watch?v=StfQetPz2og&amp;t=9s" rel="nofollow noreferrer">https://www.youtube.com/watch?v=StfQetPz2og&amp;t=9s</a><br></p> <p>• Downloaded wampserver.3.1.3.exe and the read me and pdf of how to install.<br> • Moved the exe. File into my c drive<br> • Moved readables into a folder in documents<br> • Installed the exe. For wamp in c drive<br> • I changed the default browser from IE to chrome upon setup<br> • Notepad was chosen as the text editor<br> Mysql5.7.21 was installed<br> <br> Once installed I clicked on the wampserver desktop icon. The command prompt opened and then closed immediately. I went to the bottom right of my screen and clicked on the W icon in the notifications section where the volume control is. I clicked into the wamp icon. I clicked start and services and it started PHP Apache and all that. I went to localhost and opened the WAMP homepage. <br> • Click on phpMyAdmin to create a database<br> As a default the username is root and there is not password. Just leave it blank to begin with.<br> • Click on databases<br> • Go to create database. Name it whatever you want. I named it wordpress_first.<br> • I clicked create and a prompt appeared telling me the database has been created.<br> <h2><strong>downloading wordpress</strong></h2><br> • I downloaded the wordpress 4.9.8 zip file.<br> • I extracted the files in my downloads folder.<br> • Then move your wordpress folder in the wamp folder so in c / wamp / www<br> • Next, I renamed the file from wordpress 4.9.8 to wordpress-first, the name of my database<br> • I went into the wordpress-first folder and found the wp-config-sample.php file. I made a copy of this file in the same folder and renamed it as wp-config.php<br> • I opened this file in atom<br> • There are functions in this file that look like this define(‘DB_NAME,”database-name-here”);<br> • I changed the second parameter in database name to wordpress-first<br> • I changed the second parameter in user name to root<br> • I changed the second parameter in password to “” for no password<br> • You can now see the new-folder on the WAMPSERVER homepage in localhost/ and it is called wordrpess-first<br> I clicked on the folder in localhost and got the error This site can’t be reached wordpress-first’s server IP address could not be found. If I type in localhost/wordpress-first it gives the error Error establishing a database connection<br> • Went to this site for help <a href="https://www.wpbeginner.com/wp-tutorials/how-to-fix-the-error-establishing-a-database-connection-in-wordpress/" rel="nofollow noreferrer">https://www.wpbeginner.com/wp-tutorials/how-to-fix-the-error-establishing-a-database-connection-in-wordpress/</a><br> • Theres a video that said to go into your wp-config file and after the line that<code>s all stop editing! Happy blogging. – add this line of code: define(‘WP_ALLOW_REPAIR’,true );&lt;br&gt; • This didn</code>t work, another thing they said was that I need an FTP client and that WAMP doesn’t come packaged with this. So I went to this site.<br> <a href="https://www.betterhostreview.com/setup-filezilla-ftp-server-wamp.html" rel="nofollow noreferrer">https://www.betterhostreview.com/setup-filezilla-ftp-server-wamp.html</a> where they have a tutorial on downloading filezilla, an FTP client for windows.<br></p> <h2><strong>Filezilla</strong></h2> <ul> <li>During the filezilla installation process:</li> </ul> <p>• There was a prompt for the port number and I clicked on the default one that popped up which was 14147.<br> It then said error: Connection to server lost… You appear to be behind a NAT router. Please configure the passive mode settings and forward a range of ports in your router. Warning: FTP over TLS is not enabled. users cannot securely log in.<br><br> I don`t know what to do at this point so if anyone has any suggestions I would appreciate it thanks!</p>
[ { "answer_id": 311241, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": -1, "selected": false, "text": "<p>I'm not sure if it can be done on <code>WP_Query</code>, but this should work:</p>\n\n<pre><code>global $wpdb;\n$sql = \"SELECT p.* FROM {$wpdb-&gt;posts} p \"\n . \" LEFT JOIN {$wpdb-&gt;postmeta} pm ON p.id=pm.post_id AND pm.meta_key='field_order' \"\n . \" WHERE p.post_type='insights' AND p.post_status='publish' \"\n . \" AND (pm.meta_value &gt; 0 OR pm.meta_value IS NULL) \"\n . \" ORDER BY -pm.meta_value DESC, p.post_date ASC LIMIT 9\";\n$posts = $wpdb-&gt;get_results($sql);\n</code></pre>\n" }, { "answer_id": 311256, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<h2>Multiple <code>meta_query</code> arguments with <code>OR</code></h2>\n<p>You may use the <code>'relation' =&gt; 'OR'</code> argument in <code>meta_query</code> with two sets of <code>field_order</code> arguments: one with <code>meta_value &gt;= '0'</code> and the other one with <code>NOT EXISTS</code> to generate the main query.</p>\n<pre><code> 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n field_order' =&gt; array(\n 'key' =&gt; 'field_order',\n 'value' =&gt; '0',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'NUMERIC'\n ), \n 'field_order_withnulls' =&gt; array(\n 'key' =&gt; 'field_order',\n 'compare' =&gt; 'NOT EXISTS',\n 'type' =&gt; 'NUMERIC'\n )\n )\n</code></pre>\n<h2>Proper Order by</h2>\n<p>We can use <code>'field_order_withnulls' =&gt; 'ASC'</code>, however, because of the LEFT JOIN, there will be rows with <code>null</code> <code>field_order</code> values &amp; those will come before numeric <code>field_order</code> values in <code>ASC</code> orderby.</p>\n<p>To fix that, we will use the <code>ORDER BY -field_order DESC</code> trick as described <a href=\"https://stackoverflow.com/a/8174026/854549\">here</a>.</p>\n<p>This will correct the ordering by inverting <code>DESC</code> to <code>ASC</code>, but keeping the rows with <code>null</code> values after the numeric values.</p>\n<h2>Implementing the <code>-</code> (inverse) operator in <code>orderby</code></h2>\n<p>The problem is, WordPress doesn't provide any direct way of setting the <code>-</code> (inverse) operator in <code>orderby</code>. So we will introduce a custom <code>WP_Query</code> attribute named <code>_inverse_order</code> and then use the <code>posts_orderby</code> filter to implement it.</p>\n<h2>Sample CODE:</h2>\n<pre><code> // posts_orderby filter callback function\n // place this function in theme's functions.php file or in a custom plugin\n function wpse311227_inverse_orderby( $orderby, $query ) {\n remove_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 );\n $idx = (int) $query-&gt;get( '_inverse_order' ) - 1;\n if( $idx &gt;= 0 ) {\n $orders = preg_split( &quot;/(?&lt;=ASC|DESC),[\\s]*/i&quot;, $orderby );\n if( $idx &lt; count( $orders ) ) {\n $orders[$idx] = '-' . $orders[$idx];\n }\n return implode( $orders, ', ' );\n }\n\n return $orderby;\n }\n\n\n // adding the posts_orderby filter to implement the custom '_inverse_order' attribute\n // this should be placed just before the WP_Query call\n add_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 );\n $args = array(\n 'post_type' =&gt; 'insights',\n 'posts_per_page' =&gt; '9',\n 'meta_query' =&gt; array(\n 'relation' =&gt; 'OR',\n field_order' =&gt; array(\n 'key' =&gt; 'field_order',\n 'value' =&gt; '0',\n 'compare' =&gt; '&gt;=',\n 'type' =&gt; 'NUMERIC'\n ), \n 'field_order_withnulls' =&gt; array(\n 'key' =&gt; 'field_order',\n 'compare' =&gt; 'NOT EXISTS',\n 'type' =&gt; 'NUMERIC'\n )\n ),\n 'orderby' =&gt; array(\n 'field_order_withnulls' =&gt; 'DESC',\n 'post_date' =&gt; 'ASC'\n ),\n // this custom attribute is implemented in wpse311227_inverse_orderby() function\n // to correct the ordering by placing a '-' operator\n // value of _inverse_order attribute is the position of the\n // orderby attribute to be be inversed,\n // (position starts with 1)\n // in this case, since: 'field_order_withnulls' =&gt; 'DESC'\n // is in position 1 of 'orderby' attribute array, so:\n '_inverse_order' =&gt; 1\n );\n $query = new WP_Query( $args );\n</code></pre>\n<p>This will produce all posts with <code>field_order &gt; 0</code> and the posts that don't have <code>field_order</code> meta data with the expected order.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> You'll need to pass a non-empty <code>value</code> in <code>meta_query</code> for a <code>NOT EXISTS</code> check if the WordPress version is below 3.9. Check this <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">note from codex</a>:</p>\n<blockquote>\n<p>Due to bug #23268, value is required for NOT EXISTS comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or NULL will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using NOT EXISTS.</p>\n</blockquote>\n</blockquote>\n<hr />\n<blockquote>\n<p><em><strong>Warning:</strong></em> This <code>WP_Query</code> will use two <code>LEFT JOIN</code>, which is <em>not very efficient</em>. Although, for even a few thousand posts, this is tolerable. I've tested with 15,000+ posts &amp; the query takes approximately 0.3 second on a average. However, if you have Millions or even hundreds of thousands of posts, then you'll have to optimize the query or find a more efficient method to achieve the same result.</p>\n</blockquote>\n" } ]
2018/08/12
[ "https://wordpress.stackexchange.com/questions/311244", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148592/" ]
I am getting the error: Error establishing a database connection. I go to localhost, and it brings up the wampserver homepage (I am using wamp obviously) I click on my project which is called wordpress-first and it just says this site cant be reached. if I go to localhost/wordpress-first it gives me the error establishing a database connection. I documented every step I took because I had a feeling I was going to have an issue. So here is the steps that I took installing WAMP, wordpress and filezilla. **downloading wamp** -------------------- • Download wampserver from wampserver.com/en/ • Following this video: <https://www.youtube.com/watch?v=StfQetPz2og&t=9s> • Downloaded wampserver.3.1.3.exe and the read me and pdf of how to install. • Moved the exe. File into my c drive • Moved readables into a folder in documents • Installed the exe. For wamp in c drive • I changed the default browser from IE to chrome upon setup • Notepad was chosen as the text editor Mysql5.7.21 was installed Once installed I clicked on the wampserver desktop icon. The command prompt opened and then closed immediately. I went to the bottom right of my screen and clicked on the W icon in the notifications section where the volume control is. I clicked into the wamp icon. I clicked start and services and it started PHP Apache and all that. I went to localhost and opened the WAMP homepage. • Click on phpMyAdmin to create a database As a default the username is root and there is not password. Just leave it blank to begin with. • Click on databases • Go to create database. Name it whatever you want. I named it wordpress\_first. • I clicked create and a prompt appeared telling me the database has been created. **downloading wordpress** ------------------------- • I downloaded the wordpress 4.9.8 zip file. • I extracted the files in my downloads folder. • Then move your wordpress folder in the wamp folder so in c / wamp / www • Next, I renamed the file from wordpress 4.9.8 to wordpress-first, the name of my database • I went into the wordpress-first folder and found the wp-config-sample.php file. I made a copy of this file in the same folder and renamed it as wp-config.php • I opened this file in atom • There are functions in this file that look like this define(‘DB\_NAME,”database-name-here”); • I changed the second parameter in database name to wordpress-first • I changed the second parameter in user name to root • I changed the second parameter in password to “” for no password • You can now see the new-folder on the WAMPSERVER homepage in localhost/ and it is called wordrpess-first I clicked on the folder in localhost and got the error This site can’t be reached wordpress-first’s server IP address could not be found. If I type in localhost/wordpress-first it gives the error Error establishing a database connection • Went to this site for help <https://www.wpbeginner.com/wp-tutorials/how-to-fix-the-error-establishing-a-database-connection-in-wordpress/> • Theres a video that said to go into your wp-config file and after the line that`s all stop editing! Happy blogging. – add this line of code: define(‘WP_ALLOW_REPAIR’,true );<br> • This didn`t work, another thing they said was that I need an FTP client and that WAMP doesn’t come packaged with this. So I went to this site. <https://www.betterhostreview.com/setup-filezilla-ftp-server-wamp.html> where they have a tutorial on downloading filezilla, an FTP client for windows. **Filezilla** ------------- * During the filezilla installation process: • There was a prompt for the port number and I clicked on the default one that popped up which was 14147. It then said error: Connection to server lost… You appear to be behind a NAT router. Please configure the passive mode settings and forward a range of ports in your router. Warning: FTP over TLS is not enabled. users cannot securely log in. I don`t know what to do at this point so if anyone has any suggestions I would appreciate it thanks!
Multiple `meta_query` arguments with `OR` ----------------------------------------- You may use the `'relation' => 'OR'` argument in `meta_query` with two sets of `field_order` arguments: one with `meta_value >= '0'` and the other one with `NOT EXISTS` to generate the main query. ``` 'meta_query' => array( 'relation' => 'OR', field_order' => array( 'key' => 'field_order', 'value' => '0', 'compare' => '>=', 'type' => 'NUMERIC' ), 'field_order_withnulls' => array( 'key' => 'field_order', 'compare' => 'NOT EXISTS', 'type' => 'NUMERIC' ) ) ``` Proper Order by --------------- We can use `'field_order_withnulls' => 'ASC'`, however, because of the LEFT JOIN, there will be rows with `null` `field_order` values & those will come before numeric `field_order` values in `ASC` orderby. To fix that, we will use the `ORDER BY -field_order DESC` trick as described [here](https://stackoverflow.com/a/8174026/854549). This will correct the ordering by inverting `DESC` to `ASC`, but keeping the rows with `null` values after the numeric values. Implementing the `-` (inverse) operator in `orderby` ---------------------------------------------------- The problem is, WordPress doesn't provide any direct way of setting the `-` (inverse) operator in `orderby`. So we will introduce a custom `WP_Query` attribute named `_inverse_order` and then use the `posts_orderby` filter to implement it. Sample CODE: ------------ ``` // posts_orderby filter callback function // place this function in theme's functions.php file or in a custom plugin function wpse311227_inverse_orderby( $orderby, $query ) { remove_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 ); $idx = (int) $query->get( '_inverse_order' ) - 1; if( $idx >= 0 ) { $orders = preg_split( "/(?<=ASC|DESC),[\s]*/i", $orderby ); if( $idx < count( $orders ) ) { $orders[$idx] = '-' . $orders[$idx]; } return implode( $orders, ', ' ); } return $orderby; } // adding the posts_orderby filter to implement the custom '_inverse_order' attribute // this should be placed just before the WP_Query call add_filter( 'posts_orderby', 'wpse311227_inverse_orderby', 10, 2 ); $args = array( 'post_type' => 'insights', 'posts_per_page' => '9', 'meta_query' => array( 'relation' => 'OR', field_order' => array( 'key' => 'field_order', 'value' => '0', 'compare' => '>=', 'type' => 'NUMERIC' ), 'field_order_withnulls' => array( 'key' => 'field_order', 'compare' => 'NOT EXISTS', 'type' => 'NUMERIC' ) ), 'orderby' => array( 'field_order_withnulls' => 'DESC', 'post_date' => 'ASC' ), // this custom attribute is implemented in wpse311227_inverse_orderby() function // to correct the ordering by placing a '-' operator // value of _inverse_order attribute is the position of the // orderby attribute to be be inversed, // (position starts with 1) // in this case, since: 'field_order_withnulls' => 'DESC' // is in position 1 of 'orderby' attribute array, so: '_inverse_order' => 1 ); $query = new WP_Query( $args ); ``` This will produce all posts with `field_order > 0` and the posts that don't have `field_order` meta data with the expected order. > > ***Note:*** You'll need to pass a non-empty `value` in `meta_query` for a `NOT EXISTS` check if the WordPress version is below 3.9. Check this [note from codex](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters): > > > > > > > Due to bug #23268, value is required for NOT EXISTS comparisons to work correctly prior to 3.9. You must supply some string for the value parameter. An empty string or NULL will NOT work. However, any other string will do the trick and will NOT show up in your SQL when using NOT EXISTS. > > > > > > > > > --- > > ***Warning:*** This `WP_Query` will use two `LEFT JOIN`, which is *not very efficient*. Although, for even a few thousand posts, this is tolerable. I've tested with 15,000+ posts & the query takes approximately 0.3 second on a average. However, if you have Millions or even hundreds of thousands of posts, then you'll have to optimize the query or find a more efficient method to achieve the same result. > > >
311,265
<p>Some plugins place various links under their name on the plugins page. To display these each action links for a specific plugin in a seperate line I followed <a href="https://wordpress.stackexchange.com/a/241011/25187">this</a> and <a href="https://wordpress.stackexchange.com/a/241071/25187">this</a> answers, but my code doesn't work. What I did wrong?</p> <p>I use WordPress 4.9.8 with a child Twenty Seventeen theme.</p> <pre><code>add_action( 'admin_enqueue_scripts', 'wpse_239302_hide_action_links' ); function wpse_239302_hide_action_links() { global $pagenow; if ( $pagenow == 'plugins.php' ) { ?&gt; &lt;style type="text/css"&gt; tr.active[data-slug="super-socializer"] .row-actions.visible span .1, tr.active[data-slug="super-socializer"] .row-actions.visible span .2 { display: block; } &lt;/style&gt; &lt;?php } } </code></pre>
[ { "answer_id": 311292, "author": "Kaperto", "author_id": 147795, "author_profile": "https://wordpress.stackexchange.com/users/147795", "pm_score": 1, "selected": false, "text": "<p>you can customise these links with this filter :<br>\n<a href=\"https://developer.wordpress.org/reference/hooks/plugin_action_links_plugin_file/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/hooks/plugin_action_links_plugin_file/</a></p>\n\n<p>try that : </p>\n\n<pre><code>const PLUGIN_SLUG = \"super-socializer/super_socializer.php\";\n\n\nadd_filter(\"plugin_action_links_\" . PLUGIN_SLUG, function (array $actions, string $plugin_file, array $plugin_data, string $context) {\n\n unset($actions[1]); // remove link \"Add-Ons\"\n unset($actions[2]); // remove link \"Support Documentation\"\n\n return $actions;\n\n}, 10, 4);\n</code></pre>\n" }, { "answer_id": 311422, "author": "Iurie", "author_id": 25187, "author_profile": "https://wordpress.stackexchange.com/users/25187", "pm_score": 1, "selected": true, "text": "<p>I found a better solution by moving links in discussion from the first column to the second column of plugin admin page with these two functions:</p>\n\n<pre><code>/** Remove action links from the Super Socializer plugin first column **/\nconst PLUGIN_SLUG = \"super-socializer/super_socializer.php\";\nadd_filter(\"plugin_action_links_\" . PLUGIN_SLUG, function ($actions, $plugin_file, $plugin_data, $context) {\n\n unset($actions[1]); // remove link \"Add-Ons\"\n unset($actions[2]); // remove link \"Support Documentation\"\n\n return $actions;\n\n}, 10, 4);\n\n/** Add action links to the Super Socializer plugin second column **/\nadd_filter( 'plugin_row_meta', 'custom_plugin_row_meta', 10, 2 );\nfunction custom_plugin_row_meta( $links, $file ) {\n\n if( strpos( $file, 'super_socializer.php' ) !== false ) {\n $new_links = array(\n 'addons' =&gt; '&lt;a href=\"' . esc_url( 'https://www.heateor.com/add-ons' ) . '\" target=\"_blank\" aria-label=\"' . \n esc_attr__( 'Add-Ons', 'domain' ) . '\"&gt;' . esc_html__( 'Add-Ons', 'domain' ) . '&lt;/a&gt;', // add link \"Add-Ons\"\n 'support' =&gt; '&lt;a href=\"' . esc_url( 'https://www.heateor.com/add-ons' ) . '\" target=\"_blank\" aria-label=\"' . \n esc_attr__( 'Support Documentation', 'domain' ) . '\"&gt;' . esc_html__( 'Support Documentation', 'domain' ) . '&lt;/a&gt;' // add link \"Support Documentation\"\n );\n\n $links = array_merge( $links, $new_links );\n }\n\n return $links;\n}\n</code></pre>\n" } ]
2018/08/13
[ "https://wordpress.stackexchange.com/questions/311265", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/25187/" ]
Some plugins place various links under their name on the plugins page. To display these each action links for a specific plugin in a seperate line I followed [this](https://wordpress.stackexchange.com/a/241011/25187) and [this](https://wordpress.stackexchange.com/a/241071/25187) answers, but my code doesn't work. What I did wrong? I use WordPress 4.9.8 with a child Twenty Seventeen theme. ``` add_action( 'admin_enqueue_scripts', 'wpse_239302_hide_action_links' ); function wpse_239302_hide_action_links() { global $pagenow; if ( $pagenow == 'plugins.php' ) { ?> <style type="text/css"> tr.active[data-slug="super-socializer"] .row-actions.visible span .1, tr.active[data-slug="super-socializer"] .row-actions.visible span .2 { display: block; } </style> <?php } } ```
I found a better solution by moving links in discussion from the first column to the second column of plugin admin page with these two functions: ``` /** Remove action links from the Super Socializer plugin first column **/ const PLUGIN_SLUG = "super-socializer/super_socializer.php"; add_filter("plugin_action_links_" . PLUGIN_SLUG, function ($actions, $plugin_file, $plugin_data, $context) { unset($actions[1]); // remove link "Add-Ons" unset($actions[2]); // remove link "Support Documentation" return $actions; }, 10, 4); /** Add action links to the Super Socializer plugin second column **/ add_filter( 'plugin_row_meta', 'custom_plugin_row_meta', 10, 2 ); function custom_plugin_row_meta( $links, $file ) { if( strpos( $file, 'super_socializer.php' ) !== false ) { $new_links = array( 'addons' => '<a href="' . esc_url( 'https://www.heateor.com/add-ons' ) . '" target="_blank" aria-label="' . esc_attr__( 'Add-Ons', 'domain' ) . '">' . esc_html__( 'Add-Ons', 'domain' ) . '</a>', // add link "Add-Ons" 'support' => '<a href="' . esc_url( 'https://www.heateor.com/add-ons' ) . '" target="_blank" aria-label="' . esc_attr__( 'Support Documentation', 'domain' ) . '">' . esc_html__( 'Support Documentation', 'domain' ) . '</a>' // add link "Support Documentation" ); $links = array_merge( $links, $new_links ); } return $links; } ```
311,282
<p>How do I display all posts from multisite to the main site? Please help me. thanks.</p>
[ { "answer_id": 311319, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 0, "selected": false, "text": "<p>That's exactly what my \"Multisite Post Reader\" plugin does. Grabs posts from any/all multisites. Has tons of optional parameters. It basically does the loop through the sites, similar to the other answer mentioned in the comments. </p>\n\n<p>You are welcome to try it out, or grab the code for your own use. See it here: <a href=\"https://wordpress.org/plugins/multisite-post-reader/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/multisite-post-reader/</a> . </p>\n\n<p>I have similar plugins I use for displaying all images from all sites - I use it to monitor images to ensure the subsites meet my content requirements.</p>\n" }, { "answer_id": 314483, "author": "Misha Rudrastyh", "author_id": 85985, "author_profile": "https://wordpress.stackexchange.com/users/85985", "pm_score": 1, "selected": false, "text": "<p>So, actually there is two ways to do it.</p>\n\n<p>The first one is using <code>switch_to_blog()</code> and <code>restore_current_blog()</code> functions, example:</p>\n\n<pre><code>// in this variable you can pass all the blog IDs you would like to display posts from\n$blog_ids = array( 1, 3 );\n\nforeach( $blog_ids as $id ) {\n\n switch_to_blog( $id );\n\n $args = array(); // any WP_Query args should be here\n $query = new WP_Query( $args );\n\n if( $query-&gt;have_posts() ) : \n while( $query-&gt;have_posts() : $query-&gt;the_post();\n\n // your post template goes here\n\n endwhile;\n endif;\n wp_reset_postdata();\n\n restore_current_blog();\n\n}\n</code></pre>\n\n<p>But if you do not want to switch between the blogs each time, then I recommend my – paid and restricted access – plugin which indexes all the posts from all your website into another database table and then you can use WP_Query analogue to get all the posts within just one loop. Example of this plugin <a href=\"https://rudrastyh.com/plugins/get-posts-from-all-blogs-in-multisite-network\" rel=\"nofollow noreferrer\">https://rudrastyh.com/plugins/get-posts-from-all-blogs-in-multisite-network</a></p>\n" } ]
2018/08/13
[ "https://wordpress.stackexchange.com/questions/311282", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148609/" ]
How do I display all posts from multisite to the main site? Please help me. thanks.
So, actually there is two ways to do it. The first one is using `switch_to_blog()` and `restore_current_blog()` functions, example: ``` // in this variable you can pass all the blog IDs you would like to display posts from $blog_ids = array( 1, 3 ); foreach( $blog_ids as $id ) { switch_to_blog( $id ); $args = array(); // any WP_Query args should be here $query = new WP_Query( $args ); if( $query->have_posts() ) : while( $query->have_posts() : $query->the_post(); // your post template goes here endwhile; endif; wp_reset_postdata(); restore_current_blog(); } ``` But if you do not want to switch between the blogs each time, then I recommend my – paid and restricted access – plugin which indexes all the posts from all your website into another database table and then you can use WP\_Query analogue to get all the posts within just one loop. Example of this plugin <https://rudrastyh.com/plugins/get-posts-from-all-blogs-in-multisite-network>
311,318
<p>I am using plugin "wpdevart facebook comment" for posting comments at the end of every post. They are displaying good But now I want to shift those comments little below of pagination and ads Or at the end of the page but comments should be of the relevant post. attached is the screenshot: <a href="https://i.stack.imgur.com/riA78.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/riA78.png" alt="enter image description here"></a></p> <p>And for this I have added the plugin shortcode in the Single.php</p> <pre><code>while ( have_posts() ) : the_post(); $bimber_post_settings = bimber_get_post_settings(); bimber_set_template_part_data( $bimber_post_settings ); /* * Include the post format-specific template for the content. If you want to * use this in a child theme, then include a file called called content-single-classic-___.php * (where ___ is the post format) and that will be used instead. */ get_template_part( 'template-parts/content-single-classic', get_post_format() ); comments_template(); //facebook comments echo do_shortcode('[wpdevart_facebook_comment facebook_app_id="12345678910111213" curent_url="http://developers.facebook.com/docs/plugins/comments/" order_type="social" title_text="Facebook Comment" title_text_color="#000000" title_text_font_size="16" title_text_font_famely="Arial" title_text_position="left" width="100%" bg_color="#000000" animation_effect="none" count_of_comments="10" ]'); bimber_reset_template_part_data(); endwhile; ?&gt; </code></pre> <p>But It displays all comments of all posts and pages.</p>
[ { "answer_id": 311320, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": true, "text": "<p>From the plugin's user manual.</p>\n\n<blockquote>\n <p><strong>Curent_url</strong> - Type the page URL from where you need to show Facebook\n comments</p>\n</blockquote>\n\n<p>So you will have to change the current URL which is (<a href=\"http://developers.facebook.com/docs/plugins/comments/\" rel=\"nofollow noreferrer\">http://developers.facebook.com/docs/plugins/comments/</a>) to your real current URL.</p>\n\n<pre><code>global $wp;\n$current_url = home_url( add_query_arg( array(), $wp-&gt;request ) );\necho do_shortcode('[wpdevart_facebook_comment facebook_app_id=\"12345678910111213\" curent_url=\"'.$current_url.'\n \" order_type=\"social\" title_text=\"Facebook Comment\" title_text_color=\"#000000\" title_text_font_size=\"16\" title_text_font_famely=\"Arial\" title_text_position=\"left\" width=\"100%\" bg_color=\"#000000\" animation_effect=\"none\" count_of_comments=\"10\" ]');\n</code></pre>\n" }, { "answer_id": 311367, "author": "WordPressGuru", "author_id": 148679, "author_profile": "https://wordpress.stackexchange.com/users/148679", "pm_score": 1, "selected": false, "text": "<p>Well, you can move comments div out of the \"single.php\" wrapper.</p>\n\n<p>Changle location of this shortcode <code>echo do_shortcode('[wpdevart_facebook_comment facebook_app_id=\"12345678910111213\" curent_url=\"http://developers.facebook.com/docs/plugins/comments/\" order_type=\"social\" title_text=\"Facebook Comment\" title_text_color=\"#000000\" title_text_font_size=\"16\" title_text_font_famely=\"Arial\" title_text_position=\"left\" width=\"100%\" bg_color=\"#000000\" animation_effect=\"none\" count_of_comments=\"10\" ]');</code></p>\n" } ]
2018/08/13
[ "https://wordpress.stackexchange.com/questions/311318", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/119633/" ]
I am using plugin "wpdevart facebook comment" for posting comments at the end of every post. They are displaying good But now I want to shift those comments little below of pagination and ads Or at the end of the page but comments should be of the relevant post. attached is the screenshot: [![enter image description here](https://i.stack.imgur.com/riA78.png)](https://i.stack.imgur.com/riA78.png) And for this I have added the plugin shortcode in the Single.php ``` while ( have_posts() ) : the_post(); $bimber_post_settings = bimber_get_post_settings(); bimber_set_template_part_data( $bimber_post_settings ); /* * Include the post format-specific template for the content. If you want to * use this in a child theme, then include a file called called content-single-classic-___.php * (where ___ is the post format) and that will be used instead. */ get_template_part( 'template-parts/content-single-classic', get_post_format() ); comments_template(); //facebook comments echo do_shortcode('[wpdevart_facebook_comment facebook_app_id="12345678910111213" curent_url="http://developers.facebook.com/docs/plugins/comments/" order_type="social" title_text="Facebook Comment" title_text_color="#000000" title_text_font_size="16" title_text_font_famely="Arial" title_text_position="left" width="100%" bg_color="#000000" animation_effect="none" count_of_comments="10" ]'); bimber_reset_template_part_data(); endwhile; ?> ``` But It displays all comments of all posts and pages.
From the plugin's user manual. > > **Curent\_url** - Type the page URL from where you need to show Facebook > comments > > > So you will have to change the current URL which is (<http://developers.facebook.com/docs/plugins/comments/>) to your real current URL. ``` global $wp; $current_url = home_url( add_query_arg( array(), $wp->request ) ); echo do_shortcode('[wpdevart_facebook_comment facebook_app_id="12345678910111213" curent_url="'.$current_url.' " order_type="social" title_text="Facebook Comment" title_text_color="#000000" title_text_font_size="16" title_text_font_famely="Arial" title_text_position="left" width="100%" bg_color="#000000" animation_effect="none" count_of_comments="10" ]'); ```
311,340
<p>I try to <strong>hide</strong> the "cash on pickup"-payment-gateway [cop] when I am on the checkout page of my woocommerce installation. When I echo the code it gets two times executed. One time correctly, the other time it truncates the end of the url:</p> <p>functions.php</p> <pre><code>// Disable gateway on checkout page function payment_gateway_disable_cash_on_delivery_on_checkout( $available_gateways ) { global $woocommerce; global $wp; // Helper echo(" || get_page_link: "); echo(get_page_link()); echo(" || wp-&gt;request: "); echo(home_url( $wp-&gt;request)); echo(" || get_checkout_url: "); echo($woocommerce-&gt;cart-&gt;get_checkout_url()); echo(" || end. "); if ( isset( $available_gateways['cop'] ) &amp;&amp; (get_page_link() == $woocommerce-&gt;cart-&gt;get_checkout_url())) { unset( $available_gateways['cop'] ); } return $available_gateways; } add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_cash_on_delivery_on_checkout' ); </code></pre> <p>Output on the checkout page</p> <pre><code> || get_page_link: https://mypage.com/en/checkout/ || wp-&gt;request: https://mypage.com/en/checkout/ || get_checkout_url: https://mypage.com/en/checkout/ || end. || get_page_link: https://mypage.com/en/ || wp-&gt;request: https://mypage.com/en/ || get_checkout_url: https://mypage.com/en/checkout/ || end. </code></pre> <p>The Why this happens, or how to solve that? </p> <p>Here a screenshot:</p> <p><a href="https://i.stack.imgur.com/xa3bg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xa3bg.png" alt="enter image description here"></a></p>
[ { "answer_id": 311350, "author": "Jan", "author_id": 129330, "author_profile": "https://wordpress.stackexchange.com/users/129330", "pm_score": 1, "selected": false, "text": "<p>This is my solution:</p>\n\n<p>I had to disable the woocommerce checkout ajax script. It's causing a reload and adds some parameters which changes the url. This causes the fail of my equal.</p>\n\n<pre><code>/* hide payment method \"cash on delivery on cart view (it should only available in POS) */\n\n// Disable gateway on checkout page\nfunction payment_gateway_disable_cash_on_delivery_on_checkout( $available_gateways ) {\n\n global $woocommerce;\n\n // we need to dequeue the checkout script, otherwise the ajax call will change our url and the cop option is shown\n wp_dequeue_script( 'wc-checkout' );\n\n if ( isset( $available_gateways['cop'] ) &amp;&amp; (get_page_link() == $woocommerce-&gt;cart-&gt;get_checkout_url())) {\n unset( $available_gateways['cop'] );\n }\n\n return $available_gateways;\n}\n\nadd_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_cash_on_delivery_on_checkout' );\n</code></pre>\n" }, { "answer_id": 311501, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 2, "selected": false, "text": "<p>To answer the question in this posts's title, you don't need to check for the page's URL to see if you're on the checkout page as Woocommerce has a conditional for that - <a href=\"https://docs.woocommerce.com/wc-apidocs/function-is_checkout.html\" rel=\"nofollow noreferrer\"><code>is_checkout()</code></a></p>\n" } ]
2018/08/13
[ "https://wordpress.stackexchange.com/questions/311340", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/129330/" ]
I try to **hide** the "cash on pickup"-payment-gateway [cop] when I am on the checkout page of my woocommerce installation. When I echo the code it gets two times executed. One time correctly, the other time it truncates the end of the url: functions.php ``` // Disable gateway on checkout page function payment_gateway_disable_cash_on_delivery_on_checkout( $available_gateways ) { global $woocommerce; global $wp; // Helper echo(" || get_page_link: "); echo(get_page_link()); echo(" || wp->request: "); echo(home_url( $wp->request)); echo(" || get_checkout_url: "); echo($woocommerce->cart->get_checkout_url()); echo(" || end. "); if ( isset( $available_gateways['cop'] ) && (get_page_link() == $woocommerce->cart->get_checkout_url())) { unset( $available_gateways['cop'] ); } return $available_gateways; } add_filter( 'woocommerce_available_payment_gateways', 'payment_gateway_disable_cash_on_delivery_on_checkout' ); ``` Output on the checkout page ``` || get_page_link: https://mypage.com/en/checkout/ || wp->request: https://mypage.com/en/checkout/ || get_checkout_url: https://mypage.com/en/checkout/ || end. || get_page_link: https://mypage.com/en/ || wp->request: https://mypage.com/en/ || get_checkout_url: https://mypage.com/en/checkout/ || end. ``` The Why this happens, or how to solve that? Here a screenshot: [![enter image description here](https://i.stack.imgur.com/xa3bg.png)](https://i.stack.imgur.com/xa3bg.png)
To answer the question in this posts's title, you don't need to check for the page's URL to see if you're on the checkout page as Woocommerce has a conditional for that - [`is_checkout()`](https://docs.woocommerce.com/wc-apidocs/function-is_checkout.html)
311,341
<p>I have a query like this i will get the id's for product. This works fine:</p> <pre><code>function ids(){ $args = array( 'numberposts' =&gt; -1, 'post_type' =&gt; 'product', 'meta_key' =&gt; 'wppl_is_dax', 'meta_value' =&gt; '1' ); // query $the_query = new WP_Query( $args ); if( $the_query-&gt;have_posts() ): while( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post(); global $product; return $product-&gt;get_id(); endwhile; endif; wp_reset_query(); } </code></pre> <p>But now i want to use the output from the above query in the below </p> <pre><code>function tester2(){ $targetted_products = array(/* the ids from above function- ids()*/); } </code></pre> <p>I am only getting one id if i use $targetted_products =array(ids());</p>
[ { "answer_id": 311343, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": true, "text": "<p>Your function returns <code>$product-&gt;get_id();</code>, instead of that, you should save those values into an array and at the end return that array.</p>\n\n<pre><code>function ids(){\n $args = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; 'product',\n 'meta_key' =&gt; 'wppl_is_dax',\n 'meta_value' =&gt; '1'\n );\n\n\n // query\n $the_query = new WP_Query( $args );\n $allIds = array();\n\n if( $the_query-&gt;have_posts() ): while( $the_query-&gt;have_posts() ) : $the_query-&gt;the_post();\n global $product;\n array_push($allIds,$product-&gt;get_id());\n endwhile; endif; wp_reset_query();\n return $allIds;\n}\n</code></pre>\n" }, { "answer_id": 311347, "author": "Valerii Vasyliev", "author_id": 146203, "author_profile": "https://wordpress.stackexchange.com/users/146203", "pm_score": 1, "selected": false, "text": "<pre><code>function ids(){\n\n $args = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; 'product',\n 'meta_key' =&gt; 'wppl_is_dax',\n 'meta_value' =&gt; '1'\n );\n\n\n // query\n $the_query = new WP_Query( $args );\n\n $post_ids = [];\n\n if( $the_query-&gt;have_posts() ): \n\n $post_ids = wp_list_pluck( $the_query-&gt;posts, 'ID' );\n\n endif; \n\n wp_reset_query();\n\n\n return $post_ids;\n}\n</code></pre>\n\n<p>read more <a href=\"https://codex.wordpress.org/Function_Reference/wp_list_pluck\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_list_pluck</a></p>\n" }, { "answer_id": 311362, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": false, "text": "<p>If you only want IDs, the query will consume much less memory if you use the <code>fields</code> parameter to just get that one field back in an array:</p>\n\n<pre><code>function ids(){\n $args = array(\n 'numberposts' =&gt; -1,\n 'post_type' =&gt; 'product',\n 'meta_key' =&gt; 'wppl_is_dax',\n 'meta_value' =&gt; '1'\n 'fields' =&gt; 'ids'\n );\n $the_query = new WP_Query( $args );\n if( $the_query-&gt;have_posts() ){\n return $the_query-&gt;posts;\n }\n return false;\n}\n</code></pre>\n" } ]
2018/08/13
[ "https://wordpress.stackexchange.com/questions/311341", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
I have a query like this i will get the id's for product. This works fine: ``` function ids(){ $args = array( 'numberposts' => -1, 'post_type' => 'product', 'meta_key' => 'wppl_is_dax', 'meta_value' => '1' ); // query $the_query = new WP_Query( $args ); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); global $product; return $product->get_id(); endwhile; endif; wp_reset_query(); } ``` But now i want to use the output from the above query in the below ``` function tester2(){ $targetted_products = array(/* the ids from above function- ids()*/); } ``` I am only getting one id if i use $targetted\_products =array(ids());
Your function returns `$product->get_id();`, instead of that, you should save those values into an array and at the end return that array. ``` function ids(){ $args = array( 'numberposts' => -1, 'post_type' => 'product', 'meta_key' => 'wppl_is_dax', 'meta_value' => '1' ); // query $the_query = new WP_Query( $args ); $allIds = array(); if( $the_query->have_posts() ): while( $the_query->have_posts() ) : $the_query->the_post(); global $product; array_push($allIds,$product->get_id()); endwhile; endif; wp_reset_query(); return $allIds; } ```
311,361
<p>I'm not a WordPress developer, I'm trying to help a friend who has a WordPress website. Here is the problem: </p> <p>In the template, <code>wp_head()</code> function adds bunch of styles and scripts.</p> <p>I want to remove some of them in some pages lets say this one: </p> <pre><code>&lt;link rel='stylesheet' id='yasrcss-css' href='https://www.example.com/wp-content/plugins/yet-another-stars-rating/css/yasr.css' type='text/css' media='all' /&gt; </code></pre> <p>So I searched around and based on what I've been suggested on other questions, I added this lines to <code>functions.php</code> (inside theme folder):</p> <pre><code>add_action( 'init', '_remove_style' ); function _remove_style() { wp_dequeue_style( 'yasrcss-css' ); wp_dequeue_style( 'yasr.css' ); } </code></pre> <p>It didnt work, also I added this in <code>functions.php</code>:</p> <pre><code>wp_deregister_style('yasrcss-css'); </code></pre> <p>This one didn't work either.</p> <p>Am I missing something, is there anything else I should do ? </p> <p>BTW, I tried this code: </p> <pre><code>printf( '&lt;pre&gt;%s&lt;/pre&gt;', var_export( $GLOBALS['wp_scripts']-&gt;registered, TRUE ) ); </code></pre> <p>as suggested <a href="https://wordpress.stackexchange.com/questions/213862/remove-specific-css-and-js-from-the-head">here</a>. It didn't have that particular CSS in the output. </p>
[ { "answer_id": 311366, "author": "Futuritous", "author_id": 122392, "author_profile": "https://wordpress.stackexchange.com/users/122392", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Note: the file name is <code>functions.php</code>, not <code>function.php</code> (but that's probably just a typo in the question).</p>\n</blockquote>\n\n<p>To remove a script or style, you must remove it after it was added. If you try to remove it before it was added, or even print <code>$GLOBALS['wp_scripts']-&gt;registered</code>, nothing will happen, since it was not added yet.</p>\n\n<p>So a way to remove them is to execute the <code>_remove_style</code> function as late as possible.</p>\n\n<p>Also, you need to make sure you are using the correct handle that was used to enqueue the CSS file in the first place. In this case, the correct handle is: <code>yasrcss</code> (credit to <a href=\"https://wordpress.stackexchange.com/users/1685/thedeadmedic\">@thedeadmedic</a>).</p>\n\n<p>Combining all these, you may try the following CODE:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', '_remove_style', PHP_INT_MAX );\nfunction _remove_style() {\n wp_dequeue_style( 'yasrcss' );\n}\n</code></pre>\n" }, { "answer_id": 311384, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 1, "selected": false, "text": "<p>To remove stylesheet from few selected pages, open your function.php file and put below code inside this file. In the page id array, it targets only specific page where you don't want to apply your CSS</p>\n\n<pre><code>add_action('init','_remove_style');\nfunction _remove_style(){\n global $post;\n $pageID = array('20','30', '420');//Mention the page id where you do not wish to include that script\n\n if(in_array($post-&gt;ID, $pageID)) {\n wp_dequeue_style('your_style_sheet.css'); \n }\n}\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311361", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148678/" ]
I'm not a WordPress developer, I'm trying to help a friend who has a WordPress website. Here is the problem: In the template, `wp_head()` function adds bunch of styles and scripts. I want to remove some of them in some pages lets say this one: ``` <link rel='stylesheet' id='yasrcss-css' href='https://www.example.com/wp-content/plugins/yet-another-stars-rating/css/yasr.css' type='text/css' media='all' /> ``` So I searched around and based on what I've been suggested on other questions, I added this lines to `functions.php` (inside theme folder): ``` add_action( 'init', '_remove_style' ); function _remove_style() { wp_dequeue_style( 'yasrcss-css' ); wp_dequeue_style( 'yasr.css' ); } ``` It didnt work, also I added this in `functions.php`: ``` wp_deregister_style('yasrcss-css'); ``` This one didn't work either. Am I missing something, is there anything else I should do ? BTW, I tried this code: ``` printf( '<pre>%s</pre>', var_export( $GLOBALS['wp_scripts']->registered, TRUE ) ); ``` as suggested [here](https://wordpress.stackexchange.com/questions/213862/remove-specific-css-and-js-from-the-head). It didn't have that particular CSS in the output.
> > Note: the file name is `functions.php`, not `function.php` (but that's probably just a typo in the question). > > > To remove a script or style, you must remove it after it was added. If you try to remove it before it was added, or even print `$GLOBALS['wp_scripts']->registered`, nothing will happen, since it was not added yet. So a way to remove them is to execute the `_remove_style` function as late as possible. Also, you need to make sure you are using the correct handle that was used to enqueue the CSS file in the first place. In this case, the correct handle is: `yasrcss` (credit to [@thedeadmedic](https://wordpress.stackexchange.com/users/1685/thedeadmedic)). Combining all these, you may try the following CODE: ``` add_action( 'wp_enqueue_scripts', '_remove_style', PHP_INT_MAX ); function _remove_style() { wp_dequeue_style( 'yasrcss' ); } ```
311,375
<p>when I copy my content from my WordPad and paste it into Wordpress Visual editor it shows line break on post display on the browser whenever a line is started in visual editor</p>
[ { "answer_id": 311366, "author": "Futuritous", "author_id": 122392, "author_profile": "https://wordpress.stackexchange.com/users/122392", "pm_score": 4, "selected": true, "text": "<blockquote>\n <p>Note: the file name is <code>functions.php</code>, not <code>function.php</code> (but that's probably just a typo in the question).</p>\n</blockquote>\n\n<p>To remove a script or style, you must remove it after it was added. If you try to remove it before it was added, or even print <code>$GLOBALS['wp_scripts']-&gt;registered</code>, nothing will happen, since it was not added yet.</p>\n\n<p>So a way to remove them is to execute the <code>_remove_style</code> function as late as possible.</p>\n\n<p>Also, you need to make sure you are using the correct handle that was used to enqueue the CSS file in the first place. In this case, the correct handle is: <code>yasrcss</code> (credit to <a href=\"https://wordpress.stackexchange.com/users/1685/thedeadmedic\">@thedeadmedic</a>).</p>\n\n<p>Combining all these, you may try the following CODE:</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', '_remove_style', PHP_INT_MAX );\nfunction _remove_style() {\n wp_dequeue_style( 'yasrcss' );\n}\n</code></pre>\n" }, { "answer_id": 311384, "author": "AddWeb Solution Pvt Ltd", "author_id": 73643, "author_profile": "https://wordpress.stackexchange.com/users/73643", "pm_score": 1, "selected": false, "text": "<p>To remove stylesheet from few selected pages, open your function.php file and put below code inside this file. In the page id array, it targets only specific page where you don't want to apply your CSS</p>\n\n<pre><code>add_action('init','_remove_style');\nfunction _remove_style(){\n global $post;\n $pageID = array('20','30', '420');//Mention the page id where you do not wish to include that script\n\n if(in_array($post-&gt;ID, $pageID)) {\n wp_dequeue_style('your_style_sheet.css'); \n }\n}\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311375", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148683/" ]
when I copy my content from my WordPad and paste it into Wordpress Visual editor it shows line break on post display on the browser whenever a line is started in visual editor
> > Note: the file name is `functions.php`, not `function.php` (but that's probably just a typo in the question). > > > To remove a script or style, you must remove it after it was added. If you try to remove it before it was added, or even print `$GLOBALS['wp_scripts']->registered`, nothing will happen, since it was not added yet. So a way to remove them is to execute the `_remove_style` function as late as possible. Also, you need to make sure you are using the correct handle that was used to enqueue the CSS file in the first place. In this case, the correct handle is: `yasrcss` (credit to [@thedeadmedic](https://wordpress.stackexchange.com/users/1685/thedeadmedic)). Combining all these, you may try the following CODE: ``` add_action( 'wp_enqueue_scripts', '_remove_style', PHP_INT_MAX ); function _remove_style() { wp_dequeue_style( 'yasrcss' ); } ```
311,396
<p>I want to get all post types filtered by get_post_types() arguments.</p> <pre><code>public static function get_post_type() { if(!$post_type = wp_cache_get('post_type', 'dsad')) { $post_type = get_post_types(array( 'public' =&gt; true, 'show_ui' =&gt; true )); wp_cache_set('post_type', $post_type, 'dsad'); } return $post_type; } </code></pre> <p>However, with this code, it returns this value:</p> <pre><code>array(3) { ["post"]=&gt; string(4) "post" ["page"]=&gt; string(4) "page" ["attachment"]=&gt; string(10) "attachment" } </code></pre> <p>How can I get all of my post types?</p>
[ { "answer_id": 311397, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 0, "selected": false, "text": "<p>This answer can give you an important advice: <a href=\"https://wordpress.stackexchange.com/questions/139403/action-init-hook-and-get-post-types\">action init hook and get_post_types</a></p>\n\n<p>you've to run your function using an hook later than <code>init</code> which is likely the hook used to register your CPT \nSo I think:</p>\n\n<pre><code>add_action('wp_loaded', 'get_post_type');\nfunction get_post_type()\n{\n if(!$post_type = wp_cache_get('post_type', 'dsad'))\n {\n $post_type = get_post_types(array(\n 'public' =&gt; true,\n 'show_ui' =&gt; true\n ));\n wp_cache_set('post_type', $post_type, 'dsad');\n }\n\n return $post_type;\n}\n</code></pre>\n\n<p>will work</p>\n" }, { "answer_id": 311398, "author": "Priyanka Modi", "author_id": 131670, "author_profile": "https://wordpress.stackexchange.com/users/131670", "pm_score": 1, "selected": false, "text": "<p>Build in WordPress function for fetching all registered post types: <strong>get_post_types()</strong> </p>\n\n<pre><code> &lt;?php\n // hook into init late, so everything is registered\n // you can also use get_post_types where ever. Any time after init is usually fine.\n add_action( 'init', 'wpse34410_init', 0, 99 );\n function wpse34410_init() \n {\n $types = get_post_types( [], 'objects' );\n foreach ( $types as $type ) {\n if ( isset( $type-&gt;rewrite-&gt;slug ) ) {\n // you'll probably want to do something else.\n echo $type-&gt;rewrite-&gt;slug;\n }\n }\n }\n?&gt;\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311396", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148689/" ]
I want to get all post types filtered by get\_post\_types() arguments. ``` public static function get_post_type() { if(!$post_type = wp_cache_get('post_type', 'dsad')) { $post_type = get_post_types(array( 'public' => true, 'show_ui' => true )); wp_cache_set('post_type', $post_type, 'dsad'); } return $post_type; } ``` However, with this code, it returns this value: ``` array(3) { ["post"]=> string(4) "post" ["page"]=> string(4) "page" ["attachment"]=> string(10) "attachment" } ``` How can I get all of my post types?
Build in WordPress function for fetching all registered post types: **get\_post\_types()** ``` <?php // hook into init late, so everything is registered // you can also use get_post_types where ever. Any time after init is usually fine. add_action( 'init', 'wpse34410_init', 0, 99 ); function wpse34410_init() { $types = get_post_types( [], 'objects' ); foreach ( $types as $type ) { if ( isset( $type->rewrite->slug ) ) { // you'll probably want to do something else. echo $type->rewrite->slug; } } } ?> ```
311,401
<p>I have inherited an existing site and have recently been asked to make some changes.</p> <p>They have 'renamed' the default post as 'latest-news' using this 'my_new_default_post_type':</p> <pre><code>&lt;?php add_action( 'init', 'my_new_default_post_type', 1 ); function my_new_default_post_type() { register_post_type( 'post', array( 'labels' =&gt; array( 'name_admin_bar' =&gt; _x( 'Post', 'add new on admin bar' ), ), 'public' =&gt; true, '_builtin' =&gt; false, '_edit_link' =&gt; 'post.php?post=%d', 'capability_type' =&gt; 'post', 'map_meta_cap' =&gt; true, 'hierarchical' =&gt; false, 'rewrite' =&gt; array('slug' =&gt; 'latest-news','with_front' =&gt; false), 'query_var' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); } ?&gt; </code></pre> <p>These can be seen being listed on a standard page here:</p> <p><a href="https://gateleyplc.com/news-events/latest-news/" rel="nofollow noreferrer">https://gateleyplc.com/news-events/latest-news/</a></p> <p>with the second page of pagination here:</p> <p><a href="https://gateleyplc.com/news-events/latest-news/page/2/" rel="nofollow noreferrer">https://gateleyplc.com/news-events/latest-news/page/2/</a></p> <p>Clicking into a post loads it here:</p> <p><a href="https://gateleyplc.com/latest-news/gateley-plc-celebrates-sixth-anniversary-in-yorkshire-with-the-appointment-of-six-new-solicitors/" rel="nofollow noreferrer">https://gateleyplc.com/latest-news/gateley-plc-celebrates-sixth-anniversary-in-yorkshire-with-the-appointment-of-six-new-solicitors/</a></p> <p>I have added some new custom post types, one example of which is 'corparate-deals'. The code to add this custom post type is:</p> <pre><code>&lt;?php add_action('init', 'corporate_deals_register'); function corporate_deals_register() { $labels = array( 'name' =&gt; _x('Corporate Deals', 'post type general name'), 'singular_name' =&gt; _x('Corporate Deals', 'post type singular name'), 'add_new_item' =&gt; __('Add New Briefing'), 'edit_item' =&gt; __('Edit briefing'), 'new_item' =&gt; __('New briefing'), 'view_item' =&gt; __('View briefing'), 'search_items' =&gt; __('Search Corporate Deals'), 'not_found' =&gt; __('Nothing found'), 'not_found_in_trash' =&gt; __('Nothing found in Trash'), 'parent_item_colon' =&gt; '' ); $args = array( 'labels' =&gt; $labels, 'public' =&gt; true, 'has_archive' =&gt; false, 'show_ui' =&gt; true, 'capability_type' =&gt; 'post', 'taxonomies' =&gt; array( 'category' ), 'hierarchical' =&gt; false, 'publicly_queriable' =&gt; false, 'show_ui' =&gt; true, 'show_in_nav_menus' =&gt; false, 'exclude_from_search' =&gt; false, 'menu_icon' =&gt; 'dashicons-welcome-add-page', // Icon Path 'menu_position' =&gt; 5, 'show_in_menu' =&gt; 'blogs_menu', 'query_var' =&gt; true, 'supports' =&gt; array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'revisions' ), ); register_post_type( 'corporate-deals' , $args ); } ?&gt; </code></pre> <p>You can see these listed here:</p> <p><a href="https://gateleyplc.com/corporate-deals" rel="nofollow noreferrer">https://gateleyplc.com/corporate-deals</a></p> <p>and clicking into one here:</p> <p><a href="https://gateleyplc.com/corporate-deals/gateley-corporate-team-advises-on-firms-acquisition-of-kiddy-partners/" rel="nofollow noreferrer">https://gateleyplc.com/corporate-deals/gateley-corporate-team-advises-on-firms-acquisition-of-kiddy-partners/</a></p> <p><strong>However...</strong> when you try to view the second page of pagination, here:</p> <p><a href="https://gateleyplc.com/corporate-deals/page/2/" rel="nofollow noreferrer">https://gateleyplc.com/corporate-deals/page/2/</a></p> <p>it redirects to:</p> <p><a href="https://gateleyplc.com" rel="nofollow noreferrer">https://gateleyplc.com</a></p> <p>I have searched high and low for any redirects or rewrite rules but cannot find any.</p> <p>One thing I did notice is that if I add:</p> <pre><code>'rewrite' =&gt; array('slug' =&gt; 'latest-news','with_front' =&gt; false), </code></pre> <p>to my custom post declaration (i.e. rewriting the 'corporate-deals' to 'latest-news') then the redirection doesn't occur.</p> <p>Any help greatly appreciated. Thanks in advance.</p> <p><strong>Additionally</strong></p> <p>The code that builds the post listing is:</p> <pre><code>&lt;?php // Corporate Deals function paginatedcorporatedeals_func( $atts ) { extract( shortcode_atts( array( 'pageid' =&gt; '{$pageid}', 'title' =&gt; '{$title}', 'showcontent' =&gt; '{$showcontent}', 'newsurl' =&gt; '{$newsurl}', 'postmeta' =&gt; '{$postmeta}' ), $atts ) ); $output; global $post; $ws = 1; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type'=&gt;'corporate-deals', //'order'=&gt;'ASC', 'posts_per_page' =&gt; 16, 'paged' =&gt; $paged, ); $slug = the_slug(); query_posts($args); // global $wp_query; // $postcount = $wp_query-&gt;found_posts; $count=0; if(have_posts()) { $divider = 'yes'; $featuredimg = 'date'; $truncate = 250; while (have_posts()) : the_post(); global $post; $thetitle = get_the_title($post-&gt;ID); require get_template_directory() . '/assets/inc/plugins/vc-intergration/modules/shortcode-templates/media-list.php'; $output .="&lt;hr&gt;"; $count++; endwhile; $output .= "&lt;div class='vc_row clearfix'&gt;&lt;div class='white-bar'&gt;".page_pagination()."&lt;/div&gt;&lt;/div&gt;"; wp_reset_query(); } return $output; } add_shortcode( 'paginatedcorporatedeals', 'paginatedcorporatedeals_func' ); ?&gt; </code></pre>
[ { "answer_id": 311397, "author": "Andrea Somovigo", "author_id": 64435, "author_profile": "https://wordpress.stackexchange.com/users/64435", "pm_score": 0, "selected": false, "text": "<p>This answer can give you an important advice: <a href=\"https://wordpress.stackexchange.com/questions/139403/action-init-hook-and-get-post-types\">action init hook and get_post_types</a></p>\n\n<p>you've to run your function using an hook later than <code>init</code> which is likely the hook used to register your CPT \nSo I think:</p>\n\n<pre><code>add_action('wp_loaded', 'get_post_type');\nfunction get_post_type()\n{\n if(!$post_type = wp_cache_get('post_type', 'dsad'))\n {\n $post_type = get_post_types(array(\n 'public' =&gt; true,\n 'show_ui' =&gt; true\n ));\n wp_cache_set('post_type', $post_type, 'dsad');\n }\n\n return $post_type;\n}\n</code></pre>\n\n<p>will work</p>\n" }, { "answer_id": 311398, "author": "Priyanka Modi", "author_id": 131670, "author_profile": "https://wordpress.stackexchange.com/users/131670", "pm_score": 1, "selected": false, "text": "<p>Build in WordPress function for fetching all registered post types: <strong>get_post_types()</strong> </p>\n\n<pre><code> &lt;?php\n // hook into init late, so everything is registered\n // you can also use get_post_types where ever. Any time after init is usually fine.\n add_action( 'init', 'wpse34410_init', 0, 99 );\n function wpse34410_init() \n {\n $types = get_post_types( [], 'objects' );\n foreach ( $types as $type ) {\n if ( isset( $type-&gt;rewrite-&gt;slug ) ) {\n // you'll probably want to do something else.\n echo $type-&gt;rewrite-&gt;slug;\n }\n }\n }\n?&gt;\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311401", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148618/" ]
I have inherited an existing site and have recently been asked to make some changes. They have 'renamed' the default post as 'latest-news' using this 'my\_new\_default\_post\_type': ``` <?php add_action( 'init', 'my_new_default_post_type', 1 ); function my_new_default_post_type() { register_post_type( 'post', array( 'labels' => array( 'name_admin_bar' => _x( 'Post', 'add new on admin bar' ), ), 'public' => true, '_builtin' => false, '_edit_link' => 'post.php?post=%d', 'capability_type' => 'post', 'map_meta_cap' => true, 'hierarchical' => false, 'rewrite' => array('slug' => 'latest-news','with_front' => false), 'query_var' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'comments', 'revisions', 'post-formats' ), ) ); } ?> ``` These can be seen being listed on a standard page here: <https://gateleyplc.com/news-events/latest-news/> with the second page of pagination here: <https://gateleyplc.com/news-events/latest-news/page/2/> Clicking into a post loads it here: <https://gateleyplc.com/latest-news/gateley-plc-celebrates-sixth-anniversary-in-yorkshire-with-the-appointment-of-six-new-solicitors/> I have added some new custom post types, one example of which is 'corparate-deals'. The code to add this custom post type is: ``` <?php add_action('init', 'corporate_deals_register'); function corporate_deals_register() { $labels = array( 'name' => _x('Corporate Deals', 'post type general name'), 'singular_name' => _x('Corporate Deals', 'post type singular name'), 'add_new_item' => __('Add New Briefing'), 'edit_item' => __('Edit briefing'), 'new_item' => __('New briefing'), 'view_item' => __('View briefing'), 'search_items' => __('Search Corporate Deals'), 'not_found' => __('Nothing found'), 'not_found_in_trash' => __('Nothing found in Trash'), 'parent_item_colon' => '' ); $args = array( 'labels' => $labels, 'public' => true, 'has_archive' => false, 'show_ui' => true, 'capability_type' => 'post', 'taxonomies' => array( 'category' ), 'hierarchical' => false, 'publicly_queriable' => false, 'show_ui' => true, 'show_in_nav_menus' => false, 'exclude_from_search' => false, 'menu_icon' => 'dashicons-welcome-add-page', // Icon Path 'menu_position' => 5, 'show_in_menu' => 'blogs_menu', 'query_var' => true, 'supports' => array( 'title', 'editor', 'author', 'thumbnail', 'excerpt', 'trackbacks', 'custom-fields', 'revisions' ), ); register_post_type( 'corporate-deals' , $args ); } ?> ``` You can see these listed here: <https://gateleyplc.com/corporate-deals> and clicking into one here: <https://gateleyplc.com/corporate-deals/gateley-corporate-team-advises-on-firms-acquisition-of-kiddy-partners/> **However...** when you try to view the second page of pagination, here: <https://gateleyplc.com/corporate-deals/page/2/> it redirects to: <https://gateleyplc.com> I have searched high and low for any redirects or rewrite rules but cannot find any. One thing I did notice is that if I add: ``` 'rewrite' => array('slug' => 'latest-news','with_front' => false), ``` to my custom post declaration (i.e. rewriting the 'corporate-deals' to 'latest-news') then the redirection doesn't occur. Any help greatly appreciated. Thanks in advance. **Additionally** The code that builds the post listing is: ``` <?php // Corporate Deals function paginatedcorporatedeals_func( $atts ) { extract( shortcode_atts( array( 'pageid' => '{$pageid}', 'title' => '{$title}', 'showcontent' => '{$showcontent}', 'newsurl' => '{$newsurl}', 'postmeta' => '{$postmeta}' ), $atts ) ); $output; global $post; $ws = 1; $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type'=>'corporate-deals', //'order'=>'ASC', 'posts_per_page' => 16, 'paged' => $paged, ); $slug = the_slug(); query_posts($args); // global $wp_query; // $postcount = $wp_query->found_posts; $count=0; if(have_posts()) { $divider = 'yes'; $featuredimg = 'date'; $truncate = 250; while (have_posts()) : the_post(); global $post; $thetitle = get_the_title($post->ID); require get_template_directory() . '/assets/inc/plugins/vc-intergration/modules/shortcode-templates/media-list.php'; $output .="<hr>"; $count++; endwhile; $output .= "<div class='vc_row clearfix'><div class='white-bar'>".page_pagination()."</div></div>"; wp_reset_query(); } return $output; } add_shortcode( 'paginatedcorporatedeals', 'paginatedcorporatedeals_func' ); ?> ```
Build in WordPress function for fetching all registered post types: **get\_post\_types()** ``` <?php // hook into init late, so everything is registered // you can also use get_post_types where ever. Any time after init is usually fine. add_action( 'init', 'wpse34410_init', 0, 99 ); function wpse34410_init() { $types = get_post_types( [], 'objects' ); foreach ( $types as $type ) { if ( isset( $type->rewrite->slug ) ) { // you'll probably want to do something else. echo $type->rewrite->slug; } } } ?> ```
311,414
<p>How do I for instance check if there is written a new comment in the database and then make my plugin register that there have been a change? I will use this information to do something in the database afterwards with my plugin.</p> <p>Any help appreciated. Could not find anything regarding this question.</p>
[ { "answer_id": 311420, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<h2>By checking the <code>date</code> columns:</h2>\n\n<p>To only check for new comments, new posts etc., you may create a cron job &amp; then check the <code>comment_date</code>, <code>post_date</code> etc. to determine if anything new appeared in those tables. Save a last checked timestamp from the cron job, so any row with <code>date</code> greater than the last checked timestamp is a new insert.</p>\n\n<h2>Using WordPress API filter / action hooks:</h2>\n\n<p>WordPress fires some filter / action hooks before/after making database changes.</p>\n\n<p>Usually action hooks are fired <strong>after</strong> a database action is completed. Often these hooks have name prefix/suffix like <code>added/update/updated/deleted/save/insert</code> etc. Unfortunately, WordPress hooks naming are not consistent, otherwise it would've been much easier.</p>\n\n<p>For example, comment API fires the following action hooks after database changes:</p>\n\n<ul>\n<li><code>wp_insert_comment</code>: fires after a comment is inserted into the \ndatabase.</li>\n<li><code>deleted_comment</code>: fires after a comment is deleted from the \ndatabase.</li>\n<li><code>trashed_comment</code>: fires after a comment is moved to trash.</li>\n<li><code>untrashed_comment</code>: fires after a comment is moved out of trash.</li>\n<li><code>spammed_comment</code>: fires after a comment is marked as spam.</li>\n<li><code>unspammed_comment</code>: fires after a comment (previously marked as spam) is unmarked as spam.</li>\n<li><code>edit_comment</code>: fires after a comment is updated/edited.</li>\n<li><code>comment_closed</code>: fires after a post is marked as not allowing comments.</li>\n</ul>\n\n<p>Sample CODE with an action hook:</p>\n\n<pre><code>add_action( 'wp_insert_comment', 'wpse_comment_inserted' );\nfunction wpse_comment_inserted( $comment_id, $comment_object, 99, 2 ) {\n // comment with id $comment_id is inserted into the database,\n // do something with it here\n}\n</code></pre>\n\n<p>There are many other <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference\" rel=\"nofollow noreferrer\">filter hooks</a> and <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference\" rel=\"nofollow noreferrer\">action hooks</a> that run before / after database changes. Use them as you need.</p>\n\n<p>Advantage of using these hooks is that, since they are part of WordPress core, you'll not have to worry about internal changes. The disadvantage is however, that there may be plugins / themes that don't use these core API(s), instead runs their custom constructed queries. So you'll not be able to catch DB changes from those.</p>\n\n<h2>By using <code>query</code> filter hook:</h2>\n\n<p>It's also possible to track Insert/Update/Delete queries made through WordPress <code>$wpdb</code> API. Any database query that uses WordPress Database API, uses <code>$wpdb</code> (an instance of <code>wpdb</code> class). All the queries (including insert, update and delete) fire <a href=\"https://developer.wordpress.org/reference/hooks/query/\" rel=\"nofollow noreferrer\"><code>query</code> filter hook</a>. So using this hook you can filter all the queries just before they are executed.</p>\n\n<p>However, it'll not work if any theme / plugin makes custom DB queries outside of WordPress <code>$wpdb</code> API or if any core query runs before the plugin is loaded or if any external application makes the changes through custom SQL queries.</p>\n\n<h2>By extending <code>wpdb</code> class:</h2>\n\n<p>Also, it's possible to create a <a href=\"https://wordpress.stackexchange.com/a/160815/110572\"><code>db.php</code> file, in the <code>wp-content</code></a> directory (or create a soft link in <code>wp-content</code> from a plugin) and extend the <code>wpdb</code> class from there. This way you may enhance any method of <code>wpdb</code> class and track the insert/update/delete queries from there.</p>\n\n<h2>By using database trigger:</h2>\n\n<p>However, to track any database change by any SQL query, the only reliable and complete way is to create <a href=\"https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html\" rel=\"nofollow noreferrer\">triggers</a> upon plugin activation and then track the database changes through the trigger. Although, to do this from a plugin, the Database credential you are using for WordPress must have create / drop trigger privilege. </p>\n\n<blockquote>\n <p><strong>Caution:</strong> Too many triggers may slow down DB queries. Also, make sure to clean up the triggers at the time of plugin deactivation. </p>\n</blockquote>\n" }, { "answer_id": 311444, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 2, "selected": false, "text": "<p>If you want something to happen when a comment is saved (posted) by the commenter, then you want to use the preprocess_comment filter (see \n<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/preprocess_comment\" rel=\"nofollow noreferrer\">Plugin API/Filter Reference/preprocess comment\n</a>).</p>\n\n<pre><code>function preprocess_comment_handler( $commentdata ) {\n //some code\n return $commentdata;\n}\nadd_filter( 'preprocess_comment' , 'preprocess_comment_handler' );\n</code></pre>\n\n<p>Just add code for whatever you want to happen when a comment is saved. Put this block of code in your <code>functions.php</code> (in a Child Theme, so a theme update doesn't overwrite your code).</p>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311414", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148099/" ]
How do I for instance check if there is written a new comment in the database and then make my plugin register that there have been a change? I will use this information to do something in the database afterwards with my plugin. Any help appreciated. Could not find anything regarding this question.
By checking the `date` columns: ------------------------------- To only check for new comments, new posts etc., you may create a cron job & then check the `comment_date`, `post_date` etc. to determine if anything new appeared in those tables. Save a last checked timestamp from the cron job, so any row with `date` greater than the last checked timestamp is a new insert. Using WordPress API filter / action hooks: ------------------------------------------ WordPress fires some filter / action hooks before/after making database changes. Usually action hooks are fired **after** a database action is completed. Often these hooks have name prefix/suffix like `added/update/updated/deleted/save/insert` etc. Unfortunately, WordPress hooks naming are not consistent, otherwise it would've been much easier. For example, comment API fires the following action hooks after database changes: * `wp_insert_comment`: fires after a comment is inserted into the database. * `deleted_comment`: fires after a comment is deleted from the database. * `trashed_comment`: fires after a comment is moved to trash. * `untrashed_comment`: fires after a comment is moved out of trash. * `spammed_comment`: fires after a comment is marked as spam. * `unspammed_comment`: fires after a comment (previously marked as spam) is unmarked as spam. * `edit_comment`: fires after a comment is updated/edited. * `comment_closed`: fires after a post is marked as not allowing comments. Sample CODE with an action hook: ``` add_action( 'wp_insert_comment', 'wpse_comment_inserted' ); function wpse_comment_inserted( $comment_id, $comment_object, 99, 2 ) { // comment with id $comment_id is inserted into the database, // do something with it here } ``` There are many other [filter hooks](https://codex.wordpress.org/Plugin_API/Filter_Reference) and [action hooks](https://codex.wordpress.org/Plugin_API/Action_Reference) that run before / after database changes. Use them as you need. Advantage of using these hooks is that, since they are part of WordPress core, you'll not have to worry about internal changes. The disadvantage is however, that there may be plugins / themes that don't use these core API(s), instead runs their custom constructed queries. So you'll not be able to catch DB changes from those. By using `query` filter hook: ----------------------------- It's also possible to track Insert/Update/Delete queries made through WordPress `$wpdb` API. Any database query that uses WordPress Database API, uses `$wpdb` (an instance of `wpdb` class). All the queries (including insert, update and delete) fire [`query` filter hook](https://developer.wordpress.org/reference/hooks/query/). So using this hook you can filter all the queries just before they are executed. However, it'll not work if any theme / plugin makes custom DB queries outside of WordPress `$wpdb` API or if any core query runs before the plugin is loaded or if any external application makes the changes through custom SQL queries. By extending `wpdb` class: -------------------------- Also, it's possible to create a [`db.php` file, in the `wp-content`](https://wordpress.stackexchange.com/a/160815/110572) directory (or create a soft link in `wp-content` from a plugin) and extend the `wpdb` class from there. This way you may enhance any method of `wpdb` class and track the insert/update/delete queries from there. By using database trigger: -------------------------- However, to track any database change by any SQL query, the only reliable and complete way is to create [triggers](https://dev.mysql.com/doc/refman/5.7/en/trigger-syntax.html) upon plugin activation and then track the database changes through the trigger. Although, to do this from a plugin, the Database credential you are using for WordPress must have create / drop trigger privilege. > > **Caution:** Too many triggers may slow down DB queries. Also, make sure to clean up the triggers at the time of plugin deactivation. > > >
311,416
<p>How can I configure to have two sets of URL that actually using the same content?</p> <p>For example:</p> <p>(set 1)</p> <pre><code>samplesite.com samplesite.com/about/ samplesite.com/contact/ samplesite.com/projects/ </code></pre> <p>(set 2)</p> <pre><code>samplesite.com/fr/ samplesite.com/fr/about/ samplesite.com/fr/contact/ samplesite.com/fr/projects/ </code></pre> <p>And then in my templates, I would like to check whether the request has <code>fr</code> or without.</p> <p>Is this possible without any plugin?</p>
[ { "answer_id": 311421, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 1, "selected": false, "text": "<p>You can create <strong>custom post type</strong> to manage your secondary content (multilanguage i suppose) and set these <code>/fr/</code> your CPT rewrite base.</p>\n\n<p>Create a CPT function add this to your function.</p>\n\n<pre><code>$rewrite = array(\n 'slug' =&gt; 'fr',\n 'with_front' =&gt; false,\n 'pages' =&gt; true,\n 'feeds' =&gt; true,\n);\n</code></pre>\n\n<p>After that set CPT <code>rewrite</code> option to <code>rewrite =&gt; $rewrite</code>. Not on same content but easy solution for your problem.</p>\n\n<p>Sample CPT code for you secondary content;</p>\n\n<pre><code> function secondary_content_french_post_type() {\n\n $labels = array(\n 'name' =&gt; _x( 'French', 'Post Type General Name', 'text_domain' ),\n 'singular_name' =&gt; _x( 'French', 'Post Type Singular Name', 'text_domain' ),\n 'menu_name' =&gt; __( 'French', 'text_domain' ),\n 'name_admin_bar' =&gt; __( 'French', 'text_domain' ),\n 'archives' =&gt; __( 'Item Archives', 'text_domain' ),\n 'attributes' =&gt; __( 'Item Attributes', 'text_domain' ),\n 'parent_item_colon' =&gt; __( 'Parent Item:', 'text_domain' ),\n 'all_items' =&gt; __( 'All Items', 'text_domain' ),\n 'add_new_item' =&gt; __( 'Add New Item', 'text_domain' ),\n 'add_new' =&gt; __( 'Add New', 'text_domain' ),\n 'new_item' =&gt; __( 'New Item', 'text_domain' ),\n 'edit_item' =&gt; __( 'Edit Item', 'text_domain' ),\n 'update_item' =&gt; __( 'Update Item', 'text_domain' ),\n 'view_item' =&gt; __( 'View Item', 'text_domain' ),\n 'view_items' =&gt; __( 'View Items', 'text_domain' ),\n 'search_items' =&gt; __( 'Search Item', 'text_domain' ),\n 'not_found' =&gt; __( 'Not found', 'text_domain' ),\n 'not_found_in_trash' =&gt; __( 'Not found in Trash', 'text_domain' ),\n 'featured_image' =&gt; __( 'Featured Image', 'text_domain' ),\n 'set_featured_image' =&gt; __( 'Set featured image', 'text_domain' ),\n 'remove_featured_image' =&gt; __( 'Remove featured image', 'text_domain' ),\n 'use_featured_image' =&gt; __( 'Use as featured image', 'text_domain' ),\n 'insert_into_item' =&gt; __( 'Insert into item', 'text_domain' ),\n 'uploaded_to_this_item' =&gt; __( 'Uploaded to this item', 'text_domain' ),\n 'items_list' =&gt; __( 'Items list', 'text_domain' ),\n 'items_list_navigation' =&gt; __( 'Items list navigation', 'text_domain' ),\n 'filter_items_list' =&gt; __( 'Filter items list', 'text_domain' ),\n );\n//This is Rewrite Code\n $rewrite = array(\n 'slug' =&gt; 'fr',\n 'with_front' =&gt; false,\n 'pages' =&gt; true,\n 'feeds' =&gt; true,\n );\n//This is Rewrite Code\n $args = array(\n 'label' =&gt; __( 'French', 'text_domain' ),\n 'description' =&gt; __( 'French', 'text_domain' ),\n 'labels' =&gt; $labels,\n 'supports' =&gt; array( 'title', 'editor', 'custom-fields','comments','thumbnail' ),\n 'taxonomies' =&gt; array( 'category' ),\n 'hierarchical' =&gt; false,\n 'public' =&gt; true,\n 'show_ui' =&gt; true,\n 'show_in_menu' =&gt; true,\n 'menu_position' =&gt; 10,\n 'menu_icon' =&gt; 'dashicons-nametag',\n 'show_in_admin_bar' =&gt; true,\n 'show_in_nav_menus' =&gt; false,\n 'can_export' =&gt; true,\n 'exclude_from_search' =&gt; false,\n 'publicly_queryable' =&gt; true,\n 'rewrite' =&gt; $rewrite,\n 'capability_type' =&gt; 'post',\n 'show_in_rest' =&gt; false,\n );\n register_post_type( 'french', $args );\n\n}\nadd_action( 'init', 'secondary_content_french_post_type', 0 );\n</code></pre>\n" }, { "answer_id": 311480, "author": "Run", "author_id": 89898, "author_profile": "https://wordpress.stackexchange.com/users/89898", "pm_score": 1, "selected": true, "text": "<p>My answer with the help from Sally CJ in this <a href=\"https://wordpress.stackexchange.com/questions/311476/add-rewrite-rule-to-call-front-page-php\">question</a>:</p>\n\n<pre><code>/**\n * Add new rewrite rule\n */\nfunction create_new_url_querystring() {\n // https://wordpress.stackexchange.com/questions/60173/rewrite-rule-for-multilingual-website-like-qtranslate\n add_rewrite_rule(\n '^fr/?$',\n 'index.php?&amp;page_id=2&amp;lang=fr',\n 'top'\n );\n\n add_rewrite_rule(\n '^fr/(.?.+?)(?:/([0-9]+))?/?$',\n 'index.php?pagename=$matches[1]&amp;page=$matches[2]',\n 'top'\n );\n\n add_rewrite_rule(\n 'fr/project/(.+?)(?:/([0-9]+))?/?$',\n 'index.php?project=$matches[1]&amp;page=$matches[2]',\n 'top'\n );\n\n // flush_rewrite_rules();\n global $wp_rewrite;\n $wp_rewrite-&gt;flush_rules();\n}\nadd_action('init', 'create_new_url_querystring');\n\n/**\n * Usage: get_query_var('lang');\n */\nfunction query_vars($query_vars) {\n $query_vars[] = \"lang\";\n return $query_vars;\n}\nadd_filter('query_vars', 'query_vars');\n\n/**\n * Cancel canonical redirect on home page.\n * https://wordpress.stackexchange.com/questions/311476/add-rewrite-rule-to-call-front-page-php\n */\nadd_action('template_redirect', function() {\n if (is_front_page()) {\n remove_action('template_redirect', 'redirect_canonical');\n }\n}, 0);\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311416", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/89898/" ]
How can I configure to have two sets of URL that actually using the same content? For example: (set 1) ``` samplesite.com samplesite.com/about/ samplesite.com/contact/ samplesite.com/projects/ ``` (set 2) ``` samplesite.com/fr/ samplesite.com/fr/about/ samplesite.com/fr/contact/ samplesite.com/fr/projects/ ``` And then in my templates, I would like to check whether the request has `fr` or without. Is this possible without any plugin?
My answer with the help from Sally CJ in this [question](https://wordpress.stackexchange.com/questions/311476/add-rewrite-rule-to-call-front-page-php): ``` /** * Add new rewrite rule */ function create_new_url_querystring() { // https://wordpress.stackexchange.com/questions/60173/rewrite-rule-for-multilingual-website-like-qtranslate add_rewrite_rule( '^fr/?$', 'index.php?&page_id=2&lang=fr', 'top' ); add_rewrite_rule( '^fr/(.?.+?)(?:/([0-9]+))?/?$', 'index.php?pagename=$matches[1]&page=$matches[2]', 'top' ); add_rewrite_rule( 'fr/project/(.+?)(?:/([0-9]+))?/?$', 'index.php?project=$matches[1]&page=$matches[2]', 'top' ); // flush_rewrite_rules(); global $wp_rewrite; $wp_rewrite->flush_rules(); } add_action('init', 'create_new_url_querystring'); /** * Usage: get_query_var('lang'); */ function query_vars($query_vars) { $query_vars[] = "lang"; return $query_vars; } add_filter('query_vars', 'query_vars'); /** * Cancel canonical redirect on home page. * https://wordpress.stackexchange.com/questions/311476/add-rewrite-rule-to-call-front-page-php */ add_action('template_redirect', function() { if (is_front_page()) { remove_action('template_redirect', 'redirect_canonical'); } }, 0); ```
311,427
<p>So, after working on a script that imports tons of data from another API, and doing lots of testing, all new posts I make have a post ID above 10,000,000.</p> <p>Thing is, now that I'm done, all my test data is gone, and my last "real" post has the ID 88.</p> <p>Is there a method to "reset" my post ID's, so that the next one I make has the ID 89? I know that there's no real need to do this, but I plan on maintaining this site for many years and it'll be annoying.</p> <p>Worst case, I can just reinstall and export/import.</p>
[ { "answer_id": 311429, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>I also happened to me once, I only had like 10 real post, so what I did was to go to <strong>phpMyAdmin</strong>, make sure your that on my <code>wp_posts</code> and <code>wp_posts_meta</code> tables are only information about the 10 real posts IDs, from the <code>mysite/wp-admin/export.php</code> I exported all the posts (10 of them), I run the following SQL query on <strong>phpMyAdmin</strong>. </p>\n\n<pre><code>DELETE FROM wp_posts;\nDELETE FROM wp_post_meta;\n\nTRUNCATE TABLE wp_posts;\nTRUNCATE TABLE wp_post_meta;\n</code></pre>\n\n<p>And finally, I import again the 10 posts, after that the ID was bad to normally, mine was only around 10000 tho, but it should work nonetheless.</p>\n" }, { "answer_id": 333048, "author": "Pramod Kharade", "author_id": 152890, "author_profile": "https://wordpress.stackexchange.com/users/152890", "pm_score": 2, "selected": false, "text": "<p>there is another one way to reset the auto-increment id of <code>wp_post_meta</code> and <code>wp_post</code> table :\nSOLUTION 1: </p>\n\n<pre><code>DELETE FROM wp_posts;\nDELETE FROM wp_post_meta;\n</code></pre>\n\n<p>Delete record by delete command but it will not reset the increment ID. Hence after deleting the record from both table rest the increment id like below command.</p>\n\n<pre><code>ALTER TABLE wp_posts AUTO_INCREMENT = 1;\nALTER TABLE wp_post_meta AUTO_INCREMENT = 1;\n</code></pre>\n\n<p>SOLUTION 2: </p>\n\n<pre><code>TRUNCATE TABLE wp_posts;\n TRUNCATE TABLE wp_post_meta;\n</code></pre>\n\n<p>Truncate record by Truncate command then it will reset the increment ID value to <code>0</code> and delete the records. </p>\n" }, { "answer_id": 403085, "author": "JrBPG", "author_id": 219638, "author_profile": "https://wordpress.stackexchange.com/users/219638", "pm_score": 0, "selected": false, "text": "<p><code>ALTER TABLE table_name AUTO_INCREMENT = value</code></p>\n<p>This SQL query fixed the issue for me.</p>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311427", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/44937/" ]
So, after working on a script that imports tons of data from another API, and doing lots of testing, all new posts I make have a post ID above 10,000,000. Thing is, now that I'm done, all my test data is gone, and my last "real" post has the ID 88. Is there a method to "reset" my post ID's, so that the next one I make has the ID 89? I know that there's no real need to do this, but I plan on maintaining this site for many years and it'll be annoying. Worst case, I can just reinstall and export/import.
I also happened to me once, I only had like 10 real post, so what I did was to go to **phpMyAdmin**, make sure your that on my `wp_posts` and `wp_posts_meta` tables are only information about the 10 real posts IDs, from the `mysite/wp-admin/export.php` I exported all the posts (10 of them), I run the following SQL query on **phpMyAdmin**. ``` DELETE FROM wp_posts; DELETE FROM wp_post_meta; TRUNCATE TABLE wp_posts; TRUNCATE TABLE wp_post_meta; ``` And finally, I import again the 10 posts, after that the ID was bad to normally, mine was only around 10000 tho, but it should work nonetheless.
311,431
<p>I have this working in my plugin and all is well with the world:</p> <pre><code>edit: withAPIData( props =&gt; { return { roles: '/matt-watson/secure-blocks/v1/user-roles/' }; } )( props =&gt; { </code></pre> <p>....</p> <p>However guidance here suggests that this will no longer be supported going forward: <a href="https://github.com/WordPress/gutenberg/issues/7390#issuecomment-398667802" rel="noreferrer">https://github.com/WordPress/gutenberg/issues/7390#issuecomment-398667802</a></p> <p>So I have managed to work that into the solution:</p> <pre><code>const DEFAULT_STATE = { userRoles: {}, }; const actions = { setUserRoles( userRoles ) { return { type: 'SET_USER_ROLES', userRoles, }; }, fetchFromAPI( path ) { return { type: 'FETCH_FROM_API', path, }; }, }; registerStore( 'matt-watson/secure-block', { reducer( state = DEFAULT_STATE, action ) { switch ( action.type ) { case 'SET_USER_ROLES': return { ...state, userRoles: action.userRoles, }; } return state; }, actions, selectors: { getUserRoles( state ) { const { userRoles } = state; return userRoles; }, }, controls: { FETCH_FROM_API( action ) { return apiFetch( { path: action.path } ); }, }, resolvers: { * getUserRoles( state ) { const path = '/matt-watson/secure-blocks/v1/user-roles/'; const userRoles = yield actions.fetchFromAPI( path ); return actions.setUserRoles( userRoles ); }, } , } ); </code></pre> <p>....</p> <pre><code>edit: withSelect( ( select ) =&gt; { return { roles: select('matt-watson/secure-block').getUserRoles(), }; } )( props =&gt; { </code></pre> <p>....</p> <p>Now the issue is that the 'controls' section never fires. In the documentation it says that this is an opt-in component, and I need to enable it via the <code>use</code> command: <a href="https://github.com/WordPress/gutenberg/tree/master/packages/data#controls" rel="noreferrer">https://github.com/WordPress/gutenberg/tree/master/packages/data#controls</a></p> <p>When I try this, <code>use</code> is undefined.</p> <p>So my question is this. As <code>withAPIData</code> did everything I needed in a very quick and easy way, is there an alternative 'drop-in' bit of code I can use, or do I need to progress with the store that I am registering? If so, what am I doing wrong?</p> <p>Any help appreciated. Thank you. </p>
[ { "answer_id": 311551, "author": "Matt Watson", "author_id": 148566, "author_profile": "https://wordpress.stackexchange.com/users/148566", "pm_score": 2, "selected": false, "text": "<p>I've cracked it! </p>\n\n<pre><code>const actions = {\n setUserRoles( userRoles ) {\n return {\n type: 'SET_USER_ROLES',\n userRoles,\n };\n },\n\n receiveUserRoles( path ) {\n return {\n type: 'RECEIVE_USER_ROLES',\n path,\n };\n },\n};\n\nconst store = registerStore( 'matt-watson/secure-block', {\n reducer( state = { userRoles: {} }, action ) {\n\n switch ( action.type ) {\n case 'SET_USER_ROLES':\n return {\n ...state,\n userRoles: action.userRoles,\n };\n case 'RECEIVE_USER_ROLES':\n return action.userRoles;\n }\n\n return state;\n },\n\n actions,\n\n selectors: {\n receiveUserRoles( state ) {\n const { userRoles } = state;\n return userRoles;\n },\n },\n\n resolvers: {\n * receiveUserRoles( state ) {\n const userRoles = apiFetch( { path: '/matt-watson/secure-blocks/v1/user-roles/' } )\n .then( userRoles =&gt; {\n return actions.setUserRoles( userRoles );\n } )\n yield userRoles;\n },\n },\n\n} );\n</code></pre>\n\n<p>This sets the state of the userRoles and returns the userRoles once resolved.</p>\n\n<p>You can then access this like so:</p>\n\n<p>....</p>\n\n<pre><code>edit: withSelect( ( select ) =&gt; {\n return {\n roles: select('matt-watson/secure-block').receiveUserRoles(),\n };\n } )( props =&gt; {\n</code></pre>\n\n<p>....</p>\n" }, { "answer_id": 321556, "author": "Matt Watson", "author_id": 148566, "author_profile": "https://wordpress.stackexchange.com/users/148566", "pm_score": 4, "selected": true, "text": "<p>It's worth noting that the answer above is out of date. The data store should now look like this:</p>\n\n<pre><code>const actions = {\n setUserRoles( userRoles ) {\n return {\n type: 'SET_USER_ROLES',\n userRoles,\n };\n },\n receiveUserRoles( path ) {\n return {\n type: 'RECEIVE_USER_ROLES',\n path,\n };\n },\n};\n\nconst store = registerStore( 'matt-watson/secure-block', {\n reducer( state = { userRoles: {} }, action ) {\n\n switch ( action.type ) {\n case 'SET_USER_ROLES':\n return {\n ...state,\n userRoles: action.userRoles,\n };\n }\n\n return state;\n },\n\n actions,\n\n selectors: {\n receiveUserRoles( state ) {\n const { userRoles } = state;\n return userRoles;\n },\n },\n\n controls: {\n RECEIVE_USER_ROLES( action ) {\n return apiFetch( { path: action.path } );\n },\n },\n\n resolvers: {\n * receiveUserRoles( state ) {\n const userRoles = yield actions.receiveUserRoles( '/matt-watson/secure-blocks/v1/user-roles/' );\n return actions.setUserRoles( userRoles );\n },\n },\n} );\n</code></pre>\n\n<p>I've updated my tutorial: <a href=\"https://mwatson.co.uk/working-with-gutenberg-and-the-wordpress-rest-api/\" rel=\"noreferrer\">https://mwatson.co.uk/working-with-gutenberg-and-the-wordpress-rest-api/</a></p>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311431", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148566/" ]
I have this working in my plugin and all is well with the world: ``` edit: withAPIData( props => { return { roles: '/matt-watson/secure-blocks/v1/user-roles/' }; } )( props => { ``` .... However guidance here suggests that this will no longer be supported going forward: <https://github.com/WordPress/gutenberg/issues/7390#issuecomment-398667802> So I have managed to work that into the solution: ``` const DEFAULT_STATE = { userRoles: {}, }; const actions = { setUserRoles( userRoles ) { return { type: 'SET_USER_ROLES', userRoles, }; }, fetchFromAPI( path ) { return { type: 'FETCH_FROM_API', path, }; }, }; registerStore( 'matt-watson/secure-block', { reducer( state = DEFAULT_STATE, action ) { switch ( action.type ) { case 'SET_USER_ROLES': return { ...state, userRoles: action.userRoles, }; } return state; }, actions, selectors: { getUserRoles( state ) { const { userRoles } = state; return userRoles; }, }, controls: { FETCH_FROM_API( action ) { return apiFetch( { path: action.path } ); }, }, resolvers: { * getUserRoles( state ) { const path = '/matt-watson/secure-blocks/v1/user-roles/'; const userRoles = yield actions.fetchFromAPI( path ); return actions.setUserRoles( userRoles ); }, } , } ); ``` .... ``` edit: withSelect( ( select ) => { return { roles: select('matt-watson/secure-block').getUserRoles(), }; } )( props => { ``` .... Now the issue is that the 'controls' section never fires. In the documentation it says that this is an opt-in component, and I need to enable it via the `use` command: <https://github.com/WordPress/gutenberg/tree/master/packages/data#controls> When I try this, `use` is undefined. So my question is this. As `withAPIData` did everything I needed in a very quick and easy way, is there an alternative 'drop-in' bit of code I can use, or do I need to progress with the store that I am registering? If so, what am I doing wrong? Any help appreciated. Thank you.
It's worth noting that the answer above is out of date. The data store should now look like this: ``` const actions = { setUserRoles( userRoles ) { return { type: 'SET_USER_ROLES', userRoles, }; }, receiveUserRoles( path ) { return { type: 'RECEIVE_USER_ROLES', path, }; }, }; const store = registerStore( 'matt-watson/secure-block', { reducer( state = { userRoles: {} }, action ) { switch ( action.type ) { case 'SET_USER_ROLES': return { ...state, userRoles: action.userRoles, }; } return state; }, actions, selectors: { receiveUserRoles( state ) { const { userRoles } = state; return userRoles; }, }, controls: { RECEIVE_USER_ROLES( action ) { return apiFetch( { path: action.path } ); }, }, resolvers: { * receiveUserRoles( state ) { const userRoles = yield actions.receiveUserRoles( '/matt-watson/secure-blocks/v1/user-roles/' ); return actions.setUserRoles( userRoles ); }, }, } ); ``` I've updated my tutorial: <https://mwatson.co.uk/working-with-gutenberg-and-the-wordpress-rest-api/>
311,437
<p>I'm having an issue selecting a page. </p> <p>There are guides that tell you how to find the page ID and I just couldn't find it in the admin panel to figure out what the page ID is. If only there was a way to search by slug in the admin panel that would be great.</p> <p>the other way was to look at the elements which worked beautifully for me. </p> <p>I used that and that worked great!</p> <pre><code>$classes = get_body_class(); if (in_array('page-magazine', $classes)).. </code></pre> <p>Unfortunately I was told that this isn't good practice and got rejected. </p> <p>Could anybody suggest a better way to target a specific page?</p>
[ { "answer_id": 311439, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>From <a href=\"https://codex.wordpress.org/Template_Tags/get_posts#Get_a_post_by_its_slug\" rel=\"nofollow noreferrer\">WordPress Codex Get Posts</a>.</p>\n\n<pre><code>&lt;?php\n$the_slug = 'my_slug';\n$args = array(\n 'name' =&gt; $the_slug,\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'numberposts' =&gt; 1\n);\n$my_posts = get_posts($args);\nif( $my_posts ) :\n echo 'ID on the first post found ' . $my_posts[0]-&gt;ID;\nendif;\n?&gt;\n</code></pre>\n\n<p>That way you can get a post or page by its slug.</p>\n" }, { "answer_id": 311445, "author": "Rick Hellewell", "author_id": 29416, "author_profile": "https://wordpress.stackexchange.com/users/29416", "pm_score": 1, "selected": false, "text": "<p>My understanding of your question is that you want to figure out the ID of a post/page on the Admin Post/Pages list.</p>\n\n<p>On the Admin Posts (or Pages) screen, if you hover over the post's name (or one of the links), you will see an ID in the linked URL. </p>\n\n<p>There are plugins that will add an \"ID\" column to the post list. One is Reveal ID <a href=\"https://wordpress.org/plugins/reveal-ids-for-wp-admin-25/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/reveal-ids-for-wp-admin-25/</a>. That's the easiest way, although it requires a plugin.</p>\n" }, { "answer_id": 311447, "author": "PepperAddict", "author_id": 147639, "author_profile": "https://wordpress.stackexchange.com/users/147639", "pm_score": 0, "selected": false, "text": "<p>I may not have been clear with my question and I apologize. \nI mainly just wanted to target the page in anyway I can whether it's by slug, ID, etc. I wasn't able to get the page ID the admin way because I couldn't find it in the page list. </p>\n\n<p>I discovered another way to target the specific page and I hope that it gets approved. </p>\n\n<p>In function.php </p>\n\n<pre><code>function slug_name() {\n $page_slug = trim( $_SERVER[\"REQUEST_URI\"] , '/' );\n return $page_slug;\n}\n</code></pre>\n\n<p>And then in header.php I just use an if statement to see if it matches with magazine.</p>\n\n<pre><code>if (slug_name() == 'magazine') {...}\n</code></pre>\n\n<p>Hopefully this one isn't too dirty but it does the job just like the class search one. </p>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311437", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147639/" ]
I'm having an issue selecting a page. There are guides that tell you how to find the page ID and I just couldn't find it in the admin panel to figure out what the page ID is. If only there was a way to search by slug in the admin panel that would be great. the other way was to look at the elements which worked beautifully for me. I used that and that worked great! ``` $classes = get_body_class(); if (in_array('page-magazine', $classes)).. ``` Unfortunately I was told that this isn't good practice and got rejected. Could anybody suggest a better way to target a specific page?
From [WordPress Codex Get Posts](https://codex.wordpress.org/Template_Tags/get_posts#Get_a_post_by_its_slug). ``` <?php $the_slug = 'my_slug'; $args = array( 'name' => $the_slug, 'post_type' => 'post', 'post_status' => 'publish', 'numberposts' => 1 ); $my_posts = get_posts($args); if( $my_posts ) : echo 'ID on the first post found ' . $my_posts[0]->ID; endif; ?> ``` That way you can get a post or page by its slug.
311,438
<p>I have the following function inside an existing plugin:</p> <pre><code>public static function init() { add_filter( 'wcs_view_subscription_actions', __CLASS__ . '::add_edit_address_subscription_action', 10, 2 ); } public static function add_edit_address_subscription_action( $actions, $subscription ) { if ( $subscription-&gt;needs_shipping_address() &amp;&amp; $subscription-&gt;has_status( array( 'active', 'on-hold' ) ) ) { $actions['change_address'] = array( 'url' =&gt; add_query_arg( array( 'subscription' =&gt; $subscription-&gt;get_id() ), wc_get_endpoint_url( 'edit-address', 'shipping' ) ), 'name' =&gt; __( 'Change Address', 'woocommerce-subscriptions' ), ); } return $actions; } </code></pre> <p>I am trying to modify this, so that I can add something to the <code>$actions</code> array. Is this possible without modifying the plugin directly, can I do it by filtering in the <code>functions.php</code> file?</p>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311438", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/10247/" ]
I have the following function inside an existing plugin: ``` public static function init() { add_filter( 'wcs_view_subscription_actions', __CLASS__ . '::add_edit_address_subscription_action', 10, 2 ); } public static function add_edit_address_subscription_action( $actions, $subscription ) { if ( $subscription->needs_shipping_address() && $subscription->has_status( array( 'active', 'on-hold' ) ) ) { $actions['change_address'] = array( 'url' => add_query_arg( array( 'subscription' => $subscription->get_id() ), wc_get_endpoint_url( 'edit-address', 'shipping' ) ), 'name' => __( 'Change Address', 'woocommerce-subscriptions' ), ); } return $actions; } ``` I am trying to modify this, so that I can add something to the `$actions` array. Is this possible without modifying the plugin directly, can I do it by filtering in the `functions.php` file?
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,451
<p>Hi Ive uploaded a WP site onto a new server updated the DB and can get into the backend and even see the homepge. However, all the links are messed up.</p> <p>I wasnt able to change the URL in the settings prior to moving, it was all grayed out. Here is the error message</p> <pre><code>Requested URL http://mysite-site3.itempurl.com:80/tests/ Physical Path h:\root\home\mysite\www\site3\tests\ </code></pre> <p>is this where the problem is? How would I fix?</p>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311451", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/138551/" ]
Hi Ive uploaded a WP site onto a new server updated the DB and can get into the backend and even see the homepge. However, all the links are messed up. I wasnt able to change the URL in the settings prior to moving, it was all grayed out. Here is the error message ``` Requested URL http://mysite-site3.itempurl.com:80/tests/ Physical Path h:\root\home\mysite\www\site3\tests\ ``` is this where the problem is? How would I fix?
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,468
<p>Is it possible to edit my site's header with a page-builder plugin, such as Page Builder, Elementor, or Gutenberg? I don't want to be stuck in the constraints of the theme and/or Wordpress's idea of how a header should be structured. </p> <p>I essentially just want to define a block section either above and/or below the menu that appears on every site page. </p>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/14
[ "https://wordpress.stackexchange.com/questions/311468", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/127125/" ]
Is it possible to edit my site's header with a page-builder plugin, such as Page Builder, Elementor, or Gutenberg? I don't want to be stuck in the constraints of the theme and/or Wordpress's idea of how a header should be structured. I essentially just want to define a block section either above and/or below the menu that appears on every site page.
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,479
<p>I've read <a href="https://wordpress.stackexchange.com/questions/120259/running-a-python-script-within-wordpress">this question</a> (and many more web pages) in order to figure out how to run a simple python script via a Wordpress plugin.</p> <p>However, I couldn't do it: I always get a "Blank" output.</p> <p>No errors were displayed.</p> <p><em>How can I execute a python function via Wordpress plugin?</em></p>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/15
[ "https://wordpress.stackexchange.com/questions/311479", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148751/" ]
I've read [this question](https://wordpress.stackexchange.com/questions/120259/running-a-python-script-within-wordpress) (and many more web pages) in order to figure out how to run a simple python script via a Wordpress plugin. However, I couldn't do it: I always get a "Blank" output. No errors were displayed. *How can I execute a python function via Wordpress plugin?*
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,492
<p>I am creating a directory and have a custom post type called "listings". </p> <p>I want to display a grid of "Most viewed" listings as well as "Highest rated" listings on my homepage and throughout the website. </p> <p>I am really not sure how to do this. </p>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/15
[ "https://wordpress.stackexchange.com/questions/311492", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148759/" ]
I am creating a directory and have a custom post type called "listings". I want to display a grid of "Most viewed" listings as well as "Highest rated" listings on my homepage and throughout the website. I am really not sure how to do this.
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,547
<p>I'm created two themes <em>(light &amp; dark)</em> but I'm not sure how to set cookies so the theme will remain constant when the user navigates from page-to-page or comes back to the site next week. Is there a simple script I can add to my existing code?</p> <p><b>HTML</b></p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;link id="lightTheme" rel="stylesheet" type="text/css" href="styleSheetLightTheme.css"&gt; &lt;link id="darkTheme" rel="alternate stylesheet" type="text/css" href="styleSheetDarkTheme.css"&gt; &lt;script&gt; function darkTheme() { var theme = document.getElementById('lightTheme'); theme.href = "styleSheetDarkTheme.css"; } function lightTheme() { var theme = document.getElementById('lightTheme'); theme.href = "styleSheetLightTheme.css"; } &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;a href="#" onClick="darkTheme(); return false;"&gt;Dark Theme&lt;/a&gt; | &lt;a href="#" onClick="lightTheme(); return false;"&gt;Light Theme&lt;/a&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p><b>styleSheetDarkTheme.css</b></p> <pre><code>body {background-color: #333; font-family: verdana; color: #ccc;} a:link, a:visited, a:active {color: #fff; text-decoration: none;} a:hover {color: #0ff;} </code></pre> <p><b>styleSheetLightTheme.css</b></p> <pre><code>body {background-color: #eee; font-family: verdana; color: #333;} a:link, a:visited, a:active {color: #000; text-decoration: none;} a:hover {color: #0ff;} </code></pre>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/15
[ "https://wordpress.stackexchange.com/questions/311547", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148791/" ]
I'm created two themes *(light & dark)* but I'm not sure how to set cookies so the theme will remain constant when the user navigates from page-to-page or comes back to the site next week. Is there a simple script I can add to my existing code? **HTML** ``` <html> <head> <link id="lightTheme" rel="stylesheet" type="text/css" href="styleSheetLightTheme.css"> <link id="darkTheme" rel="alternate stylesheet" type="text/css" href="styleSheetDarkTheme.css"> <script> function darkTheme() { var theme = document.getElementById('lightTheme'); theme.href = "styleSheetDarkTheme.css"; } function lightTheme() { var theme = document.getElementById('lightTheme'); theme.href = "styleSheetLightTheme.css"; } </script> </head> <body> <a href="#" onClick="darkTheme(); return false;">Dark Theme</a> | <a href="#" onClick="lightTheme(); return false;">Light Theme</a> </body> </html> ``` **styleSheetDarkTheme.css** ``` body {background-color: #333; font-family: verdana; color: #ccc;} a:link, a:visited, a:active {color: #fff; text-decoration: none;} a:hover {color: #0ff;} ``` **styleSheetLightTheme.css** ``` body {background-color: #eee; font-family: verdana; color: #333;} a:link, a:visited, a:active {color: #000; text-decoration: none;} a:hover {color: #0ff;} ```
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,550
<p>I need to expand on this discussion <a href="https://wordpress.stackexchange.com/questions/76802/redirect-entire-website-to-a-single-page">Redirect entire website to a single page</a> to include two pages rather than one.</p> <p>On this site, I need two pages to be live and all others to redirect to the home page.</p> <p><a href="http://prairiebrand.com/" rel="nofollow noreferrer">http://prairiebrand.com/</a></p> <p>This is the code I'm trying and I get a perpetual redirect.</p> <pre><code>add_action( 'template_redirect', 'wpse_76802_goodbye_redirect' ); function wpse_76802_goodbye_redirect() { if (( ! is_page( 16372 ) ) || ( ! is_page( 16384 ) )) { wp_redirect( esc_url_raw( home_url( 'index.php?page_id=16372' ), 301 ) ); exit; } } </code></pre>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/15
[ "https://wordpress.stackexchange.com/questions/311550", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17301/" ]
I need to expand on this discussion [Redirect entire website to a single page](https://wordpress.stackexchange.com/questions/76802/redirect-entire-website-to-a-single-page) to include two pages rather than one. On this site, I need two pages to be live and all others to redirect to the home page. <http://prairiebrand.com/> This is the code I'm trying and I get a perpetual redirect. ``` add_action( 'template_redirect', 'wpse_76802_goodbye_redirect' ); function wpse_76802_goodbye_redirect() { if (( ! is_page( 16372 ) ) || ( ! is_page( 16384 ) )) { wp_redirect( esc_url_raw( home_url( 'index.php?page_id=16372' ), 301 ) ); exit; } } ```
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,558
<p>I got a problem with value = 0 for meta_query checkbox field:</p> <pre><code>$args = [ 'post_type' =&gt; 'post', 'post_status' =&gt; 'publish', 'posts_per_page' =&gt; - 1, 'meta_query' =&gt; array( array( 'key' =&gt; 'test_field', 'value' =&gt; 0, 'compare' =&gt; 'LIKE', ), ), ]; </code></pre> <p>This code works fine if value is 2,3 etc. But when I set meta_query value to 0 or 1 it works wrong and i get all posts which has not empty test_field in post.</p> <p>How can i got only posts with value = 0 or 1? i have tried change compare to IN or = but its not words for checkbox fields</p>
[ { "answer_id": 311440, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 4, "selected": true, "text": "<p>You can simply use the same filter with <a href=\"https://developer.wordpress.org/reference/functions/add_filter/#parameters\" rel=\"noreferrer\">a lower or higher priority parameter</a> to make the appropriate changes to the <code>$actions</code> array. That way you may create a small custom plugin (or modify the theme's <code>functions.php</code> file), without having to modify the existing plugin directly.</p>\n\n<p>For example: if you want your custom code to execute after <code>add_edit_address_subscription_action</code> function, then use a bigger priority argument (lower priority) to the <code>wcs_view_subscription_actions</code> filter.</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 );\n\nfunction wpse_custom_action_after( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed after add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n\n<p>On the other hand, if you want your custom code to execute before <code>add_edit_address_subscription_action</code> function, then use a smaller priority argument (higher priority).</p>\n\n<p>Sample CODE (use this as part of a custom plugin or in your theme's <code>functions.php</code> file):</p>\n\n<pre><code>// original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation\nadd_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); \nfunction wpse_custom_action_before( $actions, $subscription ) {\n // your custom changes to $actions array HERE\n // this will be executed before add_edit_address_subscription_action function \n return $actions;\n}\n</code></pre>\n" }, { "answer_id": 311441, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>Yes, you can change <code>$actions</code> array in <code>functions.php</code> with your own function. </p>\n\n<pre><code>function your_function_name( $actions, $subscription ) {\n // here you can modify $actions array\n // \n return $actions;\n}\n\nadd_filter( 'wcs_view_subscription_actions', 'your_function_name', 15, 2 );\n</code></pre>\n" } ]
2018/08/15
[ "https://wordpress.stackexchange.com/questions/311558", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148797/" ]
I got a problem with value = 0 for meta\_query checkbox field: ``` $args = [ 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => - 1, 'meta_query' => array( array( 'key' => 'test_field', 'value' => 0, 'compare' => 'LIKE', ), ), ]; ``` This code works fine if value is 2,3 etc. But when I set meta\_query value to 0 or 1 it works wrong and i get all posts which has not empty test\_field in post. How can i got only posts with value = 0 or 1? i have tried change compare to IN or = but its not words for checkbox fields
You can simply use the same filter with [a lower or higher priority parameter](https://developer.wordpress.org/reference/functions/add_filter/#parameters) to make the appropriate changes to the `$actions` array. That way you may create a small custom plugin (or modify the theme's `functions.php` file), without having to modify the existing plugin directly. For example: if you want your custom code to execute after `add_edit_address_subscription_action` function, then use a bigger priority argument (lower priority) to the `wcs_view_subscription_actions` filter. Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 11 will make sure that this function executes after the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_after', 11, 2 ); function wpse_custom_action_after( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed after add_edit_address_subscription_action function return $actions; } ``` On the other hand, if you want your custom code to execute before `add_edit_address_subscription_action` function, then use a smaller priority argument (higher priority). Sample CODE (use this as part of a custom plugin or in your theme's `functions.php` file): ``` // original filter uses priority 10, so priority 9 will make sure that this function executes before the original implementation add_filter( 'wcs_view_subscription_actions', 'wpse_custom_action_before', 9, 2 ); function wpse_custom_action_before( $actions, $subscription ) { // your custom changes to $actions array HERE // this will be executed before add_edit_address_subscription_action function return $actions; } ```
311,564
<p>how can i achieve a front end form with preview option to create custom post based on the input? I want it done without any plugin. A simple example will help a lot. <hr> This is not a ACF question but ACF is having a front end form functionality but does not have preview function. </p> <p>Is it possible to get the id for form being filled so that it can be passed to </p> <pre><code>get_preview_post_link( int|WP_Post $post = null, array $query_args = array(), string $preview_link = '' ) </code></pre> <p>It tried get the get_the_ID() but it add's the id of page where form is placed. Also the id of the page get generated after form field is generated.</p> <p>The form is for registered and logged in users. May be if i am able to get a solution to get the id of the post that form generates i will be good position to go further.But the problem is that form generates ID after submission so i can't pass to get_preview_post_link()</p> <p>Thanks </p>
[ { "answer_id": 311783, "author": "Serkan Algur", "author_id": 23042, "author_profile": "https://wordpress.stackexchange.com/users/23042", "pm_score": 1, "selected": false, "text": "<p>You need to create post as draft for preview. You can use this form, function and ajax script for this. </p>\n\n<p>First standart form for new post;</p>\n\n<pre><code>&lt;form method=\"post\" id=\"new_post_form\"&gt;\n &lt;input type=\"text\" name=\"post_title\" id=\"title\" /&gt;\n &lt;?php\n /**\n * Simple editor for test reasons\n */ \n wp_editor( '', 'post_content' );\n ?&gt;\n &lt;input type=\"hidden\" name=\"author_id\" value=\"&lt;?php echo get_current_user_id(); ?&gt;\" /&gt;\n &lt;input type=\"text\" name=\"security\" value=\"&lt;?php echo wp_create_nonce( \"ajax_securiy_nonce\" ); ?&gt;\"&gt;\n &lt;input type=\"hidden\" name=\"action\" value=\"post_new_thing\"&gt;\n &lt;input type=\"submit\" id=\"submit_preview\" value=\"Submit &amp; Preview\" /&gt;\n&lt;/form&gt;\n</code></pre>\n\n<p>We will use ajax for posting. So you need an ajax PHP function for this. You can use this function in your <code>functions.php</code> </p>\n\n<pre><code>function add_header_ajax_url(){\n echo '&lt;script type=\"text/javascript\"&gt;var ajaxurl = \"&lt;?php echo admin_url(\"admin-ajax.php\"); ?&gt;\";&lt;/script&gt;';\n}\n\nadd_action( 'wp_head', 'add_header_ajax_url');\n\nadd_action( 'wp_ajax_post_new_thing', 'post_new_thing' );\n\nfunction post_new_thing() {\n /**\n * Post new for post type\n */\n check_ajax_referer( 'ajax_securiy_nonce', 'security' );\n\n $title = sanitize_text_field( $_POST['post_title'] );\n $content = sanitize_text_field( $_POST['post_content'] );\n $author_id = sanitize_text_field( $_POST['author_id'] );\n\n $args = array(\n 'post_title' =&gt; $title,\n 'post_content' =&gt; $content,\n 'post_type' =&gt; 'post',\n 'author' =&gt; $author_id,\n 'post_status' =&gt; 'draft',\n );\n\n $posts = wp_insert_post( $args );\n\n\n if( is_wp_error( $posts ) ){\n echo json_encode( $posts-&gt;get_error_messages() );\n } else {\n if ( !function_exists( 'get_preview_post_link' ) ) { \n require_once ABSPATH . WPINC . '/link-template.php'; \n } \n $post_preview = get_preview_post_link($posts);\n echo $post_preview;\n }\n wp_die();\n}\n</code></pre>\n\n<p>This function returns preview link. Also create a post with status as draft. We will force return function to open preview in new tab. Use functions where you want (probably in footer).</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\n jQuery(document).ready(function($){\n $('#submit_preview').submit(function(e){\n $.ajax({\n type: 'post',\n url : ajaxurl,\n data : $('#new_post_form').serialize(),\n success : function(data){\n window.open(data,'_blank');\n }\n });\n e.preventDefault();\n });\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>This codes should work as expected. Comment me if code works or not.</p>\n" }, { "answer_id": 311784, "author": "Aurovrata", "author_id": 52120, "author_profile": "https://wordpress.stackexchange.com/users/52120", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>how can i achieve a front end form with preview option to create custom post based on the input? I want it done without any plugin. </p>\n</blockquote>\n\n<p>without a plugin its not possible unless you're going to do a lot of custom coding which is equivalent to getting a plugin.</p>\n\n<p>The only way you can achieve this without using a plugin is to use the post creation/preview mechanism already available in WP, that is the admin Dashboard. Use a plugin such as <a href=\"https://wordpress.org/plugins/adminimize/\" rel=\"nofollow noreferrer\">Adminimize</a> to fine tune your user's privileges or make a new custom role for them, allowing them to create new posts and review them from the backend dashboard but limiting/removing other dashboard menu items so they only have access to what they need.</p>\n" }, { "answer_id": 312022, "author": "Nathan Powell", "author_id": 27196, "author_profile": "https://wordpress.stackexchange.com/users/27196", "pm_score": 0, "selected": false, "text": "<p>Choose what you think is ideal for the form your after first. Then create it using the the Plugin API of WordPress, or learn the language of those available. Doing a search fo WordPress Forms on Google can be helpful if trying to decide on an API.</p>\n\n<p>There are many, so decide for yourself which is meant for you.</p>\n" }, { "answer_id": 312346, "author": "filipecsweb", "author_id": 84657, "author_profile": "https://wordpress.stackexchange.com/users/84657", "pm_score": 3, "selected": true, "text": "<p>There are many ways you could use to reach your goal. Here's one...</p>\n\n<p><strong>Steps:</strong></p>\n\n<ol>\n<li>Create a shortcode that renders the form.</li>\n<li>Create and enqueue a JavaScript file that handles the form submission.</li>\n<li>Create PHP function for creating/updating Post/Custom Post.</li>\n</ol>\n\n<p><strong>In your functions.php:</strong></p>\n\n<pre><code>/**\n * @return string $html HTML form.\n */\nfunction shortcode__new_post_form() {\n /**\n * @var WP_User $current_user\n */\n $current_user = $GLOBALS['current_user'];\n\n ob_start(); ?&gt;\n &lt;form action=\"\" id=\"form-new-post\"&gt;\n &lt;fieldset&gt;\n &lt;legend&gt;NEW AWESOME POST&lt;/legend&gt;\n &lt;div class=\"form-group\"&gt;\n &lt;input type=\"text\" class=\"form-control\" name=\"post_title\" required/&gt;\n &lt;/div&gt;\n &lt;input type=\"hidden\" name=\"ID\" value=\"\"/&gt;\n &lt;input type=\"hidden\" name=\"post_author\" value=\"&lt;?php echo $current_user-&gt;ID; ?&gt;\"/&gt;\n &lt;button type=\"submit\"\n class=\"submit\"\n data-is-updated=\"false\"\n data-is-update-text=\"UPDATE\"&gt;CREATE\n &lt;/button&gt;\n &lt;/fieldset&gt;\n &lt;a href=\"\"\n class=\"preview-link\"\n target=\"_blank\"\n style=\"display: none;\"\n rel=\"nofollow\"&gt;Preview Link&lt;/a&gt;\n &lt;/form&gt;\n &lt;?php\n $html = ob_get_clean();\n\n return $html;\n}\n\nfunction script__new_post_form() {\n wp_enqueue_script(\n 'new-post-form',\n // Insert here your JavaScript file URL,\n array( 'jquery' ),\n '1.0.0',\n true\n );\n\n wp_localize_script(\n 'new-post-form',\n 'localized_new_post_form',\n array(\n 'admin_ajax_url' =&gt; admin_url( 'admin-ajax.php' ),\n )\n );\n}\n\nfunction maybe_insert_new_post() {\n /**\n * @var array $r Initialize response variable.\n */\n $r = array(\n 'error' =&gt; '', // Error message.\n 'html' =&gt; '', // Any message/HTML you want to output to the logged in user.\n 'preview_link' =&gt; '', // Preview link URL.\n 'post' =&gt; '' // The created/updated post.\n );\n\n /**\n * @link https://developer.wordpress.org/reference/functions/wp_insert_post/\n */\n $postarr = array(\n 'ID' =&gt; '', // If ID stays empty the post will be created.\n 'post_author' =&gt; '',\n 'post_title' =&gt; 'My name is Optimus Prime',\n 'post_status' =&gt; 'draft',\n 'post_type' =&gt; 'post',\n 'meta_input' =&gt; array( // Delete this line if you won't use it!\n 'your_NON_acf_meta_field_key' =&gt; 'your_NON_acf_meta_field_value'\n )\n );\n\n parse_str( $_POST['form_data'], $form_data );\n\n $postarr = array_merge( $postarr, $form_data );\n\n /**\n * wp_insert_post can either create posts or update existing ones, if ID is passed!\n *\n * @link https://developer.wordpress.org/reference/functions/wp_insert_post/\n *\n * @param array $postarr An array of elements that make up a post to update or insert.\n * @param bool $wp_error Whether to return a WP_Error on failure.\n *\n * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure.\n */\n $new_post = wp_insert_post(\n $postarr,\n true\n );\n\n // Post was not created/updated, so let's output the error message.\n if ( is_wp_error( $new_post ) ) {\n $r['error'] = $new_post-&gt;get_error_message();\n\n echo json_encode( $r );\n\n exit;\n }\n\n $post_id = $new_post; // Just for reference.\n\n /**\n * To save ACF fields use update_field() function. It doesn't matter if it's text field, repeater field, etc.\n * Make sure the field exists in admin area.\n * Use update_field() as many times as you want.\n *\n * @link https://www.advancedcustomfields.com/resources/update_field/\n */\n update_field( 'your_acf_meta_key', 'field_value', $post_id );\n// update_field( 'your_acf_meta_key', 'field_value', $post_id );\n// update_field( 'your_acf_meta_key', 'field_value', $post_id );\n\n /**\n * @link https://developer.wordpress.org/reference/functions/get_preview_post_link/\n */\n $preview_link = get_preview_post_link( $post_id );\n\n if ( $preview_link ) {\n $r['preview_link'] = $preview_link;\n }\n\n // Gets post info in array format as it's easier to debug via console if needed.\n $post_array = get_post( $post_id, ARRAY_A );\n\n if ( $post_array ) {\n $r['post'] = $post_array;\n }\n\n echo json_encode( $r );\n\n exit;\n}\n\n// Ads shortcode so you can use the form anywhere you want.\nadd_shortcode( 'new_post_form', 'shortcode__new_post_form' );\n\n// Use wp_enqueue_scripts action hook so you can correctly localize the script with admin ajax URL.\nadd_action( 'wp_enqueue_scripts', 'script__new_post_form' );\n\n// Prefix 'wp_ajax_' is mandatory.\nadd_action( 'wp_ajax_new_post', 'maybe_insert_new_post' );\n</code></pre>\n\n<p><strong>Create a JavaScript file and write in it (don't forget to put its URL in your functions.php):</strong></p>\n\n<pre><code>(function ($) {\n\n var el_form = $('#form-new-post'),\n el_form_submit = $('.submit', el_form);\n\n // Fires when the form is submitted.\n el_form.on('submit', function (e) {\n e.preventDefault();\n\n el_form_submit.attr('disabled', 'disabled');\n\n new_post();\n });\n\n // Ajax request.\n function new_post() {\n $.ajax({\n url: localized_new_post_form.admin_ajax_url,\n type: 'POST',\n dataType: 'json',\n data: {\n action: 'new_post', // Set action without prefix 'wp_ajax_'.\n form_data: el_form.serialize()\n },\n cache: false\n }).done(function (r) {\n if (r.post !== '' &amp;&amp; r.preview_link !== '') {\n $('[name=\"ID\"]', el_form).attr('value', r.post.ID);\n $('.preview-link', el_form)\n .attr('href', r.preview_link)\n .show();\n el_form_submit.attr('data-is-updated', 'true');\n el_form_submit.text(el_form_submit.data('is-update-text'));\n }\n\n el_form_submit.removeAttr('disabled');\n });\n }\n\n // Used to trigger/simulate post submission without user action.\n function trigger_new_post() {\n el_form.trigger('submit');\n }\n\n // Sets interval so the post the can be updated automatically provided that it was already created.\n setInterval(function () {\n if (el_form_submit.attr('data-is-updated') === 'false') {\n return false;\n }\n\n trigger_new_post();\n }, 5000); // Set to 5 seconds.\n\n})(jQuery);\n</code></pre>\n\n<p>Now, create a new page and insert the shortcode <code>[new_post_form]</code> in it. Open the page and test your form.</p>\n\n<p><strong>If it works for you, please accept my answer as your solution.</strong></p>\n" } ]
2018/08/15
[ "https://wordpress.stackexchange.com/questions/311564", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/-1/" ]
how can i achieve a front end form with preview option to create custom post based on the input? I want it done without any plugin. A simple example will help a lot. --- This is not a ACF question but ACF is having a front end form functionality but does not have preview function. Is it possible to get the id for form being filled so that it can be passed to ``` get_preview_post_link( int|WP_Post $post = null, array $query_args = array(), string $preview_link = '' ) ``` It tried get the get\_the\_ID() but it add's the id of page where form is placed. Also the id of the page get generated after form field is generated. The form is for registered and logged in users. May be if i am able to get a solution to get the id of the post that form generates i will be good position to go further.But the problem is that form generates ID after submission so i can't pass to get\_preview\_post\_link() Thanks
There are many ways you could use to reach your goal. Here's one... **Steps:** 1. Create a shortcode that renders the form. 2. Create and enqueue a JavaScript file that handles the form submission. 3. Create PHP function for creating/updating Post/Custom Post. **In your functions.php:** ``` /** * @return string $html HTML form. */ function shortcode__new_post_form() { /** * @var WP_User $current_user */ $current_user = $GLOBALS['current_user']; ob_start(); ?> <form action="" id="form-new-post"> <fieldset> <legend>NEW AWESOME POST</legend> <div class="form-group"> <input type="text" class="form-control" name="post_title" required/> </div> <input type="hidden" name="ID" value=""/> <input type="hidden" name="post_author" value="<?php echo $current_user->ID; ?>"/> <button type="submit" class="submit" data-is-updated="false" data-is-update-text="UPDATE">CREATE </button> </fieldset> <a href="" class="preview-link" target="_blank" style="display: none;" rel="nofollow">Preview Link</a> </form> <?php $html = ob_get_clean(); return $html; } function script__new_post_form() { wp_enqueue_script( 'new-post-form', // Insert here your JavaScript file URL, array( 'jquery' ), '1.0.0', true ); wp_localize_script( 'new-post-form', 'localized_new_post_form', array( 'admin_ajax_url' => admin_url( 'admin-ajax.php' ), ) ); } function maybe_insert_new_post() { /** * @var array $r Initialize response variable. */ $r = array( 'error' => '', // Error message. 'html' => '', // Any message/HTML you want to output to the logged in user. 'preview_link' => '', // Preview link URL. 'post' => '' // The created/updated post. ); /** * @link https://developer.wordpress.org/reference/functions/wp_insert_post/ */ $postarr = array( 'ID' => '', // If ID stays empty the post will be created. 'post_author' => '', 'post_title' => 'My name is Optimus Prime', 'post_status' => 'draft', 'post_type' => 'post', 'meta_input' => array( // Delete this line if you won't use it! 'your_NON_acf_meta_field_key' => 'your_NON_acf_meta_field_value' ) ); parse_str( $_POST['form_data'], $form_data ); $postarr = array_merge( $postarr, $form_data ); /** * wp_insert_post can either create posts or update existing ones, if ID is passed! * * @link https://developer.wordpress.org/reference/functions/wp_insert_post/ * * @param array $postarr An array of elements that make up a post to update or insert. * @param bool $wp_error Whether to return a WP_Error on failure. * * @return int|WP_Error The post ID on success. The value 0 or WP_Error on failure. */ $new_post = wp_insert_post( $postarr, true ); // Post was not created/updated, so let's output the error message. if ( is_wp_error( $new_post ) ) { $r['error'] = $new_post->get_error_message(); echo json_encode( $r ); exit; } $post_id = $new_post; // Just for reference. /** * To save ACF fields use update_field() function. It doesn't matter if it's text field, repeater field, etc. * Make sure the field exists in admin area. * Use update_field() as many times as you want. * * @link https://www.advancedcustomfields.com/resources/update_field/ */ update_field( 'your_acf_meta_key', 'field_value', $post_id ); // update_field( 'your_acf_meta_key', 'field_value', $post_id ); // update_field( 'your_acf_meta_key', 'field_value', $post_id ); /** * @link https://developer.wordpress.org/reference/functions/get_preview_post_link/ */ $preview_link = get_preview_post_link( $post_id ); if ( $preview_link ) { $r['preview_link'] = $preview_link; } // Gets post info in array format as it's easier to debug via console if needed. $post_array = get_post( $post_id, ARRAY_A ); if ( $post_array ) { $r['post'] = $post_array; } echo json_encode( $r ); exit; } // Ads shortcode so you can use the form anywhere you want. add_shortcode( 'new_post_form', 'shortcode__new_post_form' ); // Use wp_enqueue_scripts action hook so you can correctly localize the script with admin ajax URL. add_action( 'wp_enqueue_scripts', 'script__new_post_form' ); // Prefix 'wp_ajax_' is mandatory. add_action( 'wp_ajax_new_post', 'maybe_insert_new_post' ); ``` **Create a JavaScript file and write in it (don't forget to put its URL in your functions.php):** ``` (function ($) { var el_form = $('#form-new-post'), el_form_submit = $('.submit', el_form); // Fires when the form is submitted. el_form.on('submit', function (e) { e.preventDefault(); el_form_submit.attr('disabled', 'disabled'); new_post(); }); // Ajax request. function new_post() { $.ajax({ url: localized_new_post_form.admin_ajax_url, type: 'POST', dataType: 'json', data: { action: 'new_post', // Set action without prefix 'wp_ajax_'. form_data: el_form.serialize() }, cache: false }).done(function (r) { if (r.post !== '' && r.preview_link !== '') { $('[name="ID"]', el_form).attr('value', r.post.ID); $('.preview-link', el_form) .attr('href', r.preview_link) .show(); el_form_submit.attr('data-is-updated', 'true'); el_form_submit.text(el_form_submit.data('is-update-text')); } el_form_submit.removeAttr('disabled'); }); } // Used to trigger/simulate post submission without user action. function trigger_new_post() { el_form.trigger('submit'); } // Sets interval so the post the can be updated automatically provided that it was already created. setInterval(function () { if (el_form_submit.attr('data-is-updated') === 'false') { return false; } trigger_new_post(); }, 5000); // Set to 5 seconds. })(jQuery); ``` Now, create a new page and insert the shortcode `[new_post_form]` in it. Open the page and test your form. **If it works for you, please accept my answer as your solution.**
311,583
<p>I try to add auto increment post numbering by category. Like cat="myID" > post 1, post 2, post 3...</p> <p><a href="https://wordpress.stackexchange.com/questions/13083/display-post-number-not-post-id-number">Display post number not post ID number</a></p> <p>In find this solution, and use post_meta looks a good way. But this solution work only for all category. I try to change it like this, but it's doesn't work.</p> <pre><code>$querystr = "SELECT $wpdb-&gt;posts.* FROM $wpdb-&gt;posts WHERE $wpdb-&gt;posts.post_status = 'publish' AND $wpdb-&gt;posts.post_type = 'post' AND $wpdb-&gt;posts.post_cat = '35' ORDER BY $wpdb-&gt;posts.post_date ASC" </code></pre>
[ { "answer_id": 311585, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 0, "selected": false, "text": "<p>There's no field in wp_posts called \"post_cat\". </p>\n\n<p>Try \"post_category\" instead.</p>\n" }, { "answer_id": 311908, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>Add this code to <code>functions.php</code>. It should add meta value to posts from given category.<br>\nYou can use hardcoded category slug/ID, but maybe it would be better to store it in <code>options</code> table and allow to change from dashboard. </p>\n\n<p>Change \"ID\" / \"category_slug\" to your own.</p>\n\n<pre><code>/**\n * @param int $post_ID Post ID.\n * @param WP_Post $post_after Post object following the update.\n * @param WP_Post $post_before Post object before the update.\n */\nfunction updateNumbers($post_id, $post_after, $post_before) {\n global $wpdb;\n\n if ( $post_after-&gt;post_type != 'post' )\n return;\n\n $selected_cat_ID = 123; // &lt;-- ID of your category with numbering\n\n // -- select category ID by slug --\n // $selected_cat = 'category_slug';\n // $selected_cat_ID = get_terms(['slug' =&gt; 'category_slug', 'fields'=&gt; 'ids', 'taxonomy' =&gt; 'category', 'hide_empty' =&gt; false,]);\n // if ( !is_array($selected_cat_ID) || empty($selected_cat_ID) ) \n // return; \n // $selected_cat_ID = $selected_cat_ID[0];\n // -- end: select category ID by slug --\n\n $incr_number = get_post_meta($post_id, 'incr_number', true);\n\n //\n // get posts assigned to your category\n $query = \"SELECT p.id FROM {$wpdb-&gt;posts} p\"\n . \" LEFT JOIN {$wpdb-&gt;term_relationships} tr ON tr.object_id = p.id\"\n . \" LEFT JOIN {$wpdb-&gt;term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id\"\n . \" LEFT JOIN {$wpdb-&gt;terms} t ON t.term_id = tt.term_id\"\n . \" WHERE p.post_status = 'publish' AND p.post_type = 'post'\"\n // if you want use slug instead ID change \"AND t.term_id = %d\" to \"AND t.slug = %s\"\n . \" AND tt.taxonomy = 'category' AND t.term_id = %d\" \n . \" ORDER BY p.post_date ASC\";\n $ids = $wpdb-&gt;get_results( $wpdb-&gt;prepare($query, $selected_cat_ID), OBJECT );\n\n // is post assigned to category after update\n $in_category = false;\n $assigned_posts = [];\n\n foreach( $ids as $row ) {\n $assigned_posts[] = $row-&gt;id;\n if ( $row-&gt;id == $post_id )\n $in_category = true;\n }\n\n if ( !$in_category &amp;&amp; $incr_number === '' ) {\n //\n // after the update post is not in the category, before the update was not either\n return;\n }\n else if ($in_category &amp;&amp; $incr_number !== '' &amp;&amp; $post_before-&gt;post_date_gmt == $post_after-&gt;post_date_gmt ) {\n //\n // after the update, post is still in the category,\n // publish date has not changed,\n // numbering doesn't need to be changed\n return;\n }\n else if ( !$in_category &amp;&amp; $incr_number !== '' ) {\n //\n // post has he been removed from category\n delete_post_meta($post_id, 'incr_number');\n }\n\n // update numbering\n if ( !empty($assigned_posts) ) {\n $counts = 0;\n foreach( $assigned_posts as $pid )\n update_post_meta($pid, 'incr_number', ++$counts);\n }\n}\nadd_action( 'post_updated', 'updateNumbers', 10, 3);\n</code></pre>\n" } ]
2018/08/16
[ "https://wordpress.stackexchange.com/questions/311583", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148815/" ]
I try to add auto increment post numbering by category. Like cat="myID" > post 1, post 2, post 3... [Display post number not post ID number](https://wordpress.stackexchange.com/questions/13083/display-post-number-not-post-id-number) In find this solution, and use post\_meta looks a good way. But this solution work only for all category. I try to change it like this, but it's doesn't work. ``` $querystr = "SELECT $wpdb->posts.* FROM $wpdb->posts WHERE $wpdb->posts.post_status = 'publish' AND $wpdb->posts.post_type = 'post' AND $wpdb->posts.post_cat = '35' ORDER BY $wpdb->posts.post_date ASC" ```
Add this code to `functions.php`. It should add meta value to posts from given category. You can use hardcoded category slug/ID, but maybe it would be better to store it in `options` table and allow to change from dashboard. Change "ID" / "category\_slug" to your own. ``` /** * @param int $post_ID Post ID. * @param WP_Post $post_after Post object following the update. * @param WP_Post $post_before Post object before the update. */ function updateNumbers($post_id, $post_after, $post_before) { global $wpdb; if ( $post_after->post_type != 'post' ) return; $selected_cat_ID = 123; // <-- ID of your category with numbering // -- select category ID by slug -- // $selected_cat = 'category_slug'; // $selected_cat_ID = get_terms(['slug' => 'category_slug', 'fields'=> 'ids', 'taxonomy' => 'category', 'hide_empty' => false,]); // if ( !is_array($selected_cat_ID) || empty($selected_cat_ID) ) // return; // $selected_cat_ID = $selected_cat_ID[0]; // -- end: select category ID by slug -- $incr_number = get_post_meta($post_id, 'incr_number', true); // // get posts assigned to your category $query = "SELECT p.id FROM {$wpdb->posts} p" . " LEFT JOIN {$wpdb->term_relationships} tr ON tr.object_id = p.id" . " LEFT JOIN {$wpdb->term_taxonomy} tt ON tt.term_taxonomy_id = tr.term_taxonomy_id" . " LEFT JOIN {$wpdb->terms} t ON t.term_id = tt.term_id" . " WHERE p.post_status = 'publish' AND p.post_type = 'post'" // if you want use slug instead ID change "AND t.term_id = %d" to "AND t.slug = %s" . " AND tt.taxonomy = 'category' AND t.term_id = %d" . " ORDER BY p.post_date ASC"; $ids = $wpdb->get_results( $wpdb->prepare($query, $selected_cat_ID), OBJECT ); // is post assigned to category after update $in_category = false; $assigned_posts = []; foreach( $ids as $row ) { $assigned_posts[] = $row->id; if ( $row->id == $post_id ) $in_category = true; } if ( !$in_category && $incr_number === '' ) { // // after the update post is not in the category, before the update was not either return; } else if ($in_category && $incr_number !== '' && $post_before->post_date_gmt == $post_after->post_date_gmt ) { // // after the update, post is still in the category, // publish date has not changed, // numbering doesn't need to be changed return; } else if ( !$in_category && $incr_number !== '' ) { // // post has he been removed from category delete_post_meta($post_id, 'incr_number'); } // update numbering if ( !empty($assigned_posts) ) { $counts = 0; foreach( $assigned_posts as $pid ) update_post_meta($pid, 'incr_number', ++$counts); } } add_action( 'post_updated', 'updateNumbers', 10, 3); ```
311,624
<p>(WP Post Title)Malwarebytes Anti-Malware (Custom field value)3.5.1.2522</p> <p>How to add custome meta value in wordpress after wp post title in same hyperlink</p>
[ { "answer_id": 311634, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>It's possible to change displayed title in template file (e.g. content.php):</p>\n\n<pre><code>$custom_field = get_post_meta($post-&gt;ID, $custom_meta_key, true);\nif ( is_single() ) {\n the_title( '&lt;h1 class=\"entry-title\"&gt;', '&lt;/h1&gt;' );\n} elseif ( is_front_page() &amp;&amp; is_home() ) {\n the_title( '&lt;h3 class=\"entry-title\"&gt;&lt;a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\"&gt;',\n ' ' . $custom_field . '&lt;/a&gt;&lt;/h3&gt;' );\n} else {\n the_title( '&lt;h2 class=\"entry-title\"&gt;&lt;a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\"&gt;', \n ' ' . $custom_field . '&lt;/a&gt;&lt;/h2&gt;' );\n}\n</code></pre>\n\n<p>You can also use <code>the_title</code> filter hook (code goes to functions.php):</p>\n\n<pre><code>add_filter( 'the_title', 'modify_post_title' );\n\nfunction modify_post_title( $title ) {\n global $post;\n //\n // --- show on list and single post view\n // if ( $post-&gt;post_type == 'post' &amp;&amp; in_the_loop() ) {\n // --- show only in single post view\n // if ( is_singular() &amp;&amp; $post-&gt;post_type == 'post' &amp;&amp; in_the_loop() ) {\n\n // when to apply custom field suffix\n // --- when type is \"post\" and when it's not a single post view\n if ( !is_singular() &amp;&amp; $post-&gt;post_type == 'post' &amp;&amp; in_the_loop() ) {\n // $custom_field = get_post_meta($post-&gt;ID, $custom_meta_key, true);\n $title .= $custom_field;\n }\n return $title;\n}\n</code></pre>\n\n<p>It depends on what you want to achieve.</p>\n" }, { "answer_id": 311667, "author": "PROGOSTECH", "author_id": 148859, "author_profile": "https://wordpress.stackexchange.com/users/148859", "pm_score": 1, "selected": false, "text": "<p>It is a simple 3 step process:</p>\n\n<ol>\n<li>Look for your post title markup that should look something like:</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;h1&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;\n</code></pre>\n</blockquote>\n\n<ol start=\"2\">\n<li>Now, get your post custom meta value through:</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;?php $bannerContent = get_post_meta($post-&gt;ID, 'bannerContent', true); ?&gt;\n</code></pre>\n</blockquote>\n\n<ol start=\"3\">\n<li>Next add this value to your title where ever you need:</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;h1&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); echo $bannerContent; ?&gt;&lt;/a&gt;&lt;/h1&gt;\n</code></pre>\n</blockquote>\n\n<p>This is it. If you need any further assistance, please let us know!\nHappy coding</p>\n" }, { "answer_id": 311675, "author": "Techy solutions", "author_id": 148880, "author_profile": "https://wordpress.stackexchange.com/users/148880", "pm_score": 0, "selected": false, "text": "<p>add_filter( 'post_type_link', 'append_query_string', 10, 2 );\nfunction append_query_string( $url, $post ) \n{\n return $url.'?var_name='.get_post_meta($post->ID,'meta_key',true);\n}</p>\n" } ]
2018/08/16
[ "https://wordpress.stackexchange.com/questions/311624", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148823/" ]
(WP Post Title)Malwarebytes Anti-Malware (Custom field value)3.5.1.2522 How to add custome meta value in wordpress after wp post title in same hyperlink
It is a simple 3 step process: 1. Look for your post title markup that should look something like: > > > ``` > <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> > > ``` > > 2. Now, get your post custom meta value through: > > > ``` > <?php $bannerContent = get_post_meta($post->ID, 'bannerContent', true); ?> > > ``` > > 3. Next add this value to your title where ever you need: > > > ``` > <h1><a href="<?php the_permalink(); ?>"><?php the_title(); echo $bannerContent; ?></a></h1> > > ``` > > This is it. If you need any further assistance, please let us know! Happy coding
311,625
<p>I need to list all slug categories from a taxonomy portfolio_category. Like this:</p> <pre><code>the_terms( get_the_ID(), 'portfolio_category', '', ', ' ); </code></pre> <p>This returns categories from a single portfolio. I want to return just slug of this. </p>
[ { "answer_id": 311634, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 0, "selected": false, "text": "<p>It's possible to change displayed title in template file (e.g. content.php):</p>\n\n<pre><code>$custom_field = get_post_meta($post-&gt;ID, $custom_meta_key, true);\nif ( is_single() ) {\n the_title( '&lt;h1 class=\"entry-title\"&gt;', '&lt;/h1&gt;' );\n} elseif ( is_front_page() &amp;&amp; is_home() ) {\n the_title( '&lt;h3 class=\"entry-title\"&gt;&lt;a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\"&gt;',\n ' ' . $custom_field . '&lt;/a&gt;&lt;/h3&gt;' );\n} else {\n the_title( '&lt;h2 class=\"entry-title\"&gt;&lt;a href=\"' . esc_url( get_permalink() ) . '\" rel=\"bookmark\"&gt;', \n ' ' . $custom_field . '&lt;/a&gt;&lt;/h2&gt;' );\n}\n</code></pre>\n\n<p>You can also use <code>the_title</code> filter hook (code goes to functions.php):</p>\n\n<pre><code>add_filter( 'the_title', 'modify_post_title' );\n\nfunction modify_post_title( $title ) {\n global $post;\n //\n // --- show on list and single post view\n // if ( $post-&gt;post_type == 'post' &amp;&amp; in_the_loop() ) {\n // --- show only in single post view\n // if ( is_singular() &amp;&amp; $post-&gt;post_type == 'post' &amp;&amp; in_the_loop() ) {\n\n // when to apply custom field suffix\n // --- when type is \"post\" and when it's not a single post view\n if ( !is_singular() &amp;&amp; $post-&gt;post_type == 'post' &amp;&amp; in_the_loop() ) {\n // $custom_field = get_post_meta($post-&gt;ID, $custom_meta_key, true);\n $title .= $custom_field;\n }\n return $title;\n}\n</code></pre>\n\n<p>It depends on what you want to achieve.</p>\n" }, { "answer_id": 311667, "author": "PROGOSTECH", "author_id": 148859, "author_profile": "https://wordpress.stackexchange.com/users/148859", "pm_score": 1, "selected": false, "text": "<p>It is a simple 3 step process:</p>\n\n<ol>\n<li>Look for your post title markup that should look something like:</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;h1&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); ?&gt;&lt;/a&gt;&lt;/h1&gt;\n</code></pre>\n</blockquote>\n\n<ol start=\"2\">\n<li>Now, get your post custom meta value through:</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;?php $bannerContent = get_post_meta($post-&gt;ID, 'bannerContent', true); ?&gt;\n</code></pre>\n</blockquote>\n\n<ol start=\"3\">\n<li>Next add this value to your title where ever you need:</li>\n</ol>\n\n<blockquote>\n<pre><code>&lt;h1&gt;&lt;a href=\"&lt;?php the_permalink(); ?&gt;\"&gt;&lt;?php the_title(); echo $bannerContent; ?&gt;&lt;/a&gt;&lt;/h1&gt;\n</code></pre>\n</blockquote>\n\n<p>This is it. If you need any further assistance, please let us know!\nHappy coding</p>\n" }, { "answer_id": 311675, "author": "Techy solutions", "author_id": 148880, "author_profile": "https://wordpress.stackexchange.com/users/148880", "pm_score": 0, "selected": false, "text": "<p>add_filter( 'post_type_link', 'append_query_string', 10, 2 );\nfunction append_query_string( $url, $post ) \n{\n return $url.'?var_name='.get_post_meta($post->ID,'meta_key',true);\n}</p>\n" } ]
2018/08/16
[ "https://wordpress.stackexchange.com/questions/311625", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/94056/" ]
I need to list all slug categories from a taxonomy portfolio\_category. Like this: ``` the_terms( get_the_ID(), 'portfolio_category', '', ', ' ); ``` This returns categories from a single portfolio. I want to return just slug of this.
It is a simple 3 step process: 1. Look for your post title markup that should look something like: > > > ``` > <h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h1> > > ``` > > 2. Now, get your post custom meta value through: > > > ``` > <?php $bannerContent = get_post_meta($post->ID, 'bannerContent', true); ?> > > ``` > > 3. Next add this value to your title where ever you need: > > > ``` > <h1><a href="<?php the_permalink(); ?>"><?php the_title(); echo $bannerContent; ?></a></h1> > > ``` > > This is it. If you need any further assistance, please let us know! Happy coding
311,630
<p>I wonder if there exists a quick way to register custom background images as simple as we do with the custom headers.</p> <pre><code>$header_images = array( 'ferrari' =&gt; array( 'url' =&gt; get_template_directory_uri() . '/img/ferrari.jpg', 'thumbnail_url' =&gt; get_template_directory_uri() . '/img/ferrari.jpg', 'description' =&gt; 'Ferrari', ), 'harley-davidson' =&gt; array( 'url' =&gt; get_template_directory_uri() . '/img/harley-davidson.jpg', 'thumbnail_url' =&gt; get_template_directory_uri() . '/img/harley-davidson.jpg', 'description' =&gt; 'Harley Davidson', ), ); register_default_headers( $header_images ); </code></pre> <p>Google fetched me nothing but <a href="https://core.trac.wordpress.org/attachment/ticket/18623/18623.4.diff" rel="nofollow noreferrer">this</a>, couldn't get anything meaningful out of it. Is anyone doing this? Thoughts?</p>
[ { "answer_id": 311635, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 0, "selected": false, "text": "<p>You're correct, all plugins from wordpress.org <a href=\"https://developer.wordpress.org/plugins/wordpress-org/#requirements\" rel=\"nofollow noreferrer\">have to be GPLv2 or later</a></p>\n\n<blockquote>\n <p>Plugins must be compatible with the GNU General Public License v2 or later. If a license is not specified, code will be considered “GPLv2 or later.”</p>\n</blockquote>\n\n<p>If you don't see the licence outright, you can explore the plugins source code on the repo with</p>\n\n<pre><code>https://plugins.svn.wordpress.org/{plugin_slug}/trunk/\n</code></pre>\n\n<p>Where \"<code>{plugin_slug}</code>\" is the slug of your plugin, like <code>my-plugin</code>. You'll be looking for a file like <code>LICENCE.txt</code> or check out <code>readme.txt</code> there should be a <code>License: x</code> in the first few lines. Also the main plugin <code>.php</code> file (differs for each plugin, but usually shares the same name as the plugin slug) may mention the licence.</p>\n" }, { "answer_id": 311638, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You should ask your lawyer, never ask legal advice from random people on the net.</p>\n\n<p>Regardless of the legal question, it is rarely a smart idea to fork a plugin unless you understand that from that point forward it is your plugin. You can smartly use GIT to manage synchronizing when the original code updates, but the more changes you make to it, the harder it will become.</p>\n\n<p>This might not be a biggy for a 100 LOC plugin, but will be much harder to maintain if the plugin has 10k LOC. Foe example yoast right now has a new version at least every week, are you really going to merge the code bases every week? that is going to add an overhead to you developent process.</p>\n\n<p>Forking of plugin or theme should be the last thing on your mind regardless if its legal or not.</p>\n" } ]
2018/08/16
[ "https://wordpress.stackexchange.com/questions/311630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/67150/" ]
I wonder if there exists a quick way to register custom background images as simple as we do with the custom headers. ``` $header_images = array( 'ferrari' => array( 'url' => get_template_directory_uri() . '/img/ferrari.jpg', 'thumbnail_url' => get_template_directory_uri() . '/img/ferrari.jpg', 'description' => 'Ferrari', ), 'harley-davidson' => array( 'url' => get_template_directory_uri() . '/img/harley-davidson.jpg', 'thumbnail_url' => get_template_directory_uri() . '/img/harley-davidson.jpg', 'description' => 'Harley Davidson', ), ); register_default_headers( $header_images ); ``` Google fetched me nothing but [this](https://core.trac.wordpress.org/attachment/ticket/18623/18623.4.diff), couldn't get anything meaningful out of it. Is anyone doing this? Thoughts?
You should ask your lawyer, never ask legal advice from random people on the net. Regardless of the legal question, it is rarely a smart idea to fork a plugin unless you understand that from that point forward it is your plugin. You can smartly use GIT to manage synchronizing when the original code updates, but the more changes you make to it, the harder it will become. This might not be a biggy for a 100 LOC plugin, but will be much harder to maintain if the plugin has 10k LOC. Foe example yoast right now has a new version at least every week, are you really going to merge the code bases every week? that is going to add an overhead to you developent process. Forking of plugin or theme should be the last thing on your mind regardless if its legal or not.
311,657
<p>I'm trying to create an events page that lists events (custom post type) within the week. I'm having trouble properly selecting only the posts that have a 'start_date' that falls in the current week.</p> <p>Here is my code:</p> <pre><code> $day = date('w'); $week_start = date('d-m-Y', strtotime('-'. $day . ' days')); $week_end = date('d-m-Y', strtotime('+' . (6 - $day) . ' days')); $args = array( 'post_type' =&gt; 'hcc_events', 'order' =&gt; 'ASC', 'meta_key' =&gt; 'start_date', 'orderby' =&gt; 'meta_value', 'posts_per_page' =&gt; -1, 'meta_query' =&gt; array( 'relation' =&gt; 'AND', array( 'key' =&gt; 'start_date', 'value' =&gt; $week_start, 'compare' =&gt; '&gt;=', 'type' =&gt; 'DATE' ), array( 'key' =&gt; 'start_date', 'value' =&gt; $week_end, 'compare' =&gt; '&lt;=', 'type' =&gt; 'DATE' ) ) ); </code></pre> <p>Right now nothing is output at all. Any help is appreciated!</p>
[ { "answer_id": 311635, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 0, "selected": false, "text": "<p>You're correct, all plugins from wordpress.org <a href=\"https://developer.wordpress.org/plugins/wordpress-org/#requirements\" rel=\"nofollow noreferrer\">have to be GPLv2 or later</a></p>\n\n<blockquote>\n <p>Plugins must be compatible with the GNU General Public License v2 or later. If a license is not specified, code will be considered “GPLv2 or later.”</p>\n</blockquote>\n\n<p>If you don't see the licence outright, you can explore the plugins source code on the repo with</p>\n\n<pre><code>https://plugins.svn.wordpress.org/{plugin_slug}/trunk/\n</code></pre>\n\n<p>Where \"<code>{plugin_slug}</code>\" is the slug of your plugin, like <code>my-plugin</code>. You'll be looking for a file like <code>LICENCE.txt</code> or check out <code>readme.txt</code> there should be a <code>License: x</code> in the first few lines. Also the main plugin <code>.php</code> file (differs for each plugin, but usually shares the same name as the plugin slug) may mention the licence.</p>\n" }, { "answer_id": 311638, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 1, "selected": false, "text": "<p>You should ask your lawyer, never ask legal advice from random people on the net.</p>\n\n<p>Regardless of the legal question, it is rarely a smart idea to fork a plugin unless you understand that from that point forward it is your plugin. You can smartly use GIT to manage synchronizing when the original code updates, but the more changes you make to it, the harder it will become.</p>\n\n<p>This might not be a biggy for a 100 LOC plugin, but will be much harder to maintain if the plugin has 10k LOC. Foe example yoast right now has a new version at least every week, are you really going to merge the code bases every week? that is going to add an overhead to you developent process.</p>\n\n<p>Forking of plugin or theme should be the last thing on your mind regardless if its legal or not.</p>\n" } ]
2018/08/16
[ "https://wordpress.stackexchange.com/questions/311657", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148871/" ]
I'm trying to create an events page that lists events (custom post type) within the week. I'm having trouble properly selecting only the posts that have a 'start\_date' that falls in the current week. Here is my code: ``` $day = date('w'); $week_start = date('d-m-Y', strtotime('-'. $day . ' days')); $week_end = date('d-m-Y', strtotime('+' . (6 - $day) . ' days')); $args = array( 'post_type' => 'hcc_events', 'order' => 'ASC', 'meta_key' => 'start_date', 'orderby' => 'meta_value', 'posts_per_page' => -1, 'meta_query' => array( 'relation' => 'AND', array( 'key' => 'start_date', 'value' => $week_start, 'compare' => '>=', 'type' => 'DATE' ), array( 'key' => 'start_date', 'value' => $week_end, 'compare' => '<=', 'type' => 'DATE' ) ) ); ``` Right now nothing is output at all. Any help is appreciated!
You should ask your lawyer, never ask legal advice from random people on the net. Regardless of the legal question, it is rarely a smart idea to fork a plugin unless you understand that from that point forward it is your plugin. You can smartly use GIT to manage synchronizing when the original code updates, but the more changes you make to it, the harder it will become. This might not be a biggy for a 100 LOC plugin, but will be much harder to maintain if the plugin has 10k LOC. Foe example yoast right now has a new version at least every week, are you really going to merge the code bases every week? that is going to add an overhead to you developent process. Forking of plugin or theme should be the last thing on your mind regardless if its legal or not.
311,696
<p>for a project I have to extend the core block core/cover-image. For the first basic try I came up with the following code:</p> <p>PHP:</p> <pre><code>add_action('enqueue_block_editor_assets', function() { wp_enqueue_script('hephaestus-admin-script', get_template_directory_uri() . '/dist/js/admin.js', ['wp-blocks', 'wp-element', 'wp-edit-post'], THEME_VERSION); }); </code></pre> <p>admin.js:</p> <pre><code>function transformElement(element, blockType, attributes) { if (blockType.name != 'core/cover-image') { return element; } var newElement = wp.element.createElement( 'div', { className: 'wp-block-cover-image', style: 'background-image: url(\'' + attributes.url + '\');', }, [ wp.element.createElement( 'p', { className: 'wp-block-cover-image-text', }, [ wp.element.createElement( 'span', { className: 'wp-block-cover-image-text-stage', }, attributes.title ) ] ), ] ); return newElement; } wp.hooks.addFilter( 'blocks.getSaveElement', 'hephaestus/modify-get-save-element', transformElement ); </code></pre> <p>Basically this works. I can add the cover image block in the editor and the frontend output is as desired too.</p> <p>But when reaccessing the site in backend, Gutenberg gives me the following error:</p> <blockquote> <p>Block validation: Block validation failed for <code>core/cover-image</code></p> <p>Expected:</p> <p><code>&lt;div class="wp-block-cover-image" style="background-image: url('https://xxxxxxxx/wp-content/uploads/2018/08/xxxxxxxx.jpg');"&gt;&lt;p class="wp-block-cover-image-text"&gt;&lt;span class="wp-block-cover-image-text-stage"&gt;&lt;/span&gt;&lt;/p&gt;&lt;/div&gt;</code></p> <p>Actual:</p> <p><code>&lt;div class="wp-block-cover-image" style="background-image: url('https://xxxxxxxx/wp-content/uploads/2018/08/xxxxxxxx.jpg');"&gt;&lt;p class="wp-block-cover-image-text"&gt;&lt;span class="wp-block-cover-image-text-stage"&gt;This is a test&lt;/span&gt;&lt;/p&gt;&lt;/div&gt;</code></p> </blockquote> <p><em>Note: image url is intentionally crossed out</em></p> <p>Why do I get this block validation error here? I think it has something to do with the title attribute. But I can't figure out what causes this...</p> <p>Help, anyone?</p> <p>Regards, Marcus</p>
[ { "answer_id": 311704, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 4, "selected": true, "text": "<p>Not a real answer alert</p>\n\n<p>This sounds like a long term bad idea. You are modifying a core functionality with something which do not inherit any of the generated markup of the original block. Any later processing of the block might make assumption about the markup based on the block name, but the assumptions might be wrong and it will be hard to pinpoint why as the block has the expected name.</p>\n\n<p>Just like with widgets and shortcodes, if you are going to basically fork the block you should just create a new one. Modifying a block should be done only when all you do is modifying some small aspect of it, and maybe not even then.</p>\n\n<p>(I do realize that you might be just playing around, but still a new block is much more KISS compatible considering the code you show here)</p>\n" }, { "answer_id": 407857, "author": "Marcus Kober", "author_id": 107117, "author_profile": "https://wordpress.stackexchange.com/users/107117", "pm_score": 0, "selected": false, "text": "<p>Long time ago... :)</p>\n<p>In the meantime I wrote a little tutorial for extending Gutenberg blocks:</p>\n<p><a href=\"https://github.com/marcuskober/extending-gutenberg\" rel=\"nofollow noreferrer\">Extending Gutenberg blocks</a></p>\n" } ]
2018/08/17
[ "https://wordpress.stackexchange.com/questions/311696", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/107117/" ]
for a project I have to extend the core block core/cover-image. For the first basic try I came up with the following code: PHP: ``` add_action('enqueue_block_editor_assets', function() { wp_enqueue_script('hephaestus-admin-script', get_template_directory_uri() . '/dist/js/admin.js', ['wp-blocks', 'wp-element', 'wp-edit-post'], THEME_VERSION); }); ``` admin.js: ``` function transformElement(element, blockType, attributes) { if (blockType.name != 'core/cover-image') { return element; } var newElement = wp.element.createElement( 'div', { className: 'wp-block-cover-image', style: 'background-image: url(\'' + attributes.url + '\');', }, [ wp.element.createElement( 'p', { className: 'wp-block-cover-image-text', }, [ wp.element.createElement( 'span', { className: 'wp-block-cover-image-text-stage', }, attributes.title ) ] ), ] ); return newElement; } wp.hooks.addFilter( 'blocks.getSaveElement', 'hephaestus/modify-get-save-element', transformElement ); ``` Basically this works. I can add the cover image block in the editor and the frontend output is as desired too. But when reaccessing the site in backend, Gutenberg gives me the following error: > > Block validation: Block validation failed for `core/cover-image` > > > Expected: > > > `<div class="wp-block-cover-image" style="background-image: url('https://xxxxxxxx/wp-content/uploads/2018/08/xxxxxxxx.jpg');"><p class="wp-block-cover-image-text"><span class="wp-block-cover-image-text-stage"></span></p></div>` > > > Actual: > > > `<div class="wp-block-cover-image" style="background-image: url('https://xxxxxxxx/wp-content/uploads/2018/08/xxxxxxxx.jpg');"><p class="wp-block-cover-image-text"><span class="wp-block-cover-image-text-stage">This is a test</span></p></div>` > > > *Note: image url is intentionally crossed out* Why do I get this block validation error here? I think it has something to do with the title attribute. But I can't figure out what causes this... Help, anyone? Regards, Marcus
Not a real answer alert This sounds like a long term bad idea. You are modifying a core functionality with something which do not inherit any of the generated markup of the original block. Any later processing of the block might make assumption about the markup based on the block name, but the assumptions might be wrong and it will be hard to pinpoint why as the block has the expected name. Just like with widgets and shortcodes, if you are going to basically fork the block you should just create a new one. Modifying a block should be done only when all you do is modifying some small aspect of it, and maybe not even then. (I do realize that you might be just playing around, but still a new block is much more KISS compatible considering the code you show here)
311,816
<p>Hi I am trying to do a simple thing for my header at <a href="https://blog.madesoma.com/" rel="nofollow noreferrer">https://blog.madesoma.com/</a>, but I don't know what's wrong with it. </p> <pre><code>.site-header { background-color: #473C93; } #branding-logo { float: left; width: 50px; height: auto; } </code></pre> <p>and here is my header.php file: </p> <pre><code>&lt;?php /** * The header for our theme * * This is the template that displays all of the &lt;head&gt; section and everything up until &lt;div id="content"&gt; * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * * @package Rumah_Digital */ ?&gt; &lt;!doctype html&gt; &lt;html &lt;?php language_attributes(); ?&gt;&gt; &lt;head&gt; &lt;meta charset="&lt;?php bloginfo( 'charset' ); ?&gt;"&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1"&gt; &lt;link rel="profile" href="https://gmpg.org/xfn/11"&gt; &lt;?php wp_head(); ?&gt; &lt;/head&gt; &lt;body &lt;?php body_class(); ?&gt;&gt; &lt;div id="page" class="site"&gt; &lt;a class="skip-link screen-reader-text" href="#content"&gt;&lt;?php esc_html_e( 'Skip to content', 'rumah-digital' ); ?&gt;&lt;/a&gt; &lt;header id="masthead" class="site-header"&gt; &lt;div class="site-branding" id="branding"&gt; &lt;img src="https://blog.madesoma.com/wp-content/uploads/2018/08/icon-2088906_1280.png" id="branding-logo"&gt; &lt;/img&gt; &lt;?php the_custom_logo(); if ( is_front_page() &amp;&amp; is_home() ) : ?&gt; &lt;h1 class="site-title"&gt;&lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" rel="home"&gt;&lt;?php bloginfo( 'name' ); ?&gt;&lt;/a&gt;&lt;/h1&gt; &lt;?php else : ?&gt; &lt;p class="site-title"&gt;&lt;a href="&lt;?php echo esc_url( home_url( '/' ) ); ?&gt;" rel="home"&gt;&lt;?php bloginfo( 'name' ); ?&gt;&lt;/a&gt;&lt;/p&gt; &lt;?php endif; $rumah_digital_description = get_bloginfo( 'description', 'display' ); if ( $rumah_digital_description || is_customize_preview() ) : ?&gt; &lt;p class="site-description"&gt;&lt;?php echo $rumah_digital_description; /* WPCS: xss ok. */ ?&gt;&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/div&gt;&lt;!-- .site-branding --&gt; &lt;nav id="site-navigation" class="main-navigation"&gt; &lt;button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"&gt;&lt;?php esc_html_e( 'Primary Menu', 'rumah-digital' ); ?&gt;&lt;/button&gt; &lt;?php wp_nav_menu( array( 'theme_location' =&gt; 'menu-1', 'menu_id' =&gt; 'primary-menu', ) ); ?&gt; &lt;/nav&gt;&lt;!-- #site-navigation --&gt; &lt;/header&gt;&lt;!-- #masthead --&gt; &lt;div id="content" class="site-content"&gt; </code></pre>
[ { "answer_id": 311821, "author": "Frank P. Walentynowicz", "author_id": 32851, "author_profile": "https://wordpress.stackexchange.com/users/32851", "pm_score": -1, "selected": false, "text": "<p>In your style.css file, you should have:</p>\n\n<pre><code>.site-header { background-color: #473C93; }\n#branding-logo { float: left; width: 50px; height: auto; }\n</code></pre>\n\n<p><strong>Tip:</strong> it's always better to use ids ( when available ), to identify elements. Use:</p>\n\n<pre><code>#masthead { background-color: #473C93; }\n#branding-logo { float: left; width: 50px; height: auto; }\n</code></pre>\n\n<p>If you don't see desired effect, it means that style.css had been read from cache. In that case, you have to hard reload your page.</p>\n" }, { "answer_id": 311830, "author": "Electron", "author_id": 148986, "author_profile": "https://wordpress.stackexchange.com/users/148986", "pm_score": 0, "selected": false, "text": "<p>Try adding <code>img</code> to your css.</p>\n\n<p><strong>Example:</strong></p>\n\n<pre><code>#branding-logo img {\nfloat: left;\nwidth: 50px;\nheight: auto; \n}\n</code></pre>\n\n<p><strong>Tip:</strong> Only use ID's on elemets that will be unique. Use Classes for styles that you want to reuse on other elements.</p>\n\n<p>Currently, your image CSS has this CSS applied to it, which is making it super big.</p>\n\n<pre><code>img {\n height: auto;\n max-width: 100%;\n}\n</code></pre>\n" }, { "answer_id": 311850, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 1, "selected": false, "text": "<p>This is the relevant section of CSS in your stylesheet:</p>\n\n<pre><code>/*--------------------------------------------------------------\n## Uling dini ke beten, Bapak Ngelah olah2an. Kangguang deen malu! \n--------------------------------------------------------------*/\n/*--------------------------------------------------------------\n## Header \n--------------------------------------------------------------*\n\n.site-header {\n background-color: #473C93; \n}\n\n#branding-logo {\nfloat: left;\nwidth: 50px;\nheight: auto; \n}\n\n/*--------------------------------------------------------------\n## Menus\n--------------------------------------------------------------*/\n</code></pre>\n\n<p>If you look closely you'll see that the <a href=\"https://developer.mozilla.org/en-US/docs/Web/CSS/Comments\" rel=\"nofollow noreferrer\">CSS comment</a> has not been closed properly:</p>\n\n<pre><code>--------------------------------------------------------------*\n</code></pre>\n\n<p>So your CSS is being interpreted as a comment. Make sure you properly close comments with <code>*/</code>.</p>\n\n<pre><code>/*--------------------------------------------------------------\n## Header \n--------------------------------------------------------------*/\n</code></pre>\n\n<p>Also, use an editor that has syntax highlighting. The issue would have been obvious were it enabled.</p>\n" } ]
2018/08/18
[ "https://wordpress.stackexchange.com/questions/311816", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147326/" ]
Hi I am trying to do a simple thing for my header at <https://blog.madesoma.com/>, but I don't know what's wrong with it. ``` .site-header { background-color: #473C93; } #branding-logo { float: left; width: 50px; height: auto; } ``` and here is my header.php file: ``` <?php /** * The header for our theme * * This is the template that displays all of the <head> section and everything up until <div id="content"> * * @link https://developer.wordpress.org/themes/basics/template-files/#template-partials * * @package Rumah_Digital */ ?> <!doctype html> <html <?php language_attributes(); ?>> <head> <meta charset="<?php bloginfo( 'charset' ); ?>"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="profile" href="https://gmpg.org/xfn/11"> <?php wp_head(); ?> </head> <body <?php body_class(); ?>> <div id="page" class="site"> <a class="skip-link screen-reader-text" href="#content"><?php esc_html_e( 'Skip to content', 'rumah-digital' ); ?></a> <header id="masthead" class="site-header"> <div class="site-branding" id="branding"> <img src="https://blog.madesoma.com/wp-content/uploads/2018/08/icon-2088906_1280.png" id="branding-logo"> </img> <?php the_custom_logo(); if ( is_front_page() && is_home() ) : ?> <h1 class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></h1> <?php else : ?> <p class="site-title"><a href="<?php echo esc_url( home_url( '/' ) ); ?>" rel="home"><?php bloginfo( 'name' ); ?></a></p> <?php endif; $rumah_digital_description = get_bloginfo( 'description', 'display' ); if ( $rumah_digital_description || is_customize_preview() ) : ?> <p class="site-description"><?php echo $rumah_digital_description; /* WPCS: xss ok. */ ?></p> <?php endif; ?> </div><!-- .site-branding --> <nav id="site-navigation" class="main-navigation"> <button class="menu-toggle" aria-controls="primary-menu" aria-expanded="false"><?php esc_html_e( 'Primary Menu', 'rumah-digital' ); ?></button> <?php wp_nav_menu( array( 'theme_location' => 'menu-1', 'menu_id' => 'primary-menu', ) ); ?> </nav><!-- #site-navigation --> </header><!-- #masthead --> <div id="content" class="site-content"> ```
This is the relevant section of CSS in your stylesheet: ``` /*-------------------------------------------------------------- ## Uling dini ke beten, Bapak Ngelah olah2an. Kangguang deen malu! --------------------------------------------------------------*/ /*-------------------------------------------------------------- ## Header --------------------------------------------------------------* .site-header { background-color: #473C93; } #branding-logo { float: left; width: 50px; height: auto; } /*-------------------------------------------------------------- ## Menus --------------------------------------------------------------*/ ``` If you look closely you'll see that the [CSS comment](https://developer.mozilla.org/en-US/docs/Web/CSS/Comments) has not been closed properly: ``` --------------------------------------------------------------* ``` So your CSS is being interpreted as a comment. Make sure you properly close comments with `*/`. ``` /*-------------------------------------------------------------- ## Header --------------------------------------------------------------*/ ``` Also, use an editor that has syntax highlighting. The issue would have been obvious were it enabled.
311,825
<p>I want to login via wordpresss api. I tried with "/wp-json/wp/v2/users" . but it just returns user 1 details.</p> <p>My goal is login via api and fetch all profile information.</p>
[ { "answer_id": 311826, "author": "Mohammad Shahnewaz Sarker", "author_id": 116711, "author_profile": "https://wordpress.stackexchange.com/users/116711", "pm_score": -1, "selected": false, "text": "<p>Solved:</p>\n\n<pre><code>add_action( 'rest_api_init', 'register_api_hooks' );\nfunction register_api_hooks() {\n register_rest_route(\n 'custom-plugin', '/login/',\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'login',\n )\n );\n}\nfunction login($request){\n $creds = array();\n $creds['user_login'] = $request[\"username\"];\n $creds['user_password'] = $request[\"password\"];\n $creds['remember'] = true;\n $user = wp_signon( $creds, true );\n\n\n if ( is_wp_error($user) )\n echo $user-&gt;get_error_message();\n\n $id = $user-&gt;ID;\n $meta = get_user_meta($id);\n\n return $meta;\n}\n</code></pre>\n" }, { "answer_id": 326787, "author": "shiv", "author_id": 136088, "author_profile": "https://wordpress.stackexchange.com/users/136088", "pm_score": 2, "selected": false, "text": "<p><strong>1.</strong> Install and activate <a href=\"https://pt.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/\" rel=\"nofollow noreferrer\">JWT Authentication for WP REST API plugin</a>, also install <a href=\"https://github.com/WP-API/WP-API\" rel=\"nofollow noreferrer\">WP REST API plugin</a> <br>\n <strong>2.</strong> Now you can run any wordpress default api from mobile app or any other source or by postman. for example hit this url from your app or by postman. <a href=\"https://example.com/wp-json/wp/v2/posts\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wp/v2/posts</a> <br>\n <strong>3.</strong> By app or by postman, When you will login with valid details (using rest api) you will get back a token. To login and get token, run the following url by postman or by app\n <a href=\"https://example.com/wp-json/jwt-auth/v1/token\" rel=\"nofollow noreferrer\">https://example.com/wp-json/jwt-auth/v1/token</a>\n <br>\n <strong>4.</strong> By this way you will get a token as shown in picture\n<a href=\"https://i.stack.imgur.com/HXhXR.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HXhXR.jpg\" alt=\"postman and jwt authentication\"></a>\n<br>\nNow use this token to get logged in user details, for example<br>\n<strong>5.</strong> make function in function.php</p>\n\n<pre><code>function checkloggedinuser()\n{\n$currentuserid_fromjwt = get_current_user_id();\nprint_r($currentuserid_fromjwt);\nexit;\n}\n\n add_action('rest_api_init', function ()\n{\n register_rest_route( 'testone', 'loggedinuser',array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'checkloggedinuser'\n ));\n});\n</code></pre>\n\n<p><br>\n<strong>6.</strong> Now again run this new url in postman or in app to get logged in user details.\n<a href=\"https://example.com/wp-json/testone/loggedinuser\" rel=\"nofollow noreferrer\">https://example.com/wp-json/testone/loggedinuser</a>\n(replace example.com with your url)\n<a href=\"https://i.stack.imgur.com/WvhYD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WvhYD.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 369679, "author": "Maher Aldous", "author_id": 172281, "author_profile": "https://wordpress.stackexchange.com/users/172281", "pm_score": 0, "selected": false, "text": "<p>Hello I have a faster and better solution to get the ID and more like the user avatar.</p>\n<p>Just add this to your functions.php file:</p>\n<pre><code>/*\n * Insert some additional data to the JWT Auth plugin\n */\nfunction jwt_auth_function($data, $user) { \n $data['user_role'] = $user-&gt;roles; \n $data['user_id'] = $user-&gt;ID; \n $data['avatar']= get_avatar_url($user-&gt;ID);\n return $data; \n} \nadd_filter( 'jwt_auth_token_before_dispatch', 'jwt_auth_function', 10, 2 );\n</code></pre>\n<p>Reference: <a href=\"https://wordpress.org/support/topic/how-get-id-user/\" rel=\"nofollow noreferrer\">How to ger ID user via API</a></p>\n<p>I hope that's helped</p>\n" } ]
2018/08/19
[ "https://wordpress.stackexchange.com/questions/311825", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/116711/" ]
I want to login via wordpresss api. I tried with "/wp-json/wp/v2/users" . but it just returns user 1 details. My goal is login via api and fetch all profile information.
**1.** Install and activate [JWT Authentication for WP REST API plugin](https://pt.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/), also install [WP REST API plugin](https://github.com/WP-API/WP-API) **2.** Now you can run any wordpress default api from mobile app or any other source or by postman. for example hit this url from your app or by postman. <https://example.com/wp-json/wp/v2/posts> **3.** By app or by postman, When you will login with valid details (using rest api) you will get back a token. To login and get token, run the following url by postman or by app <https://example.com/wp-json/jwt-auth/v1/token> **4.** By this way you will get a token as shown in picture [![postman and jwt authentication](https://i.stack.imgur.com/HXhXR.jpg)](https://i.stack.imgur.com/HXhXR.jpg) Now use this token to get logged in user details, for example **5.** make function in function.php ``` function checkloggedinuser() { $currentuserid_fromjwt = get_current_user_id(); print_r($currentuserid_fromjwt); exit; } add_action('rest_api_init', function () { register_rest_route( 'testone', 'loggedinuser',array( 'methods' => 'POST', 'callback' => 'checkloggedinuser' )); }); ``` **6.** Now again run this new url in postman or in app to get logged in user details. <https://example.com/wp-json/testone/loggedinuser> (replace example.com with your url) [![enter image description here](https://i.stack.imgur.com/WvhYD.jpg)](https://i.stack.imgur.com/WvhYD.jpg)
311,833
<p>I am trying to create a shortcode to see if the url matches with the attribute, then return the content. So far I have:</p> <pre><code>add_shortcode( 'ifurl', 'ifurl' ); function ifurl( $atts, $content = null ) { $url = 'https://' . $_SERVER['SERVER_NAME']; $current_tld = end( explode( ".", parse_url( $url, PHP_URL_HOST ) ) ); $country_select = // Something to get attribute 'country' if( $current_tld == $country_select ) { return $content } } </code></pre> <p>But as you can see, I haven't been able to get the attributes to work correctly, and the if statement.</p> <p>I would like to use it like this: </p> <pre><code>[ifurl country="com"] Show only if .com [/ifurl] [ifurl country="uk"] Show only if .co.uk [/ifurl] </code></pre>
[ { "answer_id": 311826, "author": "Mohammad Shahnewaz Sarker", "author_id": 116711, "author_profile": "https://wordpress.stackexchange.com/users/116711", "pm_score": -1, "selected": false, "text": "<p>Solved:</p>\n\n<pre><code>add_action( 'rest_api_init', 'register_api_hooks' );\nfunction register_api_hooks() {\n register_rest_route(\n 'custom-plugin', '/login/',\n array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'login',\n )\n );\n}\nfunction login($request){\n $creds = array();\n $creds['user_login'] = $request[\"username\"];\n $creds['user_password'] = $request[\"password\"];\n $creds['remember'] = true;\n $user = wp_signon( $creds, true );\n\n\n if ( is_wp_error($user) )\n echo $user-&gt;get_error_message();\n\n $id = $user-&gt;ID;\n $meta = get_user_meta($id);\n\n return $meta;\n}\n</code></pre>\n" }, { "answer_id": 326787, "author": "shiv", "author_id": 136088, "author_profile": "https://wordpress.stackexchange.com/users/136088", "pm_score": 2, "selected": false, "text": "<p><strong>1.</strong> Install and activate <a href=\"https://pt.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/\" rel=\"nofollow noreferrer\">JWT Authentication for WP REST API plugin</a>, also install <a href=\"https://github.com/WP-API/WP-API\" rel=\"nofollow noreferrer\">WP REST API plugin</a> <br>\n <strong>2.</strong> Now you can run any wordpress default api from mobile app or any other source or by postman. for example hit this url from your app or by postman. <a href=\"https://example.com/wp-json/wp/v2/posts\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wp/v2/posts</a> <br>\n <strong>3.</strong> By app or by postman, When you will login with valid details (using rest api) you will get back a token. To login and get token, run the following url by postman or by app\n <a href=\"https://example.com/wp-json/jwt-auth/v1/token\" rel=\"nofollow noreferrer\">https://example.com/wp-json/jwt-auth/v1/token</a>\n <br>\n <strong>4.</strong> By this way you will get a token as shown in picture\n<a href=\"https://i.stack.imgur.com/HXhXR.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HXhXR.jpg\" alt=\"postman and jwt authentication\"></a>\n<br>\nNow use this token to get logged in user details, for example<br>\n<strong>5.</strong> make function in function.php</p>\n\n<pre><code>function checkloggedinuser()\n{\n$currentuserid_fromjwt = get_current_user_id();\nprint_r($currentuserid_fromjwt);\nexit;\n}\n\n add_action('rest_api_init', function ()\n{\n register_rest_route( 'testone', 'loggedinuser',array(\n 'methods' =&gt; 'POST',\n 'callback' =&gt; 'checkloggedinuser'\n ));\n});\n</code></pre>\n\n<p><br>\n<strong>6.</strong> Now again run this new url in postman or in app to get logged in user details.\n<a href=\"https://example.com/wp-json/testone/loggedinuser\" rel=\"nofollow noreferrer\">https://example.com/wp-json/testone/loggedinuser</a>\n(replace example.com with your url)\n<a href=\"https://i.stack.imgur.com/WvhYD.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WvhYD.jpg\" alt=\"enter image description here\"></a></p>\n" }, { "answer_id": 369679, "author": "Maher Aldous", "author_id": 172281, "author_profile": "https://wordpress.stackexchange.com/users/172281", "pm_score": 0, "selected": false, "text": "<p>Hello I have a faster and better solution to get the ID and more like the user avatar.</p>\n<p>Just add this to your functions.php file:</p>\n<pre><code>/*\n * Insert some additional data to the JWT Auth plugin\n */\nfunction jwt_auth_function($data, $user) { \n $data['user_role'] = $user-&gt;roles; \n $data['user_id'] = $user-&gt;ID; \n $data['avatar']= get_avatar_url($user-&gt;ID);\n return $data; \n} \nadd_filter( 'jwt_auth_token_before_dispatch', 'jwt_auth_function', 10, 2 );\n</code></pre>\n<p>Reference: <a href=\"https://wordpress.org/support/topic/how-get-id-user/\" rel=\"nofollow noreferrer\">How to ger ID user via API</a></p>\n<p>I hope that's helped</p>\n" } ]
2018/08/19
[ "https://wordpress.stackexchange.com/questions/311833", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147013/" ]
I am trying to create a shortcode to see if the url matches with the attribute, then return the content. So far I have: ``` add_shortcode( 'ifurl', 'ifurl' ); function ifurl( $atts, $content = null ) { $url = 'https://' . $_SERVER['SERVER_NAME']; $current_tld = end( explode( ".", parse_url( $url, PHP_URL_HOST ) ) ); $country_select = // Something to get attribute 'country' if( $current_tld == $country_select ) { return $content } } ``` But as you can see, I haven't been able to get the attributes to work correctly, and the if statement. I would like to use it like this: ``` [ifurl country="com"] Show only if .com [/ifurl] [ifurl country="uk"] Show only if .co.uk [/ifurl] ```
**1.** Install and activate [JWT Authentication for WP REST API plugin](https://pt.wordpress.org/plugins/jwt-authentication-for-wp-rest-api/), also install [WP REST API plugin](https://github.com/WP-API/WP-API) **2.** Now you can run any wordpress default api from mobile app or any other source or by postman. for example hit this url from your app or by postman. <https://example.com/wp-json/wp/v2/posts> **3.** By app or by postman, When you will login with valid details (using rest api) you will get back a token. To login and get token, run the following url by postman or by app <https://example.com/wp-json/jwt-auth/v1/token> **4.** By this way you will get a token as shown in picture [![postman and jwt authentication](https://i.stack.imgur.com/HXhXR.jpg)](https://i.stack.imgur.com/HXhXR.jpg) Now use this token to get logged in user details, for example **5.** make function in function.php ``` function checkloggedinuser() { $currentuserid_fromjwt = get_current_user_id(); print_r($currentuserid_fromjwt); exit; } add_action('rest_api_init', function () { register_rest_route( 'testone', 'loggedinuser',array( 'methods' => 'POST', 'callback' => 'checkloggedinuser' )); }); ``` **6.** Now again run this new url in postman or in app to get logged in user details. <https://example.com/wp-json/testone/loggedinuser> (replace example.com with your url) [![enter image description here](https://i.stack.imgur.com/WvhYD.jpg)](https://i.stack.imgur.com/WvhYD.jpg)
311,840
<p>I want to enqueue the stylesheet in <code>functions.php</code>, but it's not loading. What can be problem in my code?</p> <pre><code>function my_theme_sty() { wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/assets/css/bootstrap.css'); } add_action( 'admin_enqueue_s', 'my_theme_sty' ); </code></pre>
[ { "answer_id": 311841, "author": "Clinton", "author_id": 122375, "author_profile": "https://wordpress.stackexchange.com/users/122375", "pm_score": 3, "selected": true, "text": "<p>Your function should be:</p>\n\n<pre><code>function my_theme_sty() {\n wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/assets/css/bootstrap.css');\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_sty' );\n</code></pre>\n" }, { "answer_id": 311854, "author": "Scott", "author_id": 111485, "author_profile": "https://wordpress.stackexchange.com/users/111485", "pm_score": 3, "selected": false, "text": "<p>There are two useful <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"noreferrer\">action hooks</a> for registering / enqueuing external scripts &amp; styles in WordPress:</p>\n\n<h2>1. <code>wp_enqueue_scripts</code>:</h2>\n\n<p><a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_enqueue_scripts\" rel=\"noreferrer\"><code>wp_enqueue_scripts</code></a> is the proper action hook to use when enqueuing scripts &amp; styles for the front end.</p>\n\n<p>So if you want to add the CSS file on the frontend of the site, then your CODE will be like:</p>\n\n<pre><code>function my_theme_sty() {\n wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.css' );\n}\nadd_action( 'wp_enqueue_scripts', 'my_theme_sty' );\n</code></pre>\n\n<h2>2. <code>admin_enqueue_scripts</code>:</h2>\n\n<p>On the other hand, <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/admin_enqueue_scripts\" rel=\"noreferrer\"><code>admin_enqueue_scripts</code></a> is the proper action hook to use when enqueuing scripts &amp; styles for the admin panel.</p>\n\n<p>So if you want to add the CSS file on the admin panel of the site, then your CODE will be like:</p>\n\n<pre><code>function my_theme_sty() {\n wp_enqueue_style( 'bootstrap', get_template_directory_uri() . '/assets/css/bootstrap.css' );\n}\nadd_action( 'admin_enqueue_scripts', 'my_theme_sty' );\n</code></pre>\n" } ]
2018/08/19
[ "https://wordpress.stackexchange.com/questions/311840", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/144155/" ]
I want to enqueue the stylesheet in `functions.php`, but it's not loading. What can be problem in my code? ``` function my_theme_sty() { wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/assets/css/bootstrap.css'); } add_action( 'admin_enqueue_s', 'my_theme_sty' ); ```
Your function should be: ``` function my_theme_sty() { wp_enqueue_style( 'bootstrap', get_template_directory_uri().'/assets/css/bootstrap.css'); } add_action( 'wp_enqueue_scripts', 'my_theme_sty' ); ```
311,849
<p>Is there any way to block disposable emails on Woocommerce registration? I used this <a href="https://wordpress.org/plugins/ban-hammer/" rel="nofollow noreferrer">plugin</a> with a list of disposable email domains, but it would only block on regular registration - not Woocommerce registration. Any ideas?</p>
[ { "answer_id": 338008, "author": "ooi18", "author_id": 166810, "author_profile": "https://wordpress.stackexchange.com/users/166810", "pm_score": 0, "selected": false, "text": "<p>If I am right, are you asking a WordPress plugin which can validate emails from Woocommerce Registration? If so, there is some WordPress plugin that are capable to solve your problem.</p>\n\n<p>Basically those plugins will get the emails inputted from Woocommerce, validate it and return the result back to the form. Some of the plugin will require you to sign up the API key before use.</p>\n\n<p>Currently I am using <a href=\"https://wordpress.org/plugins/mailboxvalidator-email-validator/\" rel=\"nofollow noreferrer\">MailboxValidator Email Validator</a>, which did a great job on protecting my website from disposable email address.</p>\n" }, { "answer_id": 366736, "author": "srinath", "author_id": 188183, "author_profile": "https://wordpress.stackexchange.com/users/188183", "pm_score": 1, "selected": false, "text": "<p>Hi just add this code in your theme functions.php</p>\n\n<pre><code>add_action('init', 'mydomain_plugin_checks');\n\nfunction mydomain_plugin_checks(){\n if ( class_exists('BanHammer') ) {\n add_filter('woocommerce_registration_errors', 'woocommerce_banhammer_validation', 10, 3 );\n } \n}\n\nfunction woocommerce_banhammer_validation( $validation_errors, $username, $email ) {\n if( (new BanHammer)-&gt;banhammer_drop( $username, $email, $validation_errors ) )\n return new WP_Error( 'registration-error-bad-email', (new BanHammer)-&gt;options['message'] );\n return $validation_errors;\n}\n</code></pre>\n" } ]
2018/08/19
[ "https://wordpress.stackexchange.com/questions/311849", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/78330/" ]
Is there any way to block disposable emails on Woocommerce registration? I used this [plugin](https://wordpress.org/plugins/ban-hammer/) with a list of disposable email domains, but it would only block on regular registration - not Woocommerce registration. Any ideas?
Hi just add this code in your theme functions.php ``` add_action('init', 'mydomain_plugin_checks'); function mydomain_plugin_checks(){ if ( class_exists('BanHammer') ) { add_filter('woocommerce_registration_errors', 'woocommerce_banhammer_validation', 10, 3 ); } } function woocommerce_banhammer_validation( $validation_errors, $username, $email ) { if( (new BanHammer)->banhammer_drop( $username, $email, $validation_errors ) ) return new WP_Error( 'registration-error-bad-email', (new BanHammer)->options['message'] ); return $validation_errors; } ```
311,858
<p>For example, I have a category <code>/wiki/</code> <code>https://buhehe.de/wiki/</code></p> <p>It has removed the term "category" from the URL, but please see: <code>https://buhehe.de/wiki/page/2</code></p> <p>It doesn't show the second category page, but it actually has a second page.</p> <p>Where is the problem?</p>
[ { "answer_id": 311864, "author": "Cryptomanic", "author_id": 148990, "author_profile": "https://wordpress.stackexchange.com/users/148990", "pm_score": 2, "selected": false, "text": "<h2>Yoast Plugin - Remove Categories</h2>\n\n<p>You could use an SEO plugin such as <a href=\"https://yoast.com/\" rel=\"nofollow noreferrer\"><strong>Yoast</strong></a> which has a <strong>remove categories</strong> option, or you could program the function yourself which is explained in some of the below links.</p>\n\n<p><strong>Some related posts that might help you:</strong></p>\n\n<p><a href=\"https://wordpress.stackexchange.com/questions/151874/how-to-remove-category-from-wordpress-url\">How to remove category from wordpress url?</a></p>\n\n<p><a href=\"https://stackoverflow.com/questions/17798815/remove-category-tag-base-from-wordpress-url-without-a-plugin/27569173#27569173\">Remove category &amp; tag base from WordPress url - without a plugin</a></p>\n" }, { "answer_id": 311872, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": false, "text": "<h2>Why does the problem in pagination happens?</h2>\n\n<p>Say you have a category named <code>wiki</code>.</p>\n\n<p>Now, when you have a category URL like: <code>https://example.com/wiki</code> (instead of <code>https://example.com/category/wiki</code>) and say page or post URL like:</p>\n\n<pre><code>https://example.com/a-page\nor\nhttps://example.com/category-slug/a-post\n</code></pre>\n\n<p>WordPress has really no way of knowing if <code>https://example.com/wiki/page/2</code> is a the second page of another page / post, or the second page of a category archive (because <code>wiki</code> may very well be a page slug or <code>page</code> be a post slug under category <code>wiki</code>).</p>\n\n<p>This happens specifically because WordPress confuses with <code>/page/2</code> part as a different <a href=\"https://codex.wordpress.org/wp_link_pages\" rel=\"noreferrer\">multi-part paginated page or post</a>.</p>\n\n<p>So, instead of loading the next pages of your <code>wiki</code> category archive, WordPress will try to load a paginated post with the slug <code>page</code> and you'll get a <code>404</code> (page not found) error instead of getting the second page of the category archive.</p>\n\n<p>Before I give you the solution to this issue, first make sure you've got the permalink correct.</p>\n\n<h2>To achieve the necessary Category URL Structure:</h2>\n\n<p>The URL structure you wanted needs some work. So unless you've done it already, follow the instructions below to achieve the said URL structure:</p>\n\n<pre><code># URL structure for Categories\nhttps://example.com/category-slug\n</code></pre>\n\n<p>For this:</p>\n\n<ol>\n<li>Go to: <code>WordPress Admin Panel Menu</code> → <code>Settings</code>.</li>\n<li>Put a single dot (<code>.</code>) in the <code>Category base</code> text field.</li>\n<li>Click <kbd>Save Changes</kbd> button.</li>\n</ol>\n\n<hr>\n\n<pre><code># URL structure for Posts\nhttps://example.com/category-slug/post-slug\n</code></pre>\n\n<p>For this:</p>\n\n<ol>\n<li>Go to: <code>WordPress Admin Panel Menu</code> → <code>Settings</code>.</li>\n<li>Select <code>Custom Structure</code> and enter <code>/%category%/%postname%/</code> in the <code>Custom Structure</code> text field.</li>\n<li>Click <kbd>Save Changes</kbd> button.</li>\n</ol>\n\n<h2>Solving the Category Pagination Problem:</h2>\n\n<p>Some SEO plugins have solution to this problem. However, since this is a core URL structure issue of your site, it's better not to depend on SEO plugins for this. Say, what if you want to change the SEO plugin in future and the other plugin has better options but don't provide solution for this? </p>\n\n<p>So it's better to use a simple plugin that fixes only this one problem. You may use the following CODE and save it in your plugin directory with file name <code>category-pagination-fix.php</code> and then activate the plugin named <code>Category Pagination Fix</code> from the site's admin panel:</p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: Category Pagination Fix\nPlugin URI: https://wordpress.stackexchange.com/a/311858/110572\nDescription: Fix category pagination\nVersion: 1.0.0\nAuthor: Fayaz Ahmed\nAuthor URI: https://www.fayazmiraz.com/\n*/\n\nfunction wpse311858_fix_category_pagination( $query_string = array() )\n{\n if( isset( $query_string['category_name'] )\n &amp;&amp; isset( $query_string['name'] ) &amp;&amp; $query_string['name'] === 'page'\n &amp;&amp; isset( $query_string['page'] ) ) {\n $paged = trim( $query_string['page'], '/' );\n if( is_numeric( $paged ) ) {\n // we are not allowing 'page' as a page or post slug \n unset( $query_string['name'] );\n unset( $query_string['page'] ) ;\n\n // for a category archive, proper pagination query string is 'paged'\n $query_string['paged'] = ( int ) $paged;\n }\n } \n return $query_string;\n}\nadd_filter( 'request', 'wpse311858_fix_category_pagination' );\n</code></pre>\n\n<h2>Alternate solution:</h2>\n\n<p>The above solution works perfectly with pagination when you have category URL like:</p>\n\n<pre><code>https://example.com/category-slug/\n</code></pre>\n\n<p>and post URL like:</p>\n\n<pre><code>https://example.com/category-slug/post-slug\n</code></pre>\n\n<p>However, when you have subcategory URL like:</p>\n\n<pre><code>https://example.com/category-slug/sub-category-slug\n</code></pre>\n\n<p>or, when you have post URL like:</p>\n\n<pre><code>https://example.com/post-slug\n</code></pre>\n\n<p>the above simple solution doesn't work.</p>\n\n<p>In these sort of cases, you may use a plugin like <a href=\"https://wordpress.org/plugins/remove-category-url/\" rel=\"noreferrer\">Remove Category URL</a>.</p>\n\n<p>These sort of plugins make some fundamental URL rewrite changes, that's why some default WordPress behaviour may not work as expected after you use one of these plugins. So use the solution that works best for you, but make sure that you <strong>don't try to do the same thing in multiple different plugins</strong>.</p>\n\n<blockquote>\n <p><strong>Caution:</strong> Using these sort of headless archive URL (e.g. no <code>category</code> or similar term for category page links, no <code>tag</code> or similar term in for tag page links etc.) creates internal conflicts with page &amp; post URL(s). WordPress engine needs a lot of internal checking to determine which to load and which not to. That process is resource hungry. So if your site has thousands of pages, posts, categories, tags etc. it's better to use these terms in the URL.</p>\n</blockquote>\n" }, { "answer_id": 317648, "author": "norixxx", "author_id": 37130, "author_profile": "https://wordpress.stackexchange.com/users/37130", "pm_score": 0, "selected": false, "text": "<p>Here is my solution.</p>\n\n<p>This works paginated page too in my case.</p>\n\n<p>Please give it a try and let me know if it works.</p>\n\n<pre><code>// Remove category from URL\nadd_filter('user_trailingslashit', 'wpse311858_remove_category_from_url');\nfunction wpse311858_remove_category_from_url($link) {\n return str_replace(\"/category/\", \"/\", $link);\n}\n\n// Add new category URLs\nadd_filter('generate_rewrite_rules', 'wpse311858_category_rewrite');\nfunction wpse311858_category_rewrite($wp_rewrite) {\n $new_rules = [];\n\n // Get all the categories including empty categories\n $cats = get_categories(['exclude' =&gt; 1, 'hide_empty' =&gt; false ]); //exclude uncategorized catagory if there were \n\n // Loop through each category to add new rules to core rewrite pattern\n foreach( $cats as $cat ) {\n $cat_nicename = $cat-&gt;slug;\n\n // Check if it is parent or child category\n if( $cat-&gt;parent !== 0 ) {\n $cat_nicename = get_category_parents( $cat-&gt;parent, false, '/', true ) . $cat_nicename;\n }\n\n // For each pattern\n $new_rules['(' . $cat_nicename . ')/(.+?)/feed/(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]'; // for feed pattern\n $new_rules['(' . $cat_nicename . ')/(.+?)/(feed|rdf|rss|rss2|atom)/?$'] = 'index.php?category_name=$matches[1]&amp;feed=$matches[2]'; // for another feed pattern\n $new_rules['(' . $cat_nicename . ')/(.+?)/embed/?$'] = 'index.php?category_name=$matches[1]&amp;embed=true'; // for embed page\n $new_rules['(' . $cat_nicename . ')/page/?([0-9]{1,})/?$'] = 'index.php?category_name=$matches[1]&amp;paged=$matches[2]'; // for paged page\n $new_rules['(' . $cat_nicename . ')/?$'] = 'index.php?category_name=$matches[1]'; // for category archive page\n\n } //endforeach\n\n // Finally add new rules\n $wp_rewrite-&gt;rules = $new_rules + $wp_rewrite-&gt;rules;\n}\n</code></pre>\n" } ]
2018/08/19
[ "https://wordpress.stackexchange.com/questions/311858", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/147675/" ]
For example, I have a category `/wiki/` `https://buhehe.de/wiki/` It has removed the term "category" from the URL, but please see: `https://buhehe.de/wiki/page/2` It doesn't show the second category page, but it actually has a second page. Where is the problem?
Why does the problem in pagination happens? ------------------------------------------- Say you have a category named `wiki`. Now, when you have a category URL like: `https://example.com/wiki` (instead of `https://example.com/category/wiki`) and say page or post URL like: ``` https://example.com/a-page or https://example.com/category-slug/a-post ``` WordPress has really no way of knowing if `https://example.com/wiki/page/2` is a the second page of another page / post, or the second page of a category archive (because `wiki` may very well be a page slug or `page` be a post slug under category `wiki`). This happens specifically because WordPress confuses with `/page/2` part as a different [multi-part paginated page or post](https://codex.wordpress.org/wp_link_pages). So, instead of loading the next pages of your `wiki` category archive, WordPress will try to load a paginated post with the slug `page` and you'll get a `404` (page not found) error instead of getting the second page of the category archive. Before I give you the solution to this issue, first make sure you've got the permalink correct. To achieve the necessary Category URL Structure: ------------------------------------------------ The URL structure you wanted needs some work. So unless you've done it already, follow the instructions below to achieve the said URL structure: ``` # URL structure for Categories https://example.com/category-slug ``` For this: 1. Go to: `WordPress Admin Panel Menu` → `Settings`. 2. Put a single dot (`.`) in the `Category base` text field. 3. Click `Save Changes` button. --- ``` # URL structure for Posts https://example.com/category-slug/post-slug ``` For this: 1. Go to: `WordPress Admin Panel Menu` → `Settings`. 2. Select `Custom Structure` and enter `/%category%/%postname%/` in the `Custom Structure` text field. 3. Click `Save Changes` button. Solving the Category Pagination Problem: ---------------------------------------- Some SEO plugins have solution to this problem. However, since this is a core URL structure issue of your site, it's better not to depend on SEO plugins for this. Say, what if you want to change the SEO plugin in future and the other plugin has better options but don't provide solution for this? So it's better to use a simple plugin that fixes only this one problem. You may use the following CODE and save it in your plugin directory with file name `category-pagination-fix.php` and then activate the plugin named `Category Pagination Fix` from the site's admin panel: ``` <?php /* Plugin Name: Category Pagination Fix Plugin URI: https://wordpress.stackexchange.com/a/311858/110572 Description: Fix category pagination Version: 1.0.0 Author: Fayaz Ahmed Author URI: https://www.fayazmiraz.com/ */ function wpse311858_fix_category_pagination( $query_string = array() ) { if( isset( $query_string['category_name'] ) && isset( $query_string['name'] ) && $query_string['name'] === 'page' && isset( $query_string['page'] ) ) { $paged = trim( $query_string['page'], '/' ); if( is_numeric( $paged ) ) { // we are not allowing 'page' as a page or post slug unset( $query_string['name'] ); unset( $query_string['page'] ) ; // for a category archive, proper pagination query string is 'paged' $query_string['paged'] = ( int ) $paged; } } return $query_string; } add_filter( 'request', 'wpse311858_fix_category_pagination' ); ``` Alternate solution: ------------------- The above solution works perfectly with pagination when you have category URL like: ``` https://example.com/category-slug/ ``` and post URL like: ``` https://example.com/category-slug/post-slug ``` However, when you have subcategory URL like: ``` https://example.com/category-slug/sub-category-slug ``` or, when you have post URL like: ``` https://example.com/post-slug ``` the above simple solution doesn't work. In these sort of cases, you may use a plugin like [Remove Category URL](https://wordpress.org/plugins/remove-category-url/). These sort of plugins make some fundamental URL rewrite changes, that's why some default WordPress behaviour may not work as expected after you use one of these plugins. So use the solution that works best for you, but make sure that you **don't try to do the same thing in multiple different plugins**. > > **Caution:** Using these sort of headless archive URL (e.g. no `category` or similar term for category page links, no `tag` or similar term in for tag page links etc.) creates internal conflicts with page & post URL(s). WordPress engine needs a lot of internal checking to determine which to load and which not to. That process is resource hungry. So if your site has thousands of pages, posts, categories, tags etc. it's better to use these terms in the URL. > > >
311,932
<p>How to stop featured image thumbnail [set as background image] on blog index page just repeating same image across all posts:</p> <p>i have this code here: </p> <pre><code>add_action( 'wp_head', 'set_featured_background', 99); function set_featured_background() { if ( has_post_thumbnail() ) { $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full'); ?&gt; &lt;style&gt; .has-post-thumbnail { background-image: url('&lt;?php echo $featured_img_url ?&gt;'); background-size: 100% 100%; } &lt;/style&gt; &lt;?php } } </code></pre> <p>And ive tried a few different variations but it always jsut finds the most recent posts image and uses that across all posts. Do i need to be trying to put in a check to make sure it does the same thing every unique post. For example: If this post has a unique ID find its thumbnail image and apply as a style. Or is it because im trying to add it to the css class has-post-thumbnail which is applied to all posts? [that have a thumbnail]</p>
[ { "answer_id": 311961, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Or is it because im trying to add it to the css class <code>.has-post-thumbnail</code> which is applied to all posts?</p>\n</blockquote>\n\n<p>Yes, <code>set_featured_background()</code> gets first post from the loop and add <code>.has-post-thumbnail</code> to styles. All posts that have thumbnail (with class <code>.has-post-thumbnail</code>) will have the same background. </p>\n\n<p>Try setting the background in the template file responsible for displaying posts on the home page, probably in <code>content.php</code> or <code>front-page.php</code>. </p>\n\n<pre><code>&lt;?php\n $attr_style= '';\n if ( is_home() &amp;&amp; has_post_thumbnail() ) {\n $url = wp_get_attachment_url( get_post_thumbnail_id($post-&gt;ID) );\n $attr_style = ' style=\"background: url('. $url.'); background-size: 100% 100%;\" ';\n }\n?&gt;\n&lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); echo $attr_style; ?&gt;&gt;\n</code></pre>\n" }, { "answer_id": 378500, "author": "Bernhard Henselmann", "author_id": 149729, "author_profile": "https://wordpress.stackexchange.com/users/149729", "pm_score": 0, "selected": false, "text": "<p>I would try to use the ID of the post (which should be part of the id or class of the article-tag) as additional selector for the style:</p>\n<pre><code>&lt;style&gt;\n #post-&lt;?php the_ID();?&gt;.has-post-thumbnail {\n background-image: url('&lt;?php echo $featured_img_url ?&gt;');\n background-size: 100% 100%; \n }\n&lt;/style&gt;\n \n</code></pre>\n" } ]
2018/08/20
[ "https://wordpress.stackexchange.com/questions/311932", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149054/" ]
How to stop featured image thumbnail [set as background image] on blog index page just repeating same image across all posts: i have this code here: ``` add_action( 'wp_head', 'set_featured_background', 99); function set_featured_background() { if ( has_post_thumbnail() ) { $featured_img_url = get_the_post_thumbnail_url(get_the_ID(),'full'); ?> <style> .has-post-thumbnail { background-image: url('<?php echo $featured_img_url ?>'); background-size: 100% 100%; } </style> <?php } } ``` And ive tried a few different variations but it always jsut finds the most recent posts image and uses that across all posts. Do i need to be trying to put in a check to make sure it does the same thing every unique post. For example: If this post has a unique ID find its thumbnail image and apply as a style. Or is it because im trying to add it to the css class has-post-thumbnail which is applied to all posts? [that have a thumbnail]
> > Or is it because im trying to add it to the css class `.has-post-thumbnail` which is applied to all posts? > > > Yes, `set_featured_background()` gets first post from the loop and add `.has-post-thumbnail` to styles. All posts that have thumbnail (with class `.has-post-thumbnail`) will have the same background. Try setting the background in the template file responsible for displaying posts on the home page, probably in `content.php` or `front-page.php`. ``` <?php $attr_style= ''; if ( is_home() && has_post_thumbnail() ) { $url = wp_get_attachment_url( get_post_thumbnail_id($post->ID) ); $attr_style = ' style="background: url('. $url.'); background-size: 100% 100%;" '; } ?> <article id="post-<?php the_ID(); ?>" <?php post_class(); echo $attr_style; ?>> ```
311,956
<p>Is it safe to use hyphen in shortcode attribute value?</p> <p>For example:</p> <pre><code>[foo something="fo-bar"] </code></pre>
[ { "answer_id": 311957, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": -1, "selected": true, "text": "<p>It's safe, you won't have any problem using it, the only caution about <strong>Hyphens</strong> and <strong>Shortcodes</strong> comes from the <a href=\"https://codex.wordpress.org/Shortcode_API#Hyphens\" rel=\"nofollow noreferrer\">Codex</a>.</p>\n\n<blockquote>\n <p>Take caution when using hyphens in the name of your shortcodes. In the\n following instance WordPress may see the second opening shortcode as\n equivalent to the first (basically WordPress sees the first part\n before the hyphen):</p>\n</blockquote>\n\n<pre><code>[tag]\n[tag-a]\n</code></pre>\n\n<blockquote>\n <p>It all depends on which shortcode is defined first. If you are going\n to use hyphens then define the shortest shortcode first.</p>\n \n <p>To avoid this, use an underscore or simply no separator:</p>\n</blockquote>\n\n<pre><code>[tag_a]\n</code></pre>\n" }, { "answer_id": 311968, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": false, "text": "<blockquote>\n<p><strong>tl;dr;</strong> Dash (hyphen) <code>-</code> is safe to use within shortcode <strong>attribute values</strong>.</p>\n</blockquote>\n<hr />\n<h2>Rules for Shortcode attribute values:</h2>\n<p>For shortcode <strong>attribute values</strong>, anything <strong>other than the following</strong> four is usually fine:</p>\n<ol>\n<li>There shouldn't be any square brackets <code>[</code> or <code>]</code>, e.g. <code>[foo bar='baa]z']</code></li>\n<li>There shouldn't be single quote within single quote, e.g. <code>[foo bar='baa'z']</code></li>\n<li>There shouldn't be double quote within double quote, e.g. <code>[foo bar=&quot;baa&quot;z&quot;]</code></li>\n<li>Back slash <code>\\</code> will be escaped.</li>\n</ol>\n<hr />\n<p>So the following example shortcode attribute values are just fine:</p>\n<pre><code>// dash or hyphen is fine\n[foo bar='baa-z']\n// Double quote within single quote is fine\n[foo bar='baa&quot;z']\n// single quote within double quote is fine\n[foo bar=&quot;baa'z&quot;]\n// space is fine\n[foo bar='baa z']\n// use double back slash to get single back slash \n[foo bar='baa\\\\z'] \n</code></pre>\n<h2>Quote from <a href=\"https://codex.wordpress.org/Shortcode_API#Attributes\" rel=\"noreferrer\">codex</a>:</h2>\n<blockquote>\n<p>Attribute values must never contain the following characters:</p>\n<p>Square braces: <code>[ ]</code></p>\n<p>Quotes: <code>&quot; '</code></p>\n<p>Unquoted values also must never contain spaces.</p>\n<p>HTML characters <code>&lt;</code> and <code>&gt;</code> have only limited support in attributes.</p>\n<p>The recommended method of escaping special characters in shortcode attributes is HTML encoding. Most importantly, any user input appearing in a shortcode attribute must be escaped or stripped of special characters.</p>\n<p>Note that double quotes are allowed inside of single-quoted values and vice versa, however this is not recommended when dealing with user input.</p>\n<p>The following characters, if they are not escaped within an attribute value, will be automatically stripped and converted to spaces:</p>\n<p>No-break space: <code>\\xC2\\xA0</code></p>\n<p>Zero-width space: <code>\\xE2\\x80\\x8B</code></p>\n</blockquote>\n" } ]
2018/08/20
[ "https://wordpress.stackexchange.com/questions/311956", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/45321/" ]
Is it safe to use hyphen in shortcode attribute value? For example: ``` [foo something="fo-bar"] ```
It's safe, you won't have any problem using it, the only caution about **Hyphens** and **Shortcodes** comes from the [Codex](https://codex.wordpress.org/Shortcode_API#Hyphens). > > Take caution when using hyphens in the name of your shortcodes. In the > following instance WordPress may see the second opening shortcode as > equivalent to the first (basically WordPress sees the first part > before the hyphen): > > > ``` [tag] [tag-a] ``` > > It all depends on which shortcode is defined first. If you are going > to use hyphens then define the shortest shortcode first. > > > To avoid this, use an underscore or simply no separator: > > > ``` [tag_a] ```
311,967
<p>I have a multisite and I’m able to use the rest api for posts/tags/etc for specific sites but I was wondering if there’s a away to get a list of sites on the network using the rest api?</p> <p>something like this: <a href="https://wordpress.stackexchange.com/questions/205354/rest-api-for-multisite">REST API for Multisite</a> but without a plugin?</p>
[ { "answer_id": 311957, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": -1, "selected": true, "text": "<p>It's safe, you won't have any problem using it, the only caution about <strong>Hyphens</strong> and <strong>Shortcodes</strong> comes from the <a href=\"https://codex.wordpress.org/Shortcode_API#Hyphens\" rel=\"nofollow noreferrer\">Codex</a>.</p>\n\n<blockquote>\n <p>Take caution when using hyphens in the name of your shortcodes. In the\n following instance WordPress may see the second opening shortcode as\n equivalent to the first (basically WordPress sees the first part\n before the hyphen):</p>\n</blockquote>\n\n<pre><code>[tag]\n[tag-a]\n</code></pre>\n\n<blockquote>\n <p>It all depends on which shortcode is defined first. If you are going\n to use hyphens then define the shortest shortcode first.</p>\n \n <p>To avoid this, use an underscore or simply no separator:</p>\n</blockquote>\n\n<pre><code>[tag_a]\n</code></pre>\n" }, { "answer_id": 311968, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 3, "selected": false, "text": "<blockquote>\n<p><strong>tl;dr;</strong> Dash (hyphen) <code>-</code> is safe to use within shortcode <strong>attribute values</strong>.</p>\n</blockquote>\n<hr />\n<h2>Rules for Shortcode attribute values:</h2>\n<p>For shortcode <strong>attribute values</strong>, anything <strong>other than the following</strong> four is usually fine:</p>\n<ol>\n<li>There shouldn't be any square brackets <code>[</code> or <code>]</code>, e.g. <code>[foo bar='baa]z']</code></li>\n<li>There shouldn't be single quote within single quote, e.g. <code>[foo bar='baa'z']</code></li>\n<li>There shouldn't be double quote within double quote, e.g. <code>[foo bar=&quot;baa&quot;z&quot;]</code></li>\n<li>Back slash <code>\\</code> will be escaped.</li>\n</ol>\n<hr />\n<p>So the following example shortcode attribute values are just fine:</p>\n<pre><code>// dash or hyphen is fine\n[foo bar='baa-z']\n// Double quote within single quote is fine\n[foo bar='baa&quot;z']\n// single quote within double quote is fine\n[foo bar=&quot;baa'z&quot;]\n// space is fine\n[foo bar='baa z']\n// use double back slash to get single back slash \n[foo bar='baa\\\\z'] \n</code></pre>\n<h2>Quote from <a href=\"https://codex.wordpress.org/Shortcode_API#Attributes\" rel=\"noreferrer\">codex</a>:</h2>\n<blockquote>\n<p>Attribute values must never contain the following characters:</p>\n<p>Square braces: <code>[ ]</code></p>\n<p>Quotes: <code>&quot; '</code></p>\n<p>Unquoted values also must never contain spaces.</p>\n<p>HTML characters <code>&lt;</code> and <code>&gt;</code> have only limited support in attributes.</p>\n<p>The recommended method of escaping special characters in shortcode attributes is HTML encoding. Most importantly, any user input appearing in a shortcode attribute must be escaped or stripped of special characters.</p>\n<p>Note that double quotes are allowed inside of single-quoted values and vice versa, however this is not recommended when dealing with user input.</p>\n<p>The following characters, if they are not escaped within an attribute value, will be automatically stripped and converted to spaces:</p>\n<p>No-break space: <code>\\xC2\\xA0</code></p>\n<p>Zero-width space: <code>\\xE2\\x80\\x8B</code></p>\n</blockquote>\n" } ]
2018/08/20
[ "https://wordpress.stackexchange.com/questions/311967", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76667/" ]
I have a multisite and I’m able to use the rest api for posts/tags/etc for specific sites but I was wondering if there’s a away to get a list of sites on the network using the rest api? something like this: [REST API for Multisite](https://wordpress.stackexchange.com/questions/205354/rest-api-for-multisite) but without a plugin?
It's safe, you won't have any problem using it, the only caution about **Hyphens** and **Shortcodes** comes from the [Codex](https://codex.wordpress.org/Shortcode_API#Hyphens). > > Take caution when using hyphens in the name of your shortcodes. In the > following instance WordPress may see the second opening shortcode as > equivalent to the first (basically WordPress sees the first part > before the hyphen): > > > ``` [tag] [tag-a] ``` > > It all depends on which shortcode is defined first. If you are going > to use hyphens then define the shortest shortcode first. > > > To avoid this, use an underscore or simply no separator: > > > ``` [tag_a] ```
311,972
<blockquote> <p>Notice: Undefined index: mtral_field_subscriber in /wp-content/plugins/redirect-after-login/redirect-after-login.php on line 54</p> <p>Warning: Cannot modify header information - headers already sent by (output started at /wp-content/plugins/redirect-after-login/redirect-after-login.php:54) in wp-includes/pluggable.php on line 1219</p> </blockquote> <p>I get the above error and the error occurs specifically after I login since I am using Redirect After Login plugin in wordpress</p> <p>How can I debug and fix it ?</p>
[ { "answer_id": 311973, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>You can simply remove that plugin, and create that redirection youself.</p>\n\n<p>You can use the <code>login_redirect</code> hook, add this into your theme's <code>functions.php</code></p>\n\n<pre><code>function redirect_admin( $redirect_to, $request, $user ){\n\n //is there a user to check?\n\n if ( isset( $user-&gt;roles ) &amp;&amp; is_array( $user-&gt;roles ) ) {\n\n //check for admins\n if ( in_array( 'administrator', $user-&gt;roles ) ) {\n\n $redirect_to = get_site_url().'/a-page/'; // Your redirect URL\n }\n }\n\n return $redirect_to;\n}\n\nadd_filter( 'login_redirect', 'redirect_admin', 10, 3 );\n</code></pre>\n" }, { "answer_id": 311974, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": -1, "selected": false, "text": "<blockquote>\n <p>How can I debug and fix it ?</p>\n</blockquote>\n\n<p>The issue is straightforward and the error identifies the specific file and line number that it's occurring on, but since this is a plugin it's something that the plugin author has to fix. You need to contact them and tell them to fix it or find another plugin.</p>\n\n<p>That being said, a PHP notice like this is a minor issue, not something that should appear in production in front of the public. To prevent errors appearing to the public, in your wp-config.php file set <code>WP_DEBUG_DISPLAY</code> to <code>false</code>:</p>\n\n<pre><code>define('WP_DEBUG_DISPLAY', false);\n</code></pre>\n\n<p>But to keep a log of any errors, set <code>WP_DEBUG_LOG</code> to <code>true</code>:</p>\n\n<pre><code>define('WP_DEBUG_LOG', true);\n</code></pre>\n" } ]
2018/08/20
[ "https://wordpress.stackexchange.com/questions/311972", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/48078/" ]
> > Notice: Undefined index: mtral\_field\_subscriber in > /wp-content/plugins/redirect-after-login/redirect-after-login.php > on line 54 > > > Warning: Cannot modify header information - headers already sent by > (output started at > /wp-content/plugins/redirect-after-login/redirect-after-login.php:54) > in wp-includes/pluggable.php on line > 1219 > > > I get the above error and the error occurs specifically after I login since I am using Redirect After Login plugin in wordpress How can I debug and fix it ?
You can simply remove that plugin, and create that redirection youself. You can use the `login_redirect` hook, add this into your theme's `functions.php` ``` function redirect_admin( $redirect_to, $request, $user ){ //is there a user to check? if ( isset( $user->roles ) && is_array( $user->roles ) ) { //check for admins if ( in_array( 'administrator', $user->roles ) ) { $redirect_to = get_site_url().'/a-page/'; // Your redirect URL } } return $redirect_to; } add_filter( 'login_redirect', 'redirect_admin', 10, 3 ); ```
311,976
<p>My site is using a nav menu in my custom theme. I want to add navigation links to anchored links that points to specific sections of the site home page using a <code>Custom Link</code> in the nav menu.</p> <p>I want to use the equivalent of:</p> <pre><code>&lt;?php echo get_home_url(); ?&gt;/#xxxx </code></pre> <p>in the URL field. If I use just the anchored link <code>#xxx</code> as the <code>Custom Link</code>, it will work fine on the home page, but it will not link from another page (as that anchor section is not on that page).</p> <p>There has to be a clean way to do this. When I insert the php code as well, it appears to work on the home page, but not from another page. I've gone through all the other related posts, but none seem to address this issue.</p>
[ { "answer_id": 311978, "author": "lpFranz", "author_id": 135813, "author_profile": "https://wordpress.stackexchange.com/users/135813", "pm_score": -1, "selected": false, "text": "<p>You can add the <code>/index.php/#my-anchor</code> in your custom links, try it.</p>\n\n<p>Or, you can just put your intire URL in your links.</p>\n" }, { "answer_id": 311981, "author": "Scott", "author_id": 111485, "author_profile": "https://wordpress.stackexchange.com/users/111485", "pm_score": 3, "selected": true, "text": "<p>If all you want is to go to a specific section of the home page, then the easiest way is to use the <strong>relative URL</strong> mark <code>/</code> and then use the anchor <code>#xxx</code>.</p>\n\n<p>So the custom link for the menu will be: <code>/#xxx</code>.</p>\n\n<blockquote>\n <p><strong>Note the difference between <code>#xxx</code> and <code>/#xxx</code></strong> as custom link.</p>\n</blockquote>\n\n<p>The best thing about this approach is that you'll not have to bother changing the link after you go live, and additionally, this needs no programming.</p>\n" } ]
2018/08/20
[ "https://wordpress.stackexchange.com/questions/311976", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113048/" ]
My site is using a nav menu in my custom theme. I want to add navigation links to anchored links that points to specific sections of the site home page using a `Custom Link` in the nav menu. I want to use the equivalent of: ``` <?php echo get_home_url(); ?>/#xxxx ``` in the URL field. If I use just the anchored link `#xxx` as the `Custom Link`, it will work fine on the home page, but it will not link from another page (as that anchor section is not on that page). There has to be a clean way to do this. When I insert the php code as well, it appears to work on the home page, but not from another page. I've gone through all the other related posts, but none seem to address this issue.
If all you want is to go to a specific section of the home page, then the easiest way is to use the **relative URL** mark `/` and then use the anchor `#xxx`. So the custom link for the menu will be: `/#xxx`. > > **Note the difference between `#xxx` and `/#xxx`** as custom link. > > > The best thing about this approach is that you'll not have to bother changing the link after you go live, and additionally, this needs no programming.
312,041
<p>I am trying to build the simplest of custom Gutenberg block by referring the handbook <a href="https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type/" rel="nofollow noreferrer">https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type/</a>.</p> <p>The directory structure is as follows:</p> <pre><code>wp-content plugins gutenberg-bolierplate-block block.js gutenberg-boilerplate-block.php </code></pre> <p><strong>Content of <code>gutenberg-boilerplate-block.php</code></strong></p> <pre><code>&lt;?php function gutenberg_bolierplate_block() { wp_register_script( 'gutenberg-boilerplate-block-es5', plugins_url( 'block.js', __FILE__ ), array( 'wp-blocks', 'wp-element' ) ); register_block_type( 'gutenberg-boilerplate-block/hello-world', array( 'editor_script' =&gt; 'gutenberg-boilerplate-block-es5', ) ); } add_action( 'init', 'gutenberg_bolierplate_block' ); </code></pre> <p><strong>Content of <code>block.js</code></strong></p> <pre><code>var el = wp.elements.createElement, registerBlockType = wp.blocks.registerBlockType, blockStyle = { backgroundColor: '#900', color: '#fff', padding: '20px' }; registerBlockType ( 'gutenberg-boilerplate-block/hello-world', { title: 'Hello World', icon: 'universal-access-alt', category: 'common', edit: function() { return el( 'p', { style: blockStyle }, 'Hello editor' ); }, save: function() { return el( 'p', { style: blockStyle }, 'Hello saved content' ); } } ); </code></pre> <p>But the block is <strong>never showing up in the inserter dialog</strong>. I tried in different browsers and also by clearing cache. This is the first time I am trying my hand with this and absolutely no idea what I am doing wrong.</p> <p>Any suggestion would greatly help!</p>
[ { "answer_id": 312037, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 1, "selected": false, "text": "<p>You will need <a href=\"https://codex.wordpress.org/Function_Reference/get_comment_meta\" rel=\"nofollow noreferrer\"><code>get_comment_meta</code></a> to pull that information from the database. You will need to know the metakey. If you don't have that, you will have to search the theme/plugin that generates the metadata for the occurence of <a href=\"https://codex.wordpress.org/Function_Reference/add_comment_meta\" rel=\"nofollow noreferrer\"><code>add_comment_meta</code></a> to find it.</p>\n\n<p>Where to hook depends on how your theme is listing the comments. If it simply uses <a href=\"https://developer.wordpress.org/reference/functions/wp_list_comments/\" rel=\"nofollow noreferrer\"><code>wp_list_comments</code></a> there is no filter to simply attach the metadata. You will need to change the callback argument using the <code>wp_list_comments_args</code> filter. Then you can make a callback function that specifies which comment and meta data to display and how (<a href=\"https://wordpress.stackexchange.com/questions/216351/comment-walker-vs-comment-callback\">learn more</a>).</p>\n" }, { "answer_id": 357377, "author": "leemon", "author_id": 33049, "author_profile": "https://wordpress.stackexchange.com/users/33049", "pm_score": 0, "selected": false, "text": "<p>As an easier alternative, you can use flexbox to reorder the comment items:</p>\n\n<pre><code>.comment-list article {\n display: flex;\n flex-wrap: wrap;\n}\n\n.comment-list .comment-meta,\n.comment-list .comment-content {\n flex: 0 0 100%;\n}\n\n.comment-list .comment-meta {\n order: 2;\n}\n</code></pre>\n" } ]
2018/08/21
[ "https://wordpress.stackexchange.com/questions/312041", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/109082/" ]
I am trying to build the simplest of custom Gutenberg block by referring the handbook <https://wordpress.org/gutenberg/handbook/blocks/writing-your-first-block-type/>. The directory structure is as follows: ``` wp-content plugins gutenberg-bolierplate-block block.js gutenberg-boilerplate-block.php ``` **Content of `gutenberg-boilerplate-block.php`** ``` <?php function gutenberg_bolierplate_block() { wp_register_script( 'gutenberg-boilerplate-block-es5', plugins_url( 'block.js', __FILE__ ), array( 'wp-blocks', 'wp-element' ) ); register_block_type( 'gutenberg-boilerplate-block/hello-world', array( 'editor_script' => 'gutenberg-boilerplate-block-es5', ) ); } add_action( 'init', 'gutenberg_bolierplate_block' ); ``` **Content of `block.js`** ``` var el = wp.elements.createElement, registerBlockType = wp.blocks.registerBlockType, blockStyle = { backgroundColor: '#900', color: '#fff', padding: '20px' }; registerBlockType ( 'gutenberg-boilerplate-block/hello-world', { title: 'Hello World', icon: 'universal-access-alt', category: 'common', edit: function() { return el( 'p', { style: blockStyle }, 'Hello editor' ); }, save: function() { return el( 'p', { style: blockStyle }, 'Hello saved content' ); } } ); ``` But the block is **never showing up in the inserter dialog**. I tried in different browsers and also by clearing cache. This is the first time I am trying my hand with this and absolutely no idea what I am doing wrong. Any suggestion would greatly help!
You will need [`get_comment_meta`](https://codex.wordpress.org/Function_Reference/get_comment_meta) to pull that information from the database. You will need to know the metakey. If you don't have that, you will have to search the theme/plugin that generates the metadata for the occurence of [`add_comment_meta`](https://codex.wordpress.org/Function_Reference/add_comment_meta) to find it. Where to hook depends on how your theme is listing the comments. If it simply uses [`wp_list_comments`](https://developer.wordpress.org/reference/functions/wp_list_comments/) there is no filter to simply attach the metadata. You will need to change the callback argument using the `wp_list_comments_args` filter. Then you can make a callback function that specifies which comment and meta data to display and how ([learn more](https://wordpress.stackexchange.com/questions/216351/comment-walker-vs-comment-callback)).
312,103
<p>I've read many related questions and have tried all that I could so make sure it's actually a duplicate before flagging please. </p> <p>I've been using WordPress for about 6 years so when I say I'm stuck, I really mean it. </p> <p>I'm trying to add custom meta boxes to a CPT, <code>boat</code>. Below is my code and the error I'm getting.</p> <p>Error message: </p> <p><b><code>Notice: Undefined variable: boat_make in /path/to/file/wp-content/plugins/syb/admin/class-syb-admin.php on line 150</code></b></p> <p>This error message is the same for both fields. </p> <p>Here is my code: </p> <pre><code>/** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_admin_hooks() { ... /** * Add metabox and register custom fields * * @link https://code.tutsplus.com/articles/rock-solid-wordpress-30-themes-using-custom-post-types--net-12093 */ $this-&gt;loader-&gt;add_action( 'add_meta_boxes', $plugin_admin, 'rerender_meta_options' ); $this-&gt;loader-&gt;add_action( 'save_post', $plugin_admin, 'save_meta_options' ); } ... /** * Save Custom Fields * * @since 1.0.0 */ public function save_meta_options() { if ( ! current_user_can( '' ) ) return; global $post; update_post_meta($post-&gt;ID, "customer_id", $_POST["customer_id"]); update_post_meta($post-&gt;ID, "boat_make", $_POST["boat_make"]); } /** * Create a meta box for our custom fields * * @since 1.0.0 */ public function rerender_meta_options() { add_meta_box("boat-meta", "Boat Details", array($this, "display_meta_options"), "boat", "normal", "low"); } /** * Display meta box and custom fields * * @since 1.0.0 */ public function display_meta_options() { global $post; $custom = get_post_custom($post-&gt;ID); var_dump($custom); if (isset($custom["customer_id"][0])) { $customer_id = $custom["customer_id"][0]; } ?&gt; &lt;label&gt;&lt;?php _e( 'Boat Colour:', $this-&gt;plugin_name ); ?&gt;&lt;/label&gt;&lt;input name="customer_id" value="&lt;?php echo $customer_id; ?&gt;" /&gt;&lt;br&gt; &lt;?php if (isset($custom["boat_make"][0])) { $boat_make = $custom["boat_make"][0]; } ?&gt; &lt;label&gt;&lt;?php _e( 'Boat Make:', $this-&gt;plugin_name ); ?&gt;&lt;/label&gt;&lt;textarea name="boat_make"&gt;&lt;?php echo $boat_make; ?&gt;&lt;/textarea&gt; &lt;?php } </code></pre> <p>Loader method: </p> <pre><code>class Syb_Loader { /** * The array of actions registered with WordPress. * * @since 1.0.0 * @access protected * @var array $actions The actions registered with WordPress to fire when the plugin loads. */ protected $actions; /** * The array of filters registered with WordPress. * * @since 1.0.0 * @access protected * @var array $filters The filters registered with WordPress to fire when the plugin loads. */ protected $filters; /** * Initialize the collections used to maintain the actions and filters. * * @since 1.0.0 */ public function __construct() { $this-&gt;actions = array(); $this-&gt;filters = array(); } /** * Add a new action to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress action that is being registered. * @param object $component A reference to the instance of the object on which the action is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. The priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1. */ public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this-&gt;actions = $this-&gt;add( $this-&gt;actions, $hook, $component, $callback, $priority, $accepted_args ); } /** * Add a new filter to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. The priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1 */ public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this-&gt;filters = $this-&gt;add( $this-&gt;filters, $hook, $component, $callback, $priority, $accepted_args ); } /** * A utility function that is used to register the actions and hooks into a single * collection. * * @since 1.0.0 * @access private * @param array $hooks The collection of hooks that is being registered (that is, actions or filters). * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority The priority at which the function should be fired. * @param int $accepted_args The number of arguments that should be passed to the $callback. * @return array The collection of actions and filters registered with WordPress. */ private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) { $hooks[] = array( 'hook' =&gt; $hook, 'component' =&gt; $component, 'callback' =&gt; $callback, 'priority' =&gt; $priority, 'accepted_args' =&gt; $accepted_args ); return $hooks; } /** * Register the filters and actions with WordPress. * * @since 1.0.0 */ public function run() { foreach ( $this-&gt;filters as $hook ) { add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } foreach ( $this-&gt;actions as $hook ) { add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } } } </code></pre>
[ { "answer_id": 312105, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>It's not even that $custom[\"boat_make\"][0], but not even $custom[\"boat_make\"] is set.</p>\n\n<p>Because of that, you cannot ask: <code>if (isset($custom[\"boat_make\"][0]))</code></p>\n\n<p>Check your database and see if the post meta exists for \"boat_make\"</p>\n\n<p>What does it look like when you do your <code>var_dump($custom);</code> ?</p>\n" }, { "answer_id": 312106, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 2, "selected": true, "text": "<p>Before saving your meta data, you have <code>if ( ! current_user_can( '' ) ) return</code></p>\n\n<p>I've never run current_user_can against and empty string of capabilities, so I'm not sure what your results are going to be, but it's very possible this returns a false, and you return at this point.</p>\n\n<p>Also, be sure you sanitize your $_POST data before sticking it in the database.</p>\n" } ]
2018/08/21
[ "https://wordpress.stackexchange.com/questions/312103", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/76059/" ]
I've read many related questions and have tried all that I could so make sure it's actually a duplicate before flagging please. I've been using WordPress for about 6 years so when I say I'm stuck, I really mean it. I'm trying to add custom meta boxes to a CPT, `boat`. Below is my code and the error I'm getting. Error message: **`Notice: Undefined variable: boat_make in /path/to/file/wp-content/plugins/syb/admin/class-syb-admin.php on line 150`** This error message is the same for both fields. Here is my code: ``` /** * Register all of the hooks related to the admin area functionality * of the plugin. * * @since 1.0.0 * @access private */ private function define_admin_hooks() { ... /** * Add metabox and register custom fields * * @link https://code.tutsplus.com/articles/rock-solid-wordpress-30-themes-using-custom-post-types--net-12093 */ $this->loader->add_action( 'add_meta_boxes', $plugin_admin, 'rerender_meta_options' ); $this->loader->add_action( 'save_post', $plugin_admin, 'save_meta_options' ); } ... /** * Save Custom Fields * * @since 1.0.0 */ public function save_meta_options() { if ( ! current_user_can( '' ) ) return; global $post; update_post_meta($post->ID, "customer_id", $_POST["customer_id"]); update_post_meta($post->ID, "boat_make", $_POST["boat_make"]); } /** * Create a meta box for our custom fields * * @since 1.0.0 */ public function rerender_meta_options() { add_meta_box("boat-meta", "Boat Details", array($this, "display_meta_options"), "boat", "normal", "low"); } /** * Display meta box and custom fields * * @since 1.0.0 */ public function display_meta_options() { global $post; $custom = get_post_custom($post->ID); var_dump($custom); if (isset($custom["customer_id"][0])) { $customer_id = $custom["customer_id"][0]; } ?> <label><?php _e( 'Boat Colour:', $this->plugin_name ); ?></label><input name="customer_id" value="<?php echo $customer_id; ?>" /><br> <?php if (isset($custom["boat_make"][0])) { $boat_make = $custom["boat_make"][0]; } ?> <label><?php _e( 'Boat Make:', $this->plugin_name ); ?></label><textarea name="boat_make"><?php echo $boat_make; ?></textarea> <?php } ``` Loader method: ``` class Syb_Loader { /** * The array of actions registered with WordPress. * * @since 1.0.0 * @access protected * @var array $actions The actions registered with WordPress to fire when the plugin loads. */ protected $actions; /** * The array of filters registered with WordPress. * * @since 1.0.0 * @access protected * @var array $filters The filters registered with WordPress to fire when the plugin loads. */ protected $filters; /** * Initialize the collections used to maintain the actions and filters. * * @since 1.0.0 */ public function __construct() { $this->actions = array(); $this->filters = array(); } /** * Add a new action to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress action that is being registered. * @param object $component A reference to the instance of the object on which the action is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. The priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1. */ public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args ); } /** * Add a new filter to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. The priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1 */ public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args ); } /** * A utility function that is used to register the actions and hooks into a single * collection. * * @since 1.0.0 * @access private * @param array $hooks The collection of hooks that is being registered (that is, actions or filters). * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority The priority at which the function should be fired. * @param int $accepted_args The number of arguments that should be passed to the $callback. * @return array The collection of actions and filters registered with WordPress. */ private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) { $hooks[] = array( 'hook' => $hook, 'component' => $component, 'callback' => $callback, 'priority' => $priority, 'accepted_args' => $accepted_args ); return $hooks; } /** * Register the filters and actions with WordPress. * * @since 1.0.0 */ public function run() { foreach ( $this->filters as $hook ) { add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } foreach ( $this->actions as $hook ) { add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } } } ```
Before saving your meta data, you have `if ( ! current_user_can( '' ) ) return` I've never run current\_user\_can against and empty string of capabilities, so I'm not sure what your results are going to be, but it's very possible this returns a false, and you return at this point. Also, be sure you sanitize your $\_POST data before sticking it in the database.
312,112
<p>I have setup my custom post's custom taxonomy's permalink structure to be:</p> <p><strong>custom post type > custom taxonomy > post</strong> (from <a href="https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post">this helpful Q&amp;A</a>)</p> <p>Now I'm hoping to be able to code taxonomy.php to automatically loop posts based on the current permalink, ie: if the URL is <strong>example.com/writing/fiction/</strong> then the page (taxonomy.php) will show all posts with the taxonomy term "fiction" or if the URL is <strong>example.com/writing/non-fiction</strong> then taxonomy.php will show all posts with taxonomy term "non-fiction".</p> <p>The goal is to only need 1 taxonomy.php file.</p> <p>Here is current code (comment where I'm looking to make term automatic/dynamic):</p> <pre><code> &lt;?php $posts = array ( 'post_type' =&gt; 'writing', 'posts_per_page' =&gt; -1, 'tax_query' =&gt; array( array( 'taxonomy' =&gt; 'type', 'terms' =&gt; 'fiction', // looking to automate this, based on URL ), ), ); $loop = new WP_Query( $posts ); while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post(); ?&gt; &lt;a href="&lt;?php the_permalink();?&gt;"&gt; &lt;?php the_title('&lt;h2&gt;','&lt;/h2&gt;');?&gt; &lt;/a&gt; &lt;?php endwhile; wp_reset_postdata(); ?&gt; </code></pre>
[ { "answer_id": 312113, "author": "codeview", "author_id": 40679, "author_profile": "https://wordpress.stackexchange.com/users/40679", "pm_score": 1, "selected": false, "text": "<p>Got it to work with:</p>\n\n<pre><code>$queried_object = get_queried_object () ;\n</code></pre>\n\n<p>and</p>\n\n<pre><code>'terms' =&gt; $queried_object-&gt;slug,\n</code></pre>\n\n<p>full code now:</p>\n\n<pre><code> &lt;?php\n $queried_object = get_queried_object () ;\n $posts = array (\n 'post_type' =&gt; 'writing',\n 'posts_per_page' =&gt; -1,\n 'tax_query' =&gt; array(\n array(\n 'taxonomy' =&gt; 'type',\n 'field' =&gt; 'slug',\n 'terms' =&gt; $queried_object-&gt;slug,\n ),\n ),\n );\n $loop = new WP_Query( $posts );\n while ( $loop-&gt;have_posts() ) : $loop-&gt;the_post();\n ?&gt;\n &lt;a href=\"&lt;?php the_permalink();?&gt;\"&gt;\n &lt;?php the_title('&lt;h2&gt;','&lt;/h2&gt;');?&gt;\n &lt;/a&gt;\n &lt;?php endwhile; wp_reset_postdata(); ?&gt;\n</code></pre>\n" }, { "answer_id": 312114, "author": "David Sword", "author_id": 132362, "author_profile": "https://wordpress.stackexchange.com/users/132362", "pm_score": 0, "selected": false, "text": "<p>You should be able to get what you're after with:</p>\n\n<pre><code>'terms' =&gt; get_query_var( 'type' ),\n</code></pre>\n" } ]
2018/08/21
[ "https://wordpress.stackexchange.com/questions/312112", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40679/" ]
I have setup my custom post's custom taxonomy's permalink structure to be: **custom post type > custom taxonomy > post** (from [this helpful Q&A](https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post)) Now I'm hoping to be able to code taxonomy.php to automatically loop posts based on the current permalink, ie: if the URL is **example.com/writing/fiction/** then the page (taxonomy.php) will show all posts with the taxonomy term "fiction" or if the URL is **example.com/writing/non-fiction** then taxonomy.php will show all posts with taxonomy term "non-fiction". The goal is to only need 1 taxonomy.php file. Here is current code (comment where I'm looking to make term automatic/dynamic): ``` <?php $posts = array ( 'post_type' => 'writing', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'type', 'terms' => 'fiction', // looking to automate this, based on URL ), ), ); $loop = new WP_Query( $posts ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <a href="<?php the_permalink();?>"> <?php the_title('<h2>','</h2>');?> </a> <?php endwhile; wp_reset_postdata(); ?> ```
Got it to work with: ``` $queried_object = get_queried_object () ; ``` and ``` 'terms' => $queried_object->slug, ``` full code now: ``` <?php $queried_object = get_queried_object () ; $posts = array ( 'post_type' => 'writing', 'posts_per_page' => -1, 'tax_query' => array( array( 'taxonomy' => 'type', 'field' => 'slug', 'terms' => $queried_object->slug, ), ), ); $loop = new WP_Query( $posts ); while ( $loop->have_posts() ) : $loop->the_post(); ?> <a href="<?php the_permalink();?>"> <?php the_title('<h2>','</h2>');?> </a> <?php endwhile; wp_reset_postdata(); ?> ```
312,120
<p>I am currently working on a plugin using WordPress. I created a register page that allow users to register, this information is then stored in custom database table called finusers.</p> <p>This is what I have done so far:</p> <p>The code below is used to register users into custom table called finusers. </p> <pre><code> function db_insert($emailAdd, $password){ global $wpdb, $formErr; if(1 &gt; count($formErr-&gt;get_error_messages())){ $table = $wpdb-&gt;prefix."finusers"; $checksql = "SELECT * FROM $table WHERE email_address='$emailAdd'"; $checkdb = $wpdb-&gt;query($checksql); if($checkdb !=0){ echo "Email address is registered to a user"; }else { $data = array("email_address"=&gt;$emailAdd, "password"=&gt;$password); $format = array('%s'); $wpdb-&gt;insert($table,$data,$format); echo "You have successfully registered"; } } } </code></pre> <p>after the user has register, I then use the following function to authenticate the user</p> <pre><code> function authenticate($emailAdd, $password){ global $formErr; $username = $emailAdd; $password = $password; $check = wp_authenticate_username_password(NULL, $username, $password); if(1 &gt; count($formErr-&gt;get_error_messages())){ if(is_wp_error($check)){ echo "Falied"; }else{ echo "Success"; } } } </code></pre> <p>The problem that I am having here is, the wp_authenticate_username_password function is checking the the default users table to perform user authentication. How do I make it so that the user authentication is done using the custom table called finusers and not the default table users. </p> <p>Note: I do realize that code is it is prone to sql injection. Also any suggestions on how I can refine my code will be very helpful</p>
[ { "answer_id": 312352, "author": "Metal Zer0", "author_id": 149153, "author_profile": "https://wordpress.stackexchange.com/users/149153", "pm_score": 0, "selected": false, "text": "<p>After researching and looking up the WordPress Codex and support forums, this is the code that I have used to authenticate users stored in my custom table</p>\n\n<pre><code>add_filter('wp_authenticate_user', 'custom_authentication',10 ,2);\nfunction custom_authentication($emailAdd, $password) {\n global $wpdb, $formErr;\n\n if(1 &gt; count($formErr-&gt;get_error_messages())){\n $table = $wpdb-&gt;prefix.'finusers';\n $sql = \"SELECT * FROM $table WHERE email_address='$emailAdd' AND password='$password'\";\n $authenticate_user = $wpdb-&gt;query($sql);\n\n if($authenticate_user!=0){\n echo \"Successful authenticate user\";\n }else{\n echo \"Failed to authenticate user\";\n }\n }\n}\n</code></pre>\n\n<p>I will just post this as my answer it may be helpful to other people.</p>\n\n<p>I am posting an updated answer here. It took me while,but after reading and researching the StackExchange forum, the WordPress codex and more, this is my updated code</p>\n\n<pre><code>add_filter('wp_authenticate_user', 'custom_authentication', 10 , 2);\n\nfunction custom_authentication($emailAdd, $password) {\n include_once('././wp-includes/class-phpass.php');\n\n global $wpdb, $formErr;\n\n if(1 &gt; count($formErr-&gt;get_error_messages())){\n $hasher = new PasswordHash(8, TRUE);\n\n $table = $wpdb-&gt;prefix.'finusers';\n $results=$wpdb-&gt;get_row(\"SELECT * FROM $table WHERE email_address='$emailAdd'\");\n $hashed_pwd = $results-&gt;password;\n //echo $hashed_pwd;\n\n if($hasher-&gt;CheckPassword($password, $hashed_pwd)){\n echo \"Password Match Sccuessfully\";\n }else{\n echo \"Failed to authenticate, please chc\";\n }\n }\n}\n</code></pre>\n\n<p>Basically:</p>\n\n<ol>\n<li><p>added the filter so that I could override the wp_authenticate_user\nhook and define my own custom authentication function.</p></li>\n<li><p>Used $wpdb function, to match the email address stored in the database against the email address the user enters in form.</p></li>\n<li><p>if the email address matched the email address stored in the database, than extract and stored hashed password in a variable, in this case, $hashed_pwd and compared it with the plain text password stored in the variable $password. if the passwords matched user has been successfully authenticated.</p></li>\n<li><p>One thing to note here is that a another step can be added. This step verifies the users email address; check if the email address exists in the <strong>custom table</strong> in the WordPress database before checking the password. </p></li>\n</ol>\n" }, { "answer_id": 374948, "author": "Aslam Khan", "author_id": 179201, "author_profile": "https://wordpress.stackexchange.com/users/179201", "pm_score": 2, "selected": false, "text": "<p>After researching and looking up the WordPress Codex, this is the code that I have used to authenticate..</p>\n<p>I hope this helpful to all friends .it's working fine for me :)</p>\n<pre><code> $creds = array(\n 'user_login' =&gt; $username,\n 'user_password' =&gt; $userpassword,\n 'remember' =&gt; true\n );\n \n if(!empty($username) &amp;&amp; !empty($userpassword)) {\n \n if(!username_exists($username)) {\n\n $userdata = array(\n 'user_login' =&gt; $username,\n 'user_email' =&gt; $useremail, \n 'user_pass' =&gt; $userpassword, \n 'role' =&gt; 'customer' \n );\n\n $user_id = wp_insert_user( $userdata ) ; \n \n $user = wp_signon( $creds, false );\n wp_set_current_user($user-&gt;ID,$username); \n wp_set_auth_cookie($user-&gt;ID, true, false ); \n\n wp_redirect(site_url()); \n \n \n }\n</code></pre>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312120", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149153/" ]
I am currently working on a plugin using WordPress. I created a register page that allow users to register, this information is then stored in custom database table called finusers. This is what I have done so far: The code below is used to register users into custom table called finusers. ``` function db_insert($emailAdd, $password){ global $wpdb, $formErr; if(1 > count($formErr->get_error_messages())){ $table = $wpdb->prefix."finusers"; $checksql = "SELECT * FROM $table WHERE email_address='$emailAdd'"; $checkdb = $wpdb->query($checksql); if($checkdb !=0){ echo "Email address is registered to a user"; }else { $data = array("email_address"=>$emailAdd, "password"=>$password); $format = array('%s'); $wpdb->insert($table,$data,$format); echo "You have successfully registered"; } } } ``` after the user has register, I then use the following function to authenticate the user ``` function authenticate($emailAdd, $password){ global $formErr; $username = $emailAdd; $password = $password; $check = wp_authenticate_username_password(NULL, $username, $password); if(1 > count($formErr->get_error_messages())){ if(is_wp_error($check)){ echo "Falied"; }else{ echo "Success"; } } } ``` The problem that I am having here is, the wp\_authenticate\_username\_password function is checking the the default users table to perform user authentication. How do I make it so that the user authentication is done using the custom table called finusers and not the default table users. Note: I do realize that code is it is prone to sql injection. Also any suggestions on how I can refine my code will be very helpful
After researching and looking up the WordPress Codex, this is the code that I have used to authenticate.. I hope this helpful to all friends .it's working fine for me :) ``` $creds = array( 'user_login' => $username, 'user_password' => $userpassword, 'remember' => true ); if(!empty($username) && !empty($userpassword)) { if(!username_exists($username)) { $userdata = array( 'user_login' => $username, 'user_email' => $useremail, 'user_pass' => $userpassword, 'role' => 'customer' ); $user_id = wp_insert_user( $userdata ) ; $user = wp_signon( $creds, false ); wp_set_current_user($user->ID,$username); wp_set_auth_cookie($user->ID, true, false ); wp_redirect(site_url()); } ```
312,126
<p>I was going through the source code of Gutenberg, for e.g. <a href="https://github.com/WordPress/gutenberg/blob/master/edit-post/components/visual-editor/block-inspector-button.js" rel="nofollow noreferrer">this</a> and cannot understand how they handle translations... </p> <p>They do import this <code>import { __ } from '@wordpress/i18n'</code> and then in the source code they use this <code>speak( __( 'Block settings closed' ) );</code>. </p> <p>Can anybody tell me how they manage these translations within ReactJS to be collected in a normal .po file? </p> <p>I suppose they have some build process which goes through all of the files, including JS and collects them, but not sure.</p>
[ { "answer_id": 312127, "author": "kero", "author_id": 108180, "author_profile": "https://wordpress.stackexchange.com/users/108180", "pm_score": 4, "selected": true, "text": "<p>In the <a href=\"https://github.com/WordPress/gutenberg\" rel=\"noreferrer\">Gutenberg's GitHub repository</a> you can see the source of the i18n package that is used. In this source, you'll see <strong>Jed</strong> getting imported <a href=\"https://github.com/WordPress/gutenberg/blob/f02064f12a148df60b8d79801858ce3699bdfb89/packages/i18n/src/index.js#L4\" rel=\"noreferrer\">(line 4 of gutenberg/packages/i18n/src/index.js)</a> and then being used for most of the translation tasks under the hood.</p>\n<p><a href=\"https://messageformat.github.io/Jed/\" rel=\"noreferrer\">Jed</a> introduces the &quot;Gettext Style i18n for Modern JavaScript Apps&quot; (or at least so it says on their site).</p>\n<p>Your question is for the .po files. Jed explains on their site:</p>\n<blockquote>\n<p>There are quite a few available .po to .json converters out there. Gettext .po files are standard output from most decent translation companies, as it's an old standard.</p>\n<p>I currently use: <a href=\"https://www.npmjs.org/package/po2json\" rel=\"noreferrer\">po2json</a></p>\n<p>However, I'd like to add this functionality to a separate Jed module in a future version.</p>\n</blockquote>\n<p><strong>However, this does not seem to apply here.</strong></p>\n<p>Further digging turns out, <code>setLocaleData( data: Object, domain: string )</code> is used to pass the translations, <a href=\"https://github.com/WordPress/gutenberg/blob/1d9288443b38d254092f38d0d818f96be22346ad/lib/client-assets.php#L1308\" rel=\"noreferrer\">in a manner like so</a>:</p>\n<pre><code>$locale_data = gutenberg_get_jed_locale_data( 'gutenberg' );\nwp_add_inline_script(\n 'wp-i18n',\n 'wp.i18n.setLocaleData( ' . json_encode( $locale_data ) . ' );'\n);\n</code></pre>\n<p><a href=\"https://github.com/WordPress/gutenberg/blob/955f7b7e8682de100719c6affcfd304dd7cf23ac/lib/i18n.php#L21\" rel=\"noreferrer\">(<code>gutenberg_get_jed_locale_data( $domain )</code> being more or less a wrapper for <code>get_translations_for_domain( $domain )</code> )</a></p>\n<p>So it seems WordPress retrieves the translation data via PHP and then passes it to Jed. Jed itself does not seem to load any translation files.</p>\n<p>The package's <a href=\"https://github.com/WordPress/gutenberg/tree/a1bc317086fca7602f03fcf88ea0c1de514656c3/packages/i18n#build\" rel=\"noreferrer\">readme also explains how to properly generate the .pot file</a> containing the localized strings.</p>\n<blockquote>\n<p>The package also includes a <code>pot-to-php</code> script used to generate a php files containing the messages listed in a .pot file. This is useful to trick WordPress.org translation strings discovery since at the moment, WordPress.org is not capable of parsing strings directly from JavaScript files.</p>\n<pre><code>npx pot-to-php languages/myplugin.pot languages/myplugin-translations.php text-domain\n</code></pre>\n</blockquote>\n" }, { "answer_id": 312130, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 2, "selected": false, "text": "<p>At least for now, as long as there is no better automated process, I would suggest not to generate .pot files from JS at all.</p>\n\n<p>As @kero explains in his answer right now GB translations are being passed as a kind of blob array from the .mo file into JS. This workflow will break all localization tampering plugins which rely on filtering the results of <code>__</code> and associates. A better workflow will be to have an explicit generation of the blob array from strings being translated with <code>__</code> calls, similar to how you would do JS translation in non GB context. This will also solve the issue of generating .pot files.</p>\n\n<p>What is missing here is some automated process that will run over JS files and produce he relevant PHP code, which in turn can be analyzed by tools like poedit. </p>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312126", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149161/" ]
I was going through the source code of Gutenberg, for e.g. [this](https://github.com/WordPress/gutenberg/blob/master/edit-post/components/visual-editor/block-inspector-button.js) and cannot understand how they handle translations... They do import this `import { __ } from '@wordpress/i18n'` and then in the source code they use this `speak( __( 'Block settings closed' ) );`. Can anybody tell me how they manage these translations within ReactJS to be collected in a normal .po file? I suppose they have some build process which goes through all of the files, including JS and collects them, but not sure.
In the [Gutenberg's GitHub repository](https://github.com/WordPress/gutenberg) you can see the source of the i18n package that is used. In this source, you'll see **Jed** getting imported [(line 4 of gutenberg/packages/i18n/src/index.js)](https://github.com/WordPress/gutenberg/blob/f02064f12a148df60b8d79801858ce3699bdfb89/packages/i18n/src/index.js#L4) and then being used for most of the translation tasks under the hood. [Jed](https://messageformat.github.io/Jed/) introduces the "Gettext Style i18n for Modern JavaScript Apps" (or at least so it says on their site). Your question is for the .po files. Jed explains on their site: > > There are quite a few available .po to .json converters out there. Gettext .po files are standard output from most decent translation companies, as it's an old standard. > > > I currently use: [po2json](https://www.npmjs.org/package/po2json) > > > However, I'd like to add this functionality to a separate Jed module in a future version. > > > **However, this does not seem to apply here.** Further digging turns out, `setLocaleData( data: Object, domain: string )` is used to pass the translations, [in a manner like so](https://github.com/WordPress/gutenberg/blob/1d9288443b38d254092f38d0d818f96be22346ad/lib/client-assets.php#L1308): ``` $locale_data = gutenberg_get_jed_locale_data( 'gutenberg' ); wp_add_inline_script( 'wp-i18n', 'wp.i18n.setLocaleData( ' . json_encode( $locale_data ) . ' );' ); ``` [(`gutenberg_get_jed_locale_data( $domain )` being more or less a wrapper for `get_translations_for_domain( $domain )` )](https://github.com/WordPress/gutenberg/blob/955f7b7e8682de100719c6affcfd304dd7cf23ac/lib/i18n.php#L21) So it seems WordPress retrieves the translation data via PHP and then passes it to Jed. Jed itself does not seem to load any translation files. The package's [readme also explains how to properly generate the .pot file](https://github.com/WordPress/gutenberg/tree/a1bc317086fca7602f03fcf88ea0c1de514656c3/packages/i18n#build) containing the localized strings. > > The package also includes a `pot-to-php` script used to generate a php files containing the messages listed in a .pot file. This is useful to trick WordPress.org translation strings discovery since at the moment, WordPress.org is not capable of parsing strings directly from JavaScript files. > > > > ``` > npx pot-to-php languages/myplugin.pot languages/myplugin-translations.php text-domain > > ``` > >
312,147
<p>I am looking to enqueue this script on the header of a wordpress page</p> <pre><code>&lt;script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="mydomainame" &gt;&lt;/script&gt; </code></pre> <p>I know how to use </p> <pre><code>function wp_mk_scripts() { if( is_page(11) ){ wp_enqueue_script( 'chargebee', 'https://js.chargebee.com/v2/chargebee.js', array(), '2', false ); } } add_action( 'wp_enqueue_scripts', 'wp_mk_scripts' ); </code></pre> <p>but how do I add the parameter <code>data-cb-site="mydomainame"</code> ?</p>
[ { "answer_id": 312153, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 4, "selected": true, "text": "<p>Please try code given below:</p>\n\n<pre><code>function add_data_attribute($tag, $handle) {\n if ( 'chargebee' !== $handle )\n return $tag;\n\n return str_replace( ' src', ' data-cb-site=\"mydomainame\" src', $tag );\n}\nadd_filter('script_loader_tag', 'add_data_attribute', 10, 2);\n</code></pre>\n" }, { "answer_id": 312154, "author": "JoaMika", "author_id": 40727, "author_profile": "https://wordpress.stackexchange.com/users/40727", "pm_score": 1, "selected": false, "text": "<pre><code>function wp_mk_scripts() {\n\nif ( is_page('331') ) {\n wp_enqueue_script( 'chargebee', 'https://js.chargebee.com/v2/chargebee.js', array(), 2.0 , false);\n }\n\n}\nadd_action( 'wp_enqueue_scripts', 'wp_mk_scripts' );\n\nadd_filter('script_loader_tag', 'add_attributes_to_script', 10, 3); \nfunction add_attributes_to_script( $tag, $handle, $src ) {\n if ( 'chargebee.js' === $handle ) {\n $tag = '&lt;script type=\"text/javascript\" src=\"' . esc_url( $src ) . '\" data-cb-site=\"mydomainame\" &gt;&lt;/script&gt;';\n } \n return $tag;\n}\n</code></pre>\n\n<p>Based on the answer of the sample thread posted by kero - However this doesn't work - i do not get the attribute loaded.</p>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312147", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/40727/" ]
I am looking to enqueue this script on the header of a wordpress page ``` <script src="https://js.chargebee.com/v2/chargebee.js" data-cb-site="mydomainame" ></script> ``` I know how to use ``` function wp_mk_scripts() { if( is_page(11) ){ wp_enqueue_script( 'chargebee', 'https://js.chargebee.com/v2/chargebee.js', array(), '2', false ); } } add_action( 'wp_enqueue_scripts', 'wp_mk_scripts' ); ``` but how do I add the parameter `data-cb-site="mydomainame"` ?
Please try code given below: ``` function add_data_attribute($tag, $handle) { if ( 'chargebee' !== $handle ) return $tag; return str_replace( ' src', ' data-cb-site="mydomainame" src', $tag ); } add_filter('script_loader_tag', 'add_data_attribute', 10, 2); ```
312,159
<p>I want to move page template files like <code>page-{slug}.php</code> to a sub-directory within my theme, in a way that WordPress will recognize them automatically. If the page templates of the said form doesn't exist within the sub-directory, then WordPress should fall back to the default template loading rules. How can I achieve that?</p> <p><strong>Note-1:</strong> <a href="https://wordpress.stackexchange.com/questions/227006/how-to-move-page-template-to-custom-folder">This</a> question and corresponding answers are more generic for page templates and <a href="https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder" rel="noreferrer">this</a> link mentions <code>template-parts/page</code>, which is not the same thing.</p> <p><strong>Note-2:</strong> I have multiple <code>page-{slug}.php</code> like page template files, so I want to move them to sub-directory for a more tidy file organization.</p>
[ { "answer_id": 312611, "author": "Fayaz", "author_id": 110572, "author_profile": "https://wordpress.stackexchange.com/users/110572", "pm_score": 5, "selected": true, "text": "<h2>How Page Templates are loaded:</h2>\n<p>According to the default <a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/#page-templates-within-the-template-hierarchy\" rel=\"noreferrer\">WordPress Template Hierarchy</a>, a <code>page</code> request loads a template based on the priority and naming as stated below:</p>\n<ol>\n<li><code>Custom Page Template</code>: if defined in the page editor.</li>\n<li><code>page-{slug}.php</code></li>\n<li><code>page-{url-encoded-slug}.php</code>: only for multi-byte characters.</li>\n<li><code>page-{id}.php</code></li>\n<li><code>page.php</code></li>\n<li><code>singular.php</code></li>\n<li><code>index.php</code></li>\n</ol>\n<p>Among these, <code>singular.php</code> and <code>index.php</code> are <strong>not</strong> actually page templates. <code>singular.php</code> is the fallback template for any single post types and <code>index.php</code> is the ultimate fallback template for anything that a WordPress template is supposed to load. So the first five are page templates.</p>\n<h2>How to inject template files from a sub-directory within the hierarchy:</h2>\n<p>WordPress core function <a href=\"https://developer.wordpress.org/reference/functions/get_page_template/\" rel=\"noreferrer\"><code>get_page_template()</code></a> generates the necessary <code>page</code> template hierarchy array and just before deciding exactly which template file to load from the hierarchy, WordPress fires the <strong><code>page_template_hierarchy</code></strong> filter hook. So the best way to add a sub-directory, where WordPress will look for <code>page-{slug}.php</code> templates automatically, is to use this filter and inject proper file names relative to that sub-directory within the page template hierarchy array.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> the original filter hook is a dynamic filter hook defined as <strong><a href=\"https://developer.wordpress.org/reference/hooks/type_template_hierarchy/\" rel=\"noreferrer\"><code>{$type}_template_hierarchy</code></a></strong>, which is located in <code>wp-includes/template.php</code> file. So when the <code>$type</code> is <code>page</code>, the filter hook becomes <code>page_template_hierarchy</code>.</p>\n</blockquote>\n<p>Now, for our purpose, we'll inject the <code>sub-directory/page-{slug}.php</code> file name just before <code>page-{slug}.php</code> within the template hierarchy array passed to the hooks callback function. That way, WordPress will load <code>sub-directory/page-{slug}.php</code> file if it exists, otherwise it'll follow the normal page template loading hierarchy. Of course, to maintain consistency, we'll still give <code>Custom Page Template</code> a higher priority compared to our <code>sub-directory/page-{slug}.php</code> file. So the modified page template hierarchy will become:</p>\n<ol>\n<li><code>Custom Page Template</code>: if defined in the page editor.</li>\n<li><code>sub-directory/page-{slug}.php</code></li>\n<li><code>sub-directory/page-{url-encoded-slug}.php</code>: only for multi-byte characters.</li>\n<li><code>page-{slug}.php</code></li>\n<li><code>page-{url-encoded-slug}.php</code>: only for multi-byte characters.</li>\n<li><code>page-{id}.php</code></li>\n<li><code>page.php</code></li>\n</ol>\n<hr />\n<h2>Sample <code>functions.php</code> CODE:</h2>\n<p>If you plan to do this change only on a single theme, then you may use the following CODE in your active theme's <code>functions.php</code> file:</p>\n<pre><code>// defining the sub-directory so that it can be easily accessed from elsewhere as well.\ndefine( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' );\n\nfunction wpse312159_page_template_add_subdir( $templates = array() ) {\n // Generally this doesn't happen, unless another plugin / theme does modifications\n // of their own. In that case, it's better not to mess with it again with our code.\n if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) &lt; 3 )\n return $templates;\n\n $page_tpl_idx = 0;\n if( $templates[0] === get_page_template_slug() ) {\n // if there is custom template, then our page-{slug}.php template is at the next index \n $page_tpl_idx = 1;\n }\n\n $page_tpls = array( WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx] );\n\n // As of WordPress 4.7, the URL decoded page-{$slug}.php template file is included in the\n // page template hierarchy just before the URL encoded page-{$slug}.php template file.\n // Also, WordPress always keeps the page id different from page slug. So page-{slug}.php will\n // always be different from page-{id}.php, even if you try to input the {id} as {slug}.\n // So this check will work for WordPress versions prior to 4.7 as well.\n if( $templates[$page_tpl_idx] === urldecode( $templates[$page_tpl_idx + 1] ) ) {\n $page_tpls[] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx + 1];\n }\n\n array_splice( $templates, $page_tpl_idx, 0, $page_tpls );\n\n return $templates;\n}\nadd_filter( 'page_template_hierarchy', 'wpse312159_page_template_add_subdir' );\n</code></pre>\n<hr />\n<h2>Sample Plugin:</h2>\n<p>If you want to follow the same template file organization in multiple themes, then it's best to keep this feature separate from your theme. In that case, instead of modifying the theme's <code>functions.php</code> file with the above sample CODE, you'll need to create a simple plugin with the same sample CODE.</p>\n<p>Save the following CODE with a file name e.g. <code>page-slug-template-subdir.php</code> within your WordPress <code>plugins</code> directory:</p>\n<pre><code>&lt;?php\n/*\nPlugin Name: WPSE Page Template page-slug.php to Sub Directory\nPlugin URI: https://wordpress.stackexchange.com/a/312159/110572\nDescription: Page Template with page-{slug}.php to a Sub Directory\nVersion: 1.0.0\nAuthor: Fayaz Ahmed\nAuthor URI: https://www.fayazmiraz.com/\n*/\n\n// defining the sub-directory so that it can be easily accessed from elsewhere as well.\ndefine( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' );\n\nfunction wpse312159_page_template_add_subdir( $templates = array() ) {\n // Generally this doesn't happen, unless another plugin / theme does modifications\n // of their own. In that case, it's better not to mess with it again with our code.\n if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) &lt; 3 )\n return $templates;\n\n $page_tpl_idx = 0;\n if( $templates[0] === get_page_template_slug() ) {\n // if there is custom template, then our page-{slug}.php template is at the next index \n $page_tpl_idx = 1;\n }\n\n $page_tpls = array( WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx] );\n uded in the\n // page template hierarchy just before the URL encoded page-{$slug}.php template file.\n // Also, WordPress always keeps the page id different from page slug. So page-{slug}.php will\n // always be different from page-{id}.php, even if you try to input the {id} as {slug}.\n // So this check will work for WordPress versions prior to 4.7 as well.\n if( $templates[$page_tpl_idx] === urldecode( $templates[$page_tpl_idx + 1] ) ) {\n $page_tpls[] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx + 1];\n }\n\n array_splice( $templates, $page_tpl_idx, 0, $page_tpls );\n\n return $templates;\n}\n// the original filter hook is {$type}_template_hierarchy,\n// wihch is located in wp-includes/template.php file\nadd_filter( 'page_template_hierarchy', 'wpse312159_page_template_add_subdir' );\n</code></pre>\n<hr />\n<h2>Usage:</h2>\n<blockquote>\n<p>With either of the above CODE, WordPress will recognize <code>page-{slug}.php</code> template files within <code>page-templates</code> directory of your theme automatically.</p>\n<p>Say for example, you have an <code>about</code> page. So, if it doesn't have a <code>custom page template</code> set from the editor, then WordPress will look for <code>THEME/page-templates/page-about.php</code> template file and if that doesn't exist, then WordPress will look for <code>THEME/page-about.php</code> template file and so on (i.e. the default page template hierarchy).</p>\n</blockquote>\n" }, { "answer_id": 404945, "author": "Antonio Gallo", "author_id": 49733, "author_profile": "https://wordpress.stackexchange.com/users/49733", "pm_score": 0, "selected": false, "text": "<p>Use the filter <em>{$type}_template_hierarchy</em> to alter the templates that WP searches.</p>\n<p>Example: move page's templates in a subdirectory and remove the &quot;page-&quot; prefix.</p>\n<pre><code>add_filter('page_template_hierarchy',function($templates){\n foreach ($templates as &amp;$tpl) {\n $tpl = 'pages/'.preg_replace('/^page-/i','', $tpl);\n }\n return $templates;\n});\n</code></pre>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312159", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149002/" ]
I want to move page template files like `page-{slug}.php` to a sub-directory within my theme, in a way that WordPress will recognize them automatically. If the page templates of the said form doesn't exist within the sub-directory, then WordPress should fall back to the default template loading rules. How can I achieve that? **Note-1:** [This](https://wordpress.stackexchange.com/questions/227006/how-to-move-page-template-to-custom-folder) question and corresponding answers are more generic for page templates and [this](https://developer.wordpress.org/themes/basics/organizing-theme-files/#page-templates-folder) link mentions `template-parts/page`, which is not the same thing. **Note-2:** I have multiple `page-{slug}.php` like page template files, so I want to move them to sub-directory for a more tidy file organization.
How Page Templates are loaded: ------------------------------ According to the default [WordPress Template Hierarchy](https://developer.wordpress.org/themes/template-files-section/page-template-files/#page-templates-within-the-template-hierarchy), a `page` request loads a template based on the priority and naming as stated below: 1. `Custom Page Template`: if defined in the page editor. 2. `page-{slug}.php` 3. `page-{url-encoded-slug}.php`: only for multi-byte characters. 4. `page-{id}.php` 5. `page.php` 6. `singular.php` 7. `index.php` Among these, `singular.php` and `index.php` are **not** actually page templates. `singular.php` is the fallback template for any single post types and `index.php` is the ultimate fallback template for anything that a WordPress template is supposed to load. So the first five are page templates. How to inject template files from a sub-directory within the hierarchy: ----------------------------------------------------------------------- WordPress core function [`get_page_template()`](https://developer.wordpress.org/reference/functions/get_page_template/) generates the necessary `page` template hierarchy array and just before deciding exactly which template file to load from the hierarchy, WordPress fires the **`page_template_hierarchy`** filter hook. So the best way to add a sub-directory, where WordPress will look for `page-{slug}.php` templates automatically, is to use this filter and inject proper file names relative to that sub-directory within the page template hierarchy array. > > ***Note:*** the original filter hook is a dynamic filter hook defined as **[`{$type}_template_hierarchy`](https://developer.wordpress.org/reference/hooks/type_template_hierarchy/)**, which is located in `wp-includes/template.php` file. So when the `$type` is `page`, the filter hook becomes `page_template_hierarchy`. > > > Now, for our purpose, we'll inject the `sub-directory/page-{slug}.php` file name just before `page-{slug}.php` within the template hierarchy array passed to the hooks callback function. That way, WordPress will load `sub-directory/page-{slug}.php` file if it exists, otherwise it'll follow the normal page template loading hierarchy. Of course, to maintain consistency, we'll still give `Custom Page Template` a higher priority compared to our `sub-directory/page-{slug}.php` file. So the modified page template hierarchy will become: 1. `Custom Page Template`: if defined in the page editor. 2. `sub-directory/page-{slug}.php` 3. `sub-directory/page-{url-encoded-slug}.php`: only for multi-byte characters. 4. `page-{slug}.php` 5. `page-{url-encoded-slug}.php`: only for multi-byte characters. 6. `page-{id}.php` 7. `page.php` --- Sample `functions.php` CODE: ---------------------------- If you plan to do this change only on a single theme, then you may use the following CODE in your active theme's `functions.php` file: ``` // defining the sub-directory so that it can be easily accessed from elsewhere as well. define( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' ); function wpse312159_page_template_add_subdir( $templates = array() ) { // Generally this doesn't happen, unless another plugin / theme does modifications // of their own. In that case, it's better not to mess with it again with our code. if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) < 3 ) return $templates; $page_tpl_idx = 0; if( $templates[0] === get_page_template_slug() ) { // if there is custom template, then our page-{slug}.php template is at the next index $page_tpl_idx = 1; } $page_tpls = array( WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx] ); // As of WordPress 4.7, the URL decoded page-{$slug}.php template file is included in the // page template hierarchy just before the URL encoded page-{$slug}.php template file. // Also, WordPress always keeps the page id different from page slug. So page-{slug}.php will // always be different from page-{id}.php, even if you try to input the {id} as {slug}. // So this check will work for WordPress versions prior to 4.7 as well. if( $templates[$page_tpl_idx] === urldecode( $templates[$page_tpl_idx + 1] ) ) { $page_tpls[] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx + 1]; } array_splice( $templates, $page_tpl_idx, 0, $page_tpls ); return $templates; } add_filter( 'page_template_hierarchy', 'wpse312159_page_template_add_subdir' ); ``` --- Sample Plugin: -------------- If you want to follow the same template file organization in multiple themes, then it's best to keep this feature separate from your theme. In that case, instead of modifying the theme's `functions.php` file with the above sample CODE, you'll need to create a simple plugin with the same sample CODE. Save the following CODE with a file name e.g. `page-slug-template-subdir.php` within your WordPress `plugins` directory: ``` <?php /* Plugin Name: WPSE Page Template page-slug.php to Sub Directory Plugin URI: https://wordpress.stackexchange.com/a/312159/110572 Description: Page Template with page-{slug}.php to a Sub Directory Version: 1.0.0 Author: Fayaz Ahmed Author URI: https://www.fayazmiraz.com/ */ // defining the sub-directory so that it can be easily accessed from elsewhere as well. define( 'WPSE_PAGE_TEMPLATE_SUB_DIR', 'page-templates' ); function wpse312159_page_template_add_subdir( $templates = array() ) { // Generally this doesn't happen, unless another plugin / theme does modifications // of their own. In that case, it's better not to mess with it again with our code. if( empty( $templates ) || ! is_array( $templates ) || count( $templates ) < 3 ) return $templates; $page_tpl_idx = 0; if( $templates[0] === get_page_template_slug() ) { // if there is custom template, then our page-{slug}.php template is at the next index $page_tpl_idx = 1; } $page_tpls = array( WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx] ); uded in the // page template hierarchy just before the URL encoded page-{$slug}.php template file. // Also, WordPress always keeps the page id different from page slug. So page-{slug}.php will // always be different from page-{id}.php, even if you try to input the {id} as {slug}. // So this check will work for WordPress versions prior to 4.7 as well. if( $templates[$page_tpl_idx] === urldecode( $templates[$page_tpl_idx + 1] ) ) { $page_tpls[] = WPSE_PAGE_TEMPLATE_SUB_DIR . '/' . $templates[$page_tpl_idx + 1]; } array_splice( $templates, $page_tpl_idx, 0, $page_tpls ); return $templates; } // the original filter hook is {$type}_template_hierarchy, // wihch is located in wp-includes/template.php file add_filter( 'page_template_hierarchy', 'wpse312159_page_template_add_subdir' ); ``` --- Usage: ------ > > With either of the above CODE, WordPress will recognize `page-{slug}.php` template files within `page-templates` directory of your theme automatically. > > > Say for example, you have an `about` page. So, if it doesn't have a `custom page template` set from the editor, then WordPress will look for `THEME/page-templates/page-about.php` template file and if that doesn't exist, then WordPress will look for `THEME/page-about.php` template file and so on (i.e. the default page template hierarchy). > > >
312,206
<p>I built the ajax loader as follows.</p> <p>How can I detect when it reaches the end of all posts? So that I can make the "More" button to disappear, or not clickable anymore.</p> <p>In page template:</p> <pre><code>WP_Query stuff... if ($press_posts-&gt;max_num_pages &gt; 1) : echo '&lt;a class="link-button" id="load-more"&gt;More&lt;/a&gt;'; endif; </code></pre> <p>functions.php</p> <pre><code>function more_post_ajax() { $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: text/html"); $args = array( 'cat' =&gt; 1, 'posts_per_page' =&gt; $ppp, 'offset' =&gt; $offset ); $loop = new WP_Query($args); while ($loop-&gt;have_posts()) { $loop-&gt;the_post(); get_template_part('template-parts/content', 'ajax'); } exit; } add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); add_action('wp_ajax_more_post_ajax', 'more_post_ajax'); </code></pre> <p>and javascripts:</p> <pre><code>&lt;script&gt; var ajaxUrl = "&lt;?php echo admin_url('admin-ajax.php')?&gt;"; var page = 1; var ppp = 6; // posts per page jQuery("#load-more").on("click", function() { jQuery("#load-more").addClass("disabled"); jQuery.post(ajaxUrl, { action: "more_post_ajax", offset: (page * ppp) + 1, ppp: ppp }).success(function(posts) { page++; jQuery("#press-listing").append(posts); // append to container jQuery("#load-more").removeClass("disabled"); }); }); &lt;/script&gt; </code></pre>
[ { "answer_id": 312230, "author": "firxworx", "author_id": 134244, "author_profile": "https://wordpress.stackexchange.com/users/134244", "pm_score": 0, "selected": false, "text": "<p>I agree with the commenter @TomJNowell it could worth looking into the REST API. However, regarding your specific question: </p>\n\n<p>Here's an idea:</p>\n\n<ul>\n<li>Check if there are any posts remaining in your <code>more_post_ajax()</code> function and include that in your response in addition to the posts you're sending back. For example, you could have a <code>more_posts</code> boolean flag, or perhaps a count; however you'd like to do it. </li>\n<li>On the js end of things, expand the implementation of <code>.success(function(posts) { ... })</code> to add logic that handles this new piece of information in the response. If no posts are remaining, you could disable/hide your <code>#load-more</code> element and perhaps add a message to the user that no posts are remaining.</li>\n</ul>\n\n<p>I'm not sure what exactly is in the template part that you call via <code>get_template_part('template-parts/content', 'ajax')</code> or what its doing so its hard to be more specific regarding that area. </p>\n\n<p>Either way, your instance of <code>WP_Query</code> stored in <code>$loop</code> has a <code>posts</code> property that's an array of your posts. I could assume you want to send the <code>posts</code> back as part of your response.</p>\n\n<p>The <code>WP_Query</code> property <code>found_posts</code> is a count of all posts that match your criteria without consideration of your offset (i.e. its total count of posts), unless this is disabled with the arg <code>no_found_rows</code> (N/A in this case). Since you know your posts per page and offset you have the information to pass back in your response if there are more posts available to load or not. Another way could be the <code>max_num_pages</code> property. </p>\n\n<p>You could combine these into an array/object and use <code>wp_send_json()</code> or <code>wp_send_json_success()</code> to send them and then process the response in js. You would need jQuery's <code>parseJSON()</code> to parse the response.</p>\n\n<p>If you're really married to what your template partial is outputting and liking how you are easily doing <code>jQuery(\"#press-listing\").append(posts)</code> on the js side to display it, you could capture the output of <code>get_template_part('template-parts/content', 'ajax');</code> using output buffering (a little dirty) to collect it for including in your response, e.g. </p>\n\n<pre><code>ob_start();\nget_template_part('template-parts/content', 'ajax');\n// call ob_get_contents() and load the return value into an array or string to send back\nob_end_clean();\n</code></pre>\n" }, { "answer_id": 312235, "author": "Raja Mohammed", "author_id": 97358, "author_profile": "https://wordpress.stackexchange.com/users/97358", "pm_score": 0, "selected": false, "text": "<p>Change in your code <code>$offet to $paged</code> variable WP_Query can keep track of the pages that will give you the total number of pages in your loop object as </p>\n\n<pre><code>$loop-&gt;max_num_pages\n\n&lt;script&gt;\n var ajaxUrl = \"&lt;?php echo admin_url('admin-ajax.php')?&gt;\";\n var page = 1;\n var ppp = 6; // posts per page\n\n jQuery(\"#load-more\").on(\"click\", function() {\n jQuery(\"#load-more\").addClass(\"disabled\");\n jQuery.post(ajaxUrl, {\n action: \"more_post_ajax\",\n page: page,\n ppp: ppp\n }).success(function(posts) {\n // execute this block only if there is post\n if(posts) { \n page++;\n jQuery(\"#press-listing\").append(posts); // append to container\n jQuery(\"#load-more\").removeClass(\"disabled\");\n }\n });\n\n });\n&lt;/script&gt;\n</code></pre>\n\n<p>And you php ajax function would be </p>\n\n<pre><code>function more_post_ajax() {\n $page = $_POST[\"page\"];\n $ppp = $_POST[\"ppp\"];\n header(\"Content-Type: text/html\");\n\n $args = array(\n 'cat' =&gt; 1,\n 'posts_per_page' =&gt; $ppp,\n 'paged' =&gt; $page\n );\n\n $loop = new WP_Query($args);\n\n if($loop-&gt;max_num_pages &lt;= $page):\n\n while ($loop-&gt;have_posts()) { $loop-&gt;the_post();\n get_template_part('template-parts/content', 'ajax');\n }\n exit;\n\n else:\n echo 0;\n die();\n\n endif;\n}\nadd_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax');\nadd_action('wp_ajax_more_post_ajax', 'more_post_ajax');\n</code></pre>\n" }, { "answer_id": 318520, "author": "Stickers", "author_id": 9508, "author_profile": "https://wordpress.stackexchange.com/users/9508", "pm_score": 3, "selected": true, "text": "<p>Page template:</p>\n\n<pre><code>&lt;div class=\"entry-content\"&gt;\n &lt;?php \n $args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; '2',\n 'paged' =&gt; 1,\n );\n $my_posts = new WP_Query($args);\n if ($my_posts-&gt;have_posts()) : \n ?&gt;\n &lt;div class=\"my-posts\"&gt;\n &lt;?php while ($my_posts-&gt;have_posts()) : $my_posts-&gt;the_post(); ?&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n &lt;?php endwhile; ?&gt;\n &lt;/div&gt;\n &lt;?php endif; ?&gt;\n &lt;div class=\"loadmore\"&gt;Load More...&lt;/div&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>Ajax jQuery (Load more button):</p>\n\n<pre><code>&lt;script type=\"text/javascript\"&gt;\nvar ajaxurl = \"&lt;?php echo admin_url('admin-ajax.php'); ?&gt;\";\nvar page = 2;\njQuery(function($) {\n $('body').on('click', '.loadmore', function() {\n var data = {\n 'action': 'load_posts_by_ajax',\n 'page': page,\n 'security': '&lt;?php echo wp_create_nonce(\"load_more_posts\"); ?&gt;'\n };\n\n max = &lt;?php echo $my_posts-&gt;max_num_pages; ?&gt;\n\n $.post(ajaxurl, data, function(response) {\n $('.my-posts').append(response);\n if (page &lt; max) {\n // end of posts\n }\n page++;\n });\n });\n});\n&lt;/script&gt;\n</code></pre>\n\n<p>Functions:</p>\n\n<pre><code>function load_posts_by_ajax_callback() {\n check_ajax_referer('load_more_posts', 'security');\n $paged = $_POST['page'];\n $args = array(\n 'post_type' =&gt; 'post',\n 'post_status' =&gt; 'publish',\n 'posts_per_page' =&gt; '2',\n 'paged' =&gt; $paged,\n );\n $my_posts = new WP_Query($args);\n if ($my_posts-&gt;have_posts()) :\n ?&gt;\n &lt;?php while ($my_posts-&gt;have_posts()) : $my_posts-&gt;the_post(); ?&gt;\n &lt;h2&gt;&lt;?php the_title(); ?&gt;&lt;/h2&gt;\n &lt;?php the_excerpt(); ?&gt;\n &lt;?php endwhile; ?&gt;\n &lt;?php\n endif;\n wp_die();\n}\nadd_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback');\nadd_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback');\n</code></pre>\n\n<p>Addition - Ajax jQuery (Load on scroll):</p>\n\n<pre><code>$(window).scroll(function() {\n if ($(window).scrollTop() == $(document).height() - $(window).height()) {\n var data = {\n 'action': 'load_posts_by_ajax',\n 'page': page,\n 'security': '&lt;?php echo wp_create_nonce(\"load_more_posts\"); ?&gt;'\n };\n\n $.post(ajaxurl, data, function(response) {\n $('.my-posts').append(response);\n page++;\n });\n }\n});\n</code></pre>\n\n<p><a href=\"https://artisansweb.net/load-wordpress-post-ajax/\" rel=\"nofollow noreferrer\">Source</a></p>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312206", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/9508/" ]
I built the ajax loader as follows. How can I detect when it reaches the end of all posts? So that I can make the "More" button to disappear, or not clickable anymore. In page template: ``` WP_Query stuff... if ($press_posts->max_num_pages > 1) : echo '<a class="link-button" id="load-more">More</a>'; endif; ``` functions.php ``` function more_post_ajax() { $offset = $_POST["offset"]; $ppp = $_POST["ppp"]; header("Content-Type: text/html"); $args = array( 'cat' => 1, 'posts_per_page' => $ppp, 'offset' => $offset ); $loop = new WP_Query($args); while ($loop->have_posts()) { $loop->the_post(); get_template_part('template-parts/content', 'ajax'); } exit; } add_action('wp_ajax_nopriv_more_post_ajax', 'more_post_ajax'); add_action('wp_ajax_more_post_ajax', 'more_post_ajax'); ``` and javascripts: ``` <script> var ajaxUrl = "<?php echo admin_url('admin-ajax.php')?>"; var page = 1; var ppp = 6; // posts per page jQuery("#load-more").on("click", function() { jQuery("#load-more").addClass("disabled"); jQuery.post(ajaxUrl, { action: "more_post_ajax", offset: (page * ppp) + 1, ppp: ppp }).success(function(posts) { page++; jQuery("#press-listing").append(posts); // append to container jQuery("#load-more").removeClass("disabled"); }); }); </script> ```
Page template: ``` <div class="entry-content"> <?php $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => '2', 'paged' => 1, ); $my_posts = new WP_Query($args); if ($my_posts->have_posts()) : ?> <div class="my-posts"> <?php while ($my_posts->have_posts()) : $my_posts->the_post(); ?> <h2><?php the_title(); ?></h2> <?php the_excerpt(); ?> <?php endwhile; ?> </div> <?php endif; ?> <div class="loadmore">Load More...</div> </div> ``` Ajax jQuery (Load more button): ``` <script type="text/javascript"> var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>"; var page = 2; jQuery(function($) { $('body').on('click', '.loadmore', function() { var data = { 'action': 'load_posts_by_ajax', 'page': page, 'security': '<?php echo wp_create_nonce("load_more_posts"); ?>' }; max = <?php echo $my_posts->max_num_pages; ?> $.post(ajaxurl, data, function(response) { $('.my-posts').append(response); if (page < max) { // end of posts } page++; }); }); }); </script> ``` Functions: ``` function load_posts_by_ajax_callback() { check_ajax_referer('load_more_posts', 'security'); $paged = $_POST['page']; $args = array( 'post_type' => 'post', 'post_status' => 'publish', 'posts_per_page' => '2', 'paged' => $paged, ); $my_posts = new WP_Query($args); if ($my_posts->have_posts()) : ?> <?php while ($my_posts->have_posts()) : $my_posts->the_post(); ?> <h2><?php the_title(); ?></h2> <?php the_excerpt(); ?> <?php endwhile; ?> <?php endif; wp_die(); } add_action('wp_ajax_load_posts_by_ajax', 'load_posts_by_ajax_callback'); add_action('wp_ajax_nopriv_load_posts_by_ajax', 'load_posts_by_ajax_callback'); ``` Addition - Ajax jQuery (Load on scroll): ``` $(window).scroll(function() { if ($(window).scrollTop() == $(document).height() - $(window).height()) { var data = { 'action': 'load_posts_by_ajax', 'page': page, 'security': '<?php echo wp_create_nonce("load_more_posts"); ?>' }; $.post(ajaxurl, data, function(response) { $('.my-posts').append(response); page++; }); } }); ``` [Source](https://artisansweb.net/load-wordpress-post-ajax/)
312,208
<p>Could someone have the same error when im trying to <a href="https://codex.wordpress.org/Navigation_Menus" rel="nofollow noreferrer">register a menu</a>?</p> <p>function.php</p> <pre><code>function register_my_menu() { register_nav_menu('header-menu',__( 'Header Menu' )); } add_action( 'init', 'register_my_menu' ); </code></pre> <p>error</p> <blockquote> <p>function register_my_menu() { register_nav_menu('header-menu',__( 'Header Menu' )); } add_action( 'init', 'register_my_menu' ); Warning: Cannot modify header information - headers already sent by (output started at /home/milibyte/public_html/wp-content/themes/test/functions.php:4) in /home/milibyte/public_html/wp-admin/includes/misc.php on line 1126</p> </blockquote> <p><a href="https://github.com/fdesur/phpProblem.git" rel="nofollow noreferrer">GitHub</a></p> <p>Regards!</p>
[ { "answer_id": 312210, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>I believe you are running your action too soon.</p>\n\n<p>Don't run it at 'init', use 'after_setup_theme' instead.</p>\n\n<p><code>add_action( 'after_setup_theme', 'register_my_menu' );</code></p>\n" }, { "answer_id": 312211, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>The error may display itself when there are:</p>\n\n<ul>\n<li>Blank lines at the top or bottom of a document</li>\n<li>Too many spaces before, in between or after the beginning PHP tags</li>\n<li>There are too many unneeded spaces or blank lines in a specific part of a document</li>\n</ul>\n\n<p>Just to debug, try to do something like this.</p>\n\n<pre><code>function register_my_menu() { \n //do nothing \n} \nadd_action( 'init', 'register_my_menu' );\n</code></pre>\n\n<p>If you Google that issue you will get amazed by how many people have that just because of extra spaces or wrong things on the <code>functions.php</code>.</p>\n" }, { "answer_id": 312215, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 2, "selected": true, "text": "<pre><code>&lt;?php\nfunction register_my_menu() {\n register_nav_menu( 'header-menu',__( 'Header Menu' ) );\n}\nadd_action( 'after_setup_theme', 'register_my_menu' );\n</code></pre>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312208", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149189/" ]
Could someone have the same error when im trying to [register a menu](https://codex.wordpress.org/Navigation_Menus)? function.php ``` function register_my_menu() { register_nav_menu('header-menu',__( 'Header Menu' )); } add_action( 'init', 'register_my_menu' ); ``` error > > function register\_my\_menu() { register\_nav\_menu('header-menu',\_\_( > 'Header Menu' )); } add\_action( 'init', 'register\_my\_menu' ); Warning: > Cannot modify header information - headers already sent by (output > started at > /home/milibyte/public\_html/wp-content/themes/test/functions.php:4) in > /home/milibyte/public\_html/wp-admin/includes/misc.php on line 1126 > > > [GitHub](https://github.com/fdesur/phpProblem.git) Regards!
``` <?php function register_my_menu() { register_nav_menu( 'header-menu',__( 'Header Menu' ) ); } add_action( 'after_setup_theme', 'register_my_menu' ); ```
312,218
<p>I am trying to do something but I have problem...</p> <p>I wont show the list of my post, but from all titles I want remove text after last "-" (dash)</p> <p>My list of posts:</p> <blockquote> <ol> <li>My experience - this boy - first day - meet</li> <li>My love - i do not know - second day</li> <li>My first time - auuu - third time</li> </ol> </blockquote> <p>I would like to return this:</p> <blockquote> <ol> <li>My experience - this boy - first day</li> <li>My love - i do not know</li> <li>My first time</li> </ol> </blockquote> <p>I tried this:</p> <pre><code>&lt;?php $stringx = get_the_title(); echo preg_replace('/-[^-]*$/', '', $stringx); ?&gt; </code></pre> <p>But this return whole text... with the dashes.... </p> <p>also I tried this:</p> <p><a href="https://stackoverflow.com/questions/12042170/get-the-characters-before-the-last-dash">https://stackoverflow.com/questions/12042170/get-the-characters-before-the-last-dash</a></p> <p>Somone could help me how to output titles of post withoust text after last '-'?</p>
[ { "answer_id": 312223, "author": "C C", "author_id": 83299, "author_profile": "https://wordpress.stackexchange.com/users/83299", "pm_score": 3, "selected": true, "text": "<p>This is really a PHP question not so much a WP question -- but:</p>\n\n<pre><code>echo substr($stringx,0,strrpos($stringx,'-'));\n</code></pre>\n\n<p>Also I think your example #3 is wrong unless there are some cases where you want to exclude more than simply after the final dash character.</p>\n\n<p>Note - if you want to exclude both that final blank space along with the final dash that immediately follows it, then change the substr length by -1 to avoid the final blank space:</p>\n\n<pre><code>echo substr($stringx,0,strrpos($stringx,'-')-1);\n</code></pre>\n" }, { "answer_id": 312290, "author": "kibus90", "author_id": 140882, "author_profile": "https://wordpress.stackexchange.com/users/140882", "pm_score": 1, "selected": false, "text": "<p>I fount where were problem...</p>\n\n<p><a href=\"https://codex.wordpress.org/Function_Reference/wptexturize\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wptexturize</a></p>\n\n<p>Each dash (short dash) is changing for long dash</p>\n\n<p>I just wptexturize for titles by add to functions.php this code:</p>\n\n<pre><code>remove_filter('the_title', 'wptexturize');\n</code></pre>\n\n<p>and works well. But how can I get with long dash? I do not know... but I hope it will help someone in future.</p>\n" } ]
2018/08/22
[ "https://wordpress.stackexchange.com/questions/312218", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140882/" ]
I am trying to do something but I have problem... I wont show the list of my post, but from all titles I want remove text after last "-" (dash) My list of posts: > > 1. My experience - this boy - first day - meet > 2. My love - i do not know - second day > 3. My first time - auuu - third time > > > I would like to return this: > > 1. My experience - this boy - first day > 2. My love - i do not know > 3. My first time > > > I tried this: ``` <?php $stringx = get_the_title(); echo preg_replace('/-[^-]*$/', '', $stringx); ?> ``` But this return whole text... with the dashes.... also I tried this: <https://stackoverflow.com/questions/12042170/get-the-characters-before-the-last-dash> Somone could help me how to output titles of post withoust text after last '-'?
This is really a PHP question not so much a WP question -- but: ``` echo substr($stringx,0,strrpos($stringx,'-')); ``` Also I think your example #3 is wrong unless there are some cases where you want to exclude more than simply after the final dash character. Note - if you want to exclude both that final blank space along with the final dash that immediately follows it, then change the substr length by -1 to avoid the final blank space: ``` echo substr($stringx,0,strrpos($stringx,'-')-1); ```
312,231
<p>I am trying to apply discounts based on quantity amounts in the cart for each product. Each product has it's own quantity discounts set by custom fields. I'm using the action "woocommerce_before_calculate_totals" and in the foreach loop trying to apply the discount from the custom fields. However, it only works for the first item in the cart. The second item is set at the full price. I can't see why it doesn't work for the rest of the items in the cart.</p> <p>Here is my current code:</p> <pre><code>add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 20, 1 ); function set_custom_cart_item_price( $wc_cart ) { if ( is_admin() &amp;&amp; ! defined( 'DOING_AJAX' ) ) return; // First loop to check if product 11 is in cart foreach ( $wc_cart-&gt;get_cart() as $key =&gt; $cart_item ){ // This is necessary for WC 3.0+ $qty = $cart_item['quantity']; $discount1 = get_post_meta($cart_item['product_id'], '_discount_1_4_items', true); $discount2 = get_post_meta($cart_item['product_id'], '_discount_5_9_items', true); $discount3 = get_post_meta($cart_item['product_id'], '_discount_10_19_items', true); $discount4 = get_post_meta($cart_item['product_id'], '_discount_20_items', true); $OriginalPrice = $cart_item['data']-&gt;get_price(); if($qty &gt;= 1 &amp;&amp; $qty &lt;=4){ $FinalPrice = $OriginalPrice*$discount1; }elseif($qty &gt;= 5 &amp;&amp; $qty &lt;=9){ $FinalPrice = $OriginalPrice*$discount2; }elseif($qty &gt;= 10 &amp;&amp; $qty &lt;=19){ $FinalPrice = $OriginalPrice*$discount3; }elseif($qty &gt;= 20 ){ $FinalPrice = $OriginalPrice*$discount4; } $cart_item['data']-&gt;set_price( $FinalPrice ); } } </code></pre>
[ { "answer_id": 312233, "author": "Raja Mohammed", "author_id": 97358, "author_profile": "https://wordpress.stackexchange.com/users/97358", "pm_score": 0, "selected": false, "text": "<p>In your code, you are trying to equate $qty to the number of items <code>$qty = 5</code> which should be <code>$qty == 5</code>.</p>\n\n<p>You don't need to check if <code>$qty == 5 &amp;&amp; $qty == 10</code> you might need to change that to <code>||</code> operator to check for either of the case else the case might not be truthy. </p>\n\n<p>And you are applying discount 4 for all the four cases so you might need to refactor your code.</p>\n" }, { "answer_id": 312301, "author": "Tyler Robinson", "author_id": 81422, "author_profile": "https://wordpress.stackexchange.com/users/81422", "pm_score": 2, "selected": true, "text": "<p>So the answer to this is instead of placing the code in your functions.php, you create a \"woocommerce\" folder in your theme folder, and place the \"cart\" folder and the \"cart.php\" template file from the woocommerce plugin inside of that. Then you place the same code as in the \"woocommerce_before_calculate_totals\" action inside the loop of the cart template. So the code below is what I placed in the cart.php file and it now works!</p>\n\n<pre><code>$qty = $cart_item['quantity'];\n\n$discount1 = get_post_meta($cart_item['product_id'], '_discount_1_4_items', true);\n$discount2 = get_post_meta($cart_item['product_id'], '_discount_5_9_items', true);\n$discount3 = get_post_meta($cart_item['product_id'], '_discount_10_19_items', true);\n$discount4 = get_post_meta($cart_item['product_id'], '_discount_20_items', true);\n\n$OriginalPrice = $cart_item['data']-&gt;get_price();\n\nif($qty &gt;= 1 &amp;&amp; $qty &lt;=4){\n $FinalPrice = $OriginalPrice*$discount1;\n}elseif($qty &gt;= 5 &amp;&amp; $qty &lt;=9){\n $FinalPrice = $OriginalPrice*$discount2;\n}elseif($qty &gt;= 10 &amp;&amp; $qty &lt;=19){\n $FinalPrice = $OriginalPrice*$discount3;\n}elseif($qty &gt;= 20 ){\n $FinalPrice = $OriginalPrice*$discount4;\n}\n$cart_item['data']-&gt;set_price( $FinalPrice );\n</code></pre>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312231", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/81422/" ]
I am trying to apply discounts based on quantity amounts in the cart for each product. Each product has it's own quantity discounts set by custom fields. I'm using the action "woocommerce\_before\_calculate\_totals" and in the foreach loop trying to apply the discount from the custom fields. However, it only works for the first item in the cart. The second item is set at the full price. I can't see why it doesn't work for the rest of the items in the cart. Here is my current code: ``` add_action( 'woocommerce_before_calculate_totals', 'set_custom_cart_item_price', 20, 1 ); function set_custom_cart_item_price( $wc_cart ) { if ( is_admin() && ! defined( 'DOING_AJAX' ) ) return; // First loop to check if product 11 is in cart foreach ( $wc_cart->get_cart() as $key => $cart_item ){ // This is necessary for WC 3.0+ $qty = $cart_item['quantity']; $discount1 = get_post_meta($cart_item['product_id'], '_discount_1_4_items', true); $discount2 = get_post_meta($cart_item['product_id'], '_discount_5_9_items', true); $discount3 = get_post_meta($cart_item['product_id'], '_discount_10_19_items', true); $discount4 = get_post_meta($cart_item['product_id'], '_discount_20_items', true); $OriginalPrice = $cart_item['data']->get_price(); if($qty >= 1 && $qty <=4){ $FinalPrice = $OriginalPrice*$discount1; }elseif($qty >= 5 && $qty <=9){ $FinalPrice = $OriginalPrice*$discount2; }elseif($qty >= 10 && $qty <=19){ $FinalPrice = $OriginalPrice*$discount3; }elseif($qty >= 20 ){ $FinalPrice = $OriginalPrice*$discount4; } $cart_item['data']->set_price( $FinalPrice ); } } ```
So the answer to this is instead of placing the code in your functions.php, you create a "woocommerce" folder in your theme folder, and place the "cart" folder and the "cart.php" template file from the woocommerce plugin inside of that. Then you place the same code as in the "woocommerce\_before\_calculate\_totals" action inside the loop of the cart template. So the code below is what I placed in the cart.php file and it now works! ``` $qty = $cart_item['quantity']; $discount1 = get_post_meta($cart_item['product_id'], '_discount_1_4_items', true); $discount2 = get_post_meta($cart_item['product_id'], '_discount_5_9_items', true); $discount3 = get_post_meta($cart_item['product_id'], '_discount_10_19_items', true); $discount4 = get_post_meta($cart_item['product_id'], '_discount_20_items', true); $OriginalPrice = $cart_item['data']->get_price(); if($qty >= 1 && $qty <=4){ $FinalPrice = $OriginalPrice*$discount1; }elseif($qty >= 5 && $qty <=9){ $FinalPrice = $OriginalPrice*$discount2; }elseif($qty >= 10 && $qty <=19){ $FinalPrice = $OriginalPrice*$discount3; }elseif($qty >= 20 ){ $FinalPrice = $OriginalPrice*$discount4; } $cart_item['data']->set_price( $FinalPrice ); ```
312,243
<p>In my website this characters ​​ showing up on everywhere in blog content and title, after many hours of searching and googling cant find any useful answer i tried this meta but no luck</p> <pre><code>header("Content-Type: text/html; charset=ISO-8859-1"); &lt;meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"&gt; </code></pre> <p>Is there any way to rid-off this <code>​​</code> And many other characters: <code>‘</code> <code>â</code> <code>�</code></p> <p>Also tried Plugin search and replace but the character is not searchable.</p>
[ { "answer_id": 312376, "author": "user141080", "author_id": 141080, "author_profile": "https://wordpress.stackexchange.com/users/141080", "pm_score": 1, "selected": false, "text": "<p>If you search your content for these characters <code>‘ â �</code> you will not find them, because they are not there. Characters <code>‘ â �</code> like these are a sign, that the character encoding in the frontend does not match with that from the database. Normaly wordpress used for database, file endcoding and character encoding UTF-8. </p>\n" }, { "answer_id": 320568, "author": "Dev65", "author_id": 149061, "author_profile": "https://wordpress.stackexchange.com/users/149061", "pm_score": 2, "selected": true, "text": "<p>Found the answer after little bit search on google &amp; <a href=\"http://php.net/manual/en/function.htmlspecialchars-decode.php\" rel=\"nofollow noreferrer\">http://php.net/manual/en/function.htmlspecialchars-decode.php</a> , After a long time answered my own question thought maybe it will help someone.</p>\n\n<pre><code>htmlspecialchars_decode(utf8_decode(htmlentities(YOUR_STRING, ENT_COMPAT, 'utf-8', false)));\n</code></pre>\n" }, { "answer_id": 363403, "author": "David Hussey", "author_id": 185573, "author_profile": "https://wordpress.stackexchange.com/users/185573", "pm_score": 0, "selected": false, "text": "<p>Was searching for the same throughout the internet. Finally found a working solution. </p>\n\n<p>I tried method 1 listed on the below website and it works like charm.</p>\n\n<p>Just changed these two lines from wp-config.php:</p>\n\n<pre><code>define('DB_CHARSET', 'utf8');\ndefine('DB_COLLATE', '');\n</code></pre>\n\n<p>with</p>\n\n<pre><code>//define('DB_CHARSET', 'utf8');\n//define('DB_COLLATE', '');\n</code></pre>\n\n<p>Here is the article link: <a href=\"https://samacharpedia.com/fix-strange-character-encoding-issue-wordpress-post-content/\" rel=\"nofollow noreferrer\">https://samacharpedia.com/fix-strange-character-encoding-issue-wordpress-post-content/</a></p>\n" }, { "answer_id": 396378, "author": "Ramzan Shareef", "author_id": 213130, "author_profile": "https://wordpress.stackexchange.com/users/213130", "pm_score": 0, "selected": false, "text": "<p>Follow these steps</p>\n<ol>\n<li><p>login into wp admin dashboard</p>\n</li>\n<li><p>Go to add new plugin</p>\n</li>\n<li><p>Search &quot;File Manager&quot;</p>\n</li>\n<li><p>Install and activate it</p>\n</li>\n<li><p>Open file manager and find wp-config.php file</p>\n</li>\n<li><p>Right click on it and open it with code editor</p>\n</li>\n<li><p>Find</p>\n<pre><code> define('DB_CHARSET', 'utf8');\n</code></pre>\n</li>\n<li><p>And just add <code>-</code> between utf and 8</p>\n</li>\n<li><p>As follow</p>\n<pre><code>define('DB_CHARSET', 'utf-8');\n</code></pre>\n</li>\n<li><p>Save and close the wp-config.php file</p>\n</li>\n<li><p>Clear browser cache and refresh the page</p>\n</li>\n</ol>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312243", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149061/" ]
In my website this characters ​​ showing up on everywhere in blog content and title, after many hours of searching and googling cant find any useful answer i tried this meta but no luck ``` header("Content-Type: text/html; charset=ISO-8859-1"); <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> ``` Is there any way to rid-off this `​​` And many other characters: `‘` `â` `�` Also tried Plugin search and replace but the character is not searchable.
Found the answer after little bit search on google & <http://php.net/manual/en/function.htmlspecialchars-decode.php> , After a long time answered my own question thought maybe it will help someone. ``` htmlspecialchars_decode(utf8_decode(htmlentities(YOUR_STRING, ENT_COMPAT, 'utf-8', false))); ```
312,274
<p>I am using a custum gutenberg block plugin for wordpress(<a href="https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/" rel="noreferrer">https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/</a>)</p> <p>This block is using an image but always choosing the full size image. I would like that it chooses custom image sizes like the standard gutenberg image or gallery blocks. when browsing the web I can't find any plugin for Guteberg with these options. Can you give me any suggestion on how to get these functionalities? Is it even possible?</p> <p>Thank you for all your efforts to help me.</p> <p>Best Lukas</p>
[ { "answer_id": 314768, "author": "Ashiquzzaman Kiron", "author_id": 78505, "author_profile": "https://wordpress.stackexchange.com/users/78505", "pm_score": 0, "selected": false, "text": "<p>Couple of ways to manage the uploaded image size-</p>\n\n<ol>\n<li><p>Define a new attribute with default image size and add that into block edit function.</p></li>\n<li><p>Create inspector control with dropdown options and make the small image size the default value. From the dropdown option users' can select image size. Depeding on dropdown options CSS class will be added and these added CSS class with restrict image size.</p></li>\n</ol>\n\n<p>Both of these will require adding significant amount of code. The easiest way would be to </p>\n\n<ol start=\"3\">\n<li>Define and restrict image size in your existing image class, like \"<strong>nelio-testimonial-image</strong>\"</li>\n</ol>\n" }, { "answer_id": 319062, "author": "jezremy", "author_id": 153982, "author_profile": "https://wordpress.stackexchange.com/users/153982", "pm_score": 2, "selected": false, "text": "<p>Yes, this can be done.</p>\n\n<p>Are you using MediaUpload? Once an image is selected, MediaUpload returns that image object, which includes sizes: full, large, medium etc - this will include any custom sizes you've defined. Then, instead of assigned the url to the attribute, you save the url <em>of the size you want</em>.</p>\n\n<p>This is demonstrated here <a href=\"http://jschof.com/gutenberg-blocks/wordpress-gutenberg-blocks-example-creating-a-hero-image-block-with-inspector-controls-color-palette-and-media-upload-part-2/\" rel=\"nofollow noreferrer\">http://jschof.com/gutenberg-blocks/wordpress-gutenberg-blocks-example-creating-a-hero-image-block-with-inspector-controls-color-palette-and-media-upload-part-2/</a>\nUnder the heading \"MediaUpload and the object it returns\"</p>\n\n<p>Ie in the Edit section of your Gutenberg block:</p>\n\n<pre><code>function onImageSelect(imageObject) {\n /* want to see the sizes returned? console log it */\n console.log(imageObject);\n setAttributes({\n backgroundImage: imageObject.sizes.full.url\n })\n}\n\n...\n\n&lt;div&gt;\n &lt;strong&gt;Select a background image:&lt;/strong&gt;\n &lt;MediaUpload\n onSelect={onImageSelect}\n type=\"image\"\n value={backgroundImage}\n render={({ open }) =&gt; (\n &lt;button onClick={open}&gt;\n Upload Image!\n &lt;/button&gt;\n )}\n /&gt;\n&lt;/div&gt;\n</code></pre>\n\n<p>You may need a conditional to check if your image size is in the sizes, and if not use the full image.</p>\n" }, { "answer_id": 360943, "author": "user1861582", "author_id": 83283, "author_profile": "https://wordpress.stackexchange.com/users/83283", "pm_score": 0, "selected": false, "text": "<p>In order to have custom media image sizes returned in the media object, they need to be added with image_size_names_choose:</p>\n\n<pre><code>add_action( 'init', 'DE_add_image_sizes' );\nfunction DE_add_image_sizes() {\n /* Custom Images */\n add_image_size( \"bannerLarge\", 1593, 513, true );\n}\n\nadd_filter( 'image_size_names_choose', 'DE_custom_sizes' );\n\nfunction DE_custom_sizes( $sizes ) {\n return array_merge( $sizes, array(\n 'bannerLarge' =&gt; __('Banner Image'),\n ) );\n}\n</code></pre>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312274", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148458/" ]
I am using a custum gutenberg block plugin for wordpress(<https://neliosoftware.com/blog/how-to-create-your-first-block-for-gutenberg/>) This block is using an image but always choosing the full size image. I would like that it chooses custom image sizes like the standard gutenberg image or gallery blocks. when browsing the web I can't find any plugin for Guteberg with these options. Can you give me any suggestion on how to get these functionalities? Is it even possible? Thank you for all your efforts to help me. Best Lukas
Yes, this can be done. Are you using MediaUpload? Once an image is selected, MediaUpload returns that image object, which includes sizes: full, large, medium etc - this will include any custom sizes you've defined. Then, instead of assigned the url to the attribute, you save the url *of the size you want*. This is demonstrated here <http://jschof.com/gutenberg-blocks/wordpress-gutenberg-blocks-example-creating-a-hero-image-block-with-inspector-controls-color-palette-and-media-upload-part-2/> Under the heading "MediaUpload and the object it returns" Ie in the Edit section of your Gutenberg block: ``` function onImageSelect(imageObject) { /* want to see the sizes returned? console log it */ console.log(imageObject); setAttributes({ backgroundImage: imageObject.sizes.full.url }) } ... <div> <strong>Select a background image:</strong> <MediaUpload onSelect={onImageSelect} type="image" value={backgroundImage} render={({ open }) => ( <button onClick={open}> Upload Image! </button> )} /> </div> ``` You may need a conditional to check if your image size is in the sizes, and if not use the full image.
312,283
<p>I'm trying to get the alt text of our featured image and have it output on the frontend.</p> <p>Currently my code is</p> <pre><code>&lt;img class="vehicle-photo" src="&lt;?php echo the_post_thumbnail_url() ?&gt;" alt="&lt;?php the_post_thumbnail_caption();?&gt;" /&gt; </code></pre> <p>But on the frontend, it is outputting as </p> <pre><code>&lt;img class="vehicle-photo" src="photo url here" alt=""&gt; </code></pre>
[ { "answer_id": 312284, "author": "Bhupen", "author_id": 128529, "author_profile": "https://wordpress.stackexchange.com/users/128529", "pm_score": 1, "selected": false, "text": "<p>Please try code given below:</p>\n\n<pre><code>&lt;?php $image_id = get_post_thumbnail_id(get_the_ID());\n$alt_text = get_post_meta($image_id , '_wp_attachment_image_alt', true);?&gt;//Variable name updated\n\n&lt;img class=\"vehicle-photo\" src=\"&lt;?php echo the_post_thumbnail_url() ?&gt;\" alt=\"&lt;?php echo $alt_text ;?&gt;\" /&gt;\n</code></pre>\n" }, { "answer_id": 312285, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 4, "selected": false, "text": "<p>The alt text is stored as post meta on the attachment, and can be retrieved with <code>get_post_meta()</code> combined with <code>get_post_thumbnail_id()</code>:</p>\n<pre><code>&lt;?php echo get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true ); ?&gt;\n</code></pre>\n<p>But if you just use the <a href=\"https://developer.wordpress.org/reference/functions/the_post_thumbnail/\" rel=\"noreferrer\"><code>the_post_thumbnail()</code></a> function then you don't need to bother, the img tag will be output for you, with the alt text:</p>\n<pre><code>&lt;?php the_post_thumbnail( 'post-thumbnail', ['class' =&gt; 'vehicle-photo'] ); ?&gt;\n</code></pre>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312283", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149246/" ]
I'm trying to get the alt text of our featured image and have it output on the frontend. Currently my code is ``` <img class="vehicle-photo" src="<?php echo the_post_thumbnail_url() ?>" alt="<?php the_post_thumbnail_caption();?>" /> ``` But on the frontend, it is outputting as ``` <img class="vehicle-photo" src="photo url here" alt=""> ```
The alt text is stored as post meta on the attachment, and can be retrieved with `get_post_meta()` combined with `get_post_thumbnail_id()`: ``` <?php echo get_post_meta( get_post_thumbnail_id(), '_wp_attachment_image_alt', true ); ?> ``` But if you just use the [`the_post_thumbnail()`](https://developer.wordpress.org/reference/functions/the_post_thumbnail/) function then you don't need to bother, the img tag will be output for you, with the alt text: ``` <?php the_post_thumbnail( 'post-thumbnail', ['class' => 'vehicle-photo'] ); ?> ```
312,296
<p>I have a script that requires jQuery, and I don't know how to add it into a post correctly. I've read <a href="https://wordpress.stackexchange.com/q/45437/64282">How to include jQuery and JavaScript files correctly?</a> and <a href="https://wordpress.stackexchange.com/q/285383/64282">Using JavaScript and JQuery in Page</a> but they are too advanced for me to understand. The Scripts 'n Styles plugin has the <em>Include Scripts</em> section, which I suspect is another way to use <a href="https://developer.wordpress.org/reference/functions/wp_enqueue_script/" rel="nofollow noreferrer"><code>wp_enqueue_script</code></a>, but I don't know which one to choose:</p> <p><img src="https://i.imgur.com/dXqI7ji.png" alt=""></p> <p>So far, I only add the <code>&lt;head&gt;</code> and <code>&lt;body&gt;</code> elements without the jQuery, and while it ultimately worked, it didn't work at the beginning and I had to tried many times. So is there a proper and easy way to do this?</p> <p><br></p> <p><sup>FYI: <a href="https://wordpress.stackexchange.com/q/312124/64282">How to add JavaScript code on WordPress correctly?</a></sup></p> <hr> <p>The code is below.</p> <pre><code>&lt;head&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"&gt;&lt;/script&gt; &lt;script&gt; var words = []; words.push('vocabulary'); words.push('lexicon'); words.push('lexicons'); &lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;p id="demo"&gt;A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array. &lt;/p&gt; &lt;script&gt; function toggle(element) { if (element.innerHTML.split('_').join('').trim().length === 0) { element.innerHTML = element.getAttribute("word"); } else { element.innerHTML = "_______"; } } $.each(words, function(index, value) { var replacestr = new RegExp('\\b'+value+'\\b', "g"); $("p#demo:contains('" + value + "')").html(function(_, html) { return html.replace(replacestr, ' &lt;span class = "smallcaps" word="' + value + '" onclick="toggle(this)"&gt;_______&lt;/span&gt;') }); }); &lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[ { "answer_id": 312313, "author": "maverick", "author_id": 132953, "author_profile": "https://wordpress.stackexchange.com/users/132953", "pm_score": 2, "selected": false, "text": "<p>assuming you have enqueued everything ( script files and style files ) properly in your wordpress theme's folder</p>\n\n<p>following would be ( just assume ) your theme files</p>\n\n<pre><code>wp-content/themes/your-theme-dir/\n assets/\n css/ ( this is directory/folder )\n styles.css ( this is file )\n js/\n scripts.js\n index.php\n functions.php\n</code></pre>\n\n<p>lets say your code shown above is in index.php </p>\n\n<p>now assuming you've included your scripts.js file from functions.php file</p>\n\n<p>the content in your scripts.js file should look like:</p>\n\n<pre><code>(function($){\n var words = [];\n\n words.push('vocabulary');\n words.push('lexicon');\n words.push('lexicons');\n function toggle(element) {\n if (element.innerHTML.split('_').join('').trim().length === 0) {\n element.innerHTML = element.getAttribute(\"word\");\n } else {\n element.innerHTML = \"_______\";\n }\n }\n\n $.each(words, function(index, value) {\n var replacestr = new RegExp('\\\\b'+value+'\\\\b', \"g\");\n $(\"p#demo:contains('\" + value + \"')\").html(function(_, html) {\n return html.replace(replacestr, ' &lt;span class = \"smallcaps\" word=\"' + value + '\" onclick=\"toggle(this)\"&gt;_______&lt;/span&gt;')\n });\n });\n})(jQuery);\n</code></pre>\n\n<p>Remember when enqueunig scripts your file should be dependent upon jquery like</p>\n\n<pre><code>wp_enqueue_script( 'file-id', 'path-to-file', array( 'jquery' ), 'version-number', 'true' );\n</code></pre>\n\n<p>for getting path to file, you have two options </p>\n\n<ol>\n<li><p>if your theme is parent theme use: <code>get_template_directory_uri()</code>\ne.g. get_template_directory_uri().'/assets/js/scripts.js'</p></li>\n<li><p>if your theme is child theme use: <code>get_stylesheet_directory_uri()</code>\ne.g. get_stylesheet_directory_uri().'/assets/js/scripts.js'</p></li>\n</ol>\n" }, { "answer_id": 312433, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 2, "selected": false, "text": "<p>I tested this code in its strict html format, and the jQuery works. </p>\n\n<p>Then I coded answers to this question in WordPress as 1) a plugin and 2) loaded from functions.php. In each case, the jQuery fails. </p>\n\n<p>The problem appears, to my untrained eye, to be related to the Javascript. Specifically because the method \"toggle(element)\" is a global object at the time that \"$.each\" is executed. Somewhere along the line, I believe that the two need to be inter-linked but despite spending the better part of a day on this, it is beyond my ability. Of course, there's the risk of PEBCAK. </p>\n\n<p><strong>The content as displayed</strong> (proving that $.each has run successfully)<br>\n<a href=\"https://i.stack.imgur.com/00WWP.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/00WWP.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>The content HTML</strong>\n<a href=\"https://i.stack.imgur.com/MWxHk.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/MWxHk.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Chrome Console before clicking on the text</strong>:<br>\n<a href=\"https://i.stack.imgur.com/dE9wr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/dE9wr.jpg\" alt=\"enter image description here\"></a></p>\n\n<p><strong>Chrome Console after clicking on a blank work in the text</strong> </p>\n\n<h2><a href=\"https://i.stack.imgur.com/aVJEr.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aVJEr.jpg\" alt=\"enter image description here\"></a></h2>\n\n<hr>\n\n<p>The Plugin consists of:<br>\n1 - <em>The Plugin file</em> (vocab.php)<br>\n2 - <em>The Plugin Javascript file</em> (vocab.js)<br>\n3 - <em>The Plugin Template content file</em> (vocab-template.php)<br>\n4 - <em>The Page Template</em> (page-vocab.php) (Template name = Vocab Test)<br>\nPlus <em>One Standard WordPress Page</em>, template = \"Vocab Test\"</p>\n\n<p><strong>The Plugin file</strong> (vocab.php) </p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: a_Stackoverflow_Vocab test\n*/\n// 01 - Define the filesystem paths for the plugin\n\nif ( ! defined( 'WP_CONTENT_URL' ) )\n define( 'WP_CONTENT_URL', get_option( 'siteurl' ) . '/wp-content' );\nif ( ! defined( 'WP_CONTENT_DIR' ) )\n define( 'WP_CONTENT_DIR', ABSPATH . 'wp-content' );\nif ( ! defined( 'WP_PLUGIN_URL' ) )\n define( 'WP_PLUGIN_URL', WP_CONTENT_URL. '/plugins' );\nif ( ! defined( 'WP_PLUGIN_DIR' ) )\n define( 'WP_PLUGIN_DIR', WP_CONTENT_DIR . '/plugins' );\ndefine( 'VOCAB_DIR', plugin_dir_path( __FILE__ ) );\ndefine( 'VOCAB_URL', plugin_dir_url( __FILE__ ) );\n\n// 02 - Enqueue scripts and styles for the plugin. \n\nfunction vocab_scripts() {\n if (!is_admin()) {\n if (is_page(array('vocab'))) { \n wp_enqueue_script( 'jquery' );\n wp_register_script('vocabjs', VOCAB_URL . 'vocab.js', array( 'jquery'),NULL); \n wp_enqueue_script('vocabjs'); \n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'vocab_scripts' );\n\n// Calls to key files: template layout\n\nrequire(\"vocab-template.php\"); \n\n?&gt;\n</code></pre>\n\n<p><strong>The Javascript file</strong> (vocab.js) </p>\n\n<pre><code>jQuery(document).ready(function ($) {\n var words = [];\n words.push('vocabulary');\n words.push('lexicon');\n words.push('lexicons');\n\nfunction toggle(element) {\n if (element.innerHTML.split('_').join('').trim().length === 0) {\n element.innerHTML = element.getAttribute(\"word\");\n } else {\n element.innerHTML = \"_______\";\n }\n}\n\n$.each(words, function(index, value) {\n var replacestr = new RegExp('\\\\b'+value+'\\\\b', \"g\");\n $(\"p#demo:contains('\" + value + \"')\").html(function(_, html) {\n return html.replace(replacestr, ' &lt;span class = \"smallcaps\" word=\"' + value + '\" onclick=\"toggle(this)\"&gt;_______&lt;/span&gt;')\n });\n});\n});\n</code></pre>\n\n<p><strong>The Plugin Template content file</strong> (vocab-template.php) </p>\n\n<pre><code>&lt;?php\n/*\n* function to deliver template\n*/\nfunction insert_vocab_template(){\n?&gt;\n&lt;div id=\"page\"&gt;\n&lt;!-- start div page --&gt;\n &lt;h1&gt;Vocabulary Test&lt;/h1&gt;\n &lt;div id=\"cover_content\"&gt;\n &lt;h2&gt;Test content&lt;/h2&gt;\n &lt;p id=\"demo\"&gt;A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array.&lt;/p&gt;\n &lt;/div&gt;\n &lt;!-- end cover_content --&gt;\n &lt;/div&gt; \n &lt;!-- end #page --&gt;\n&lt;?php\n}\n?&gt;\n</code></pre>\n\n<p><strong>The Page Template</strong> (page-vocab.php)</p>\n\n<pre><code>&lt;?php /* Template Name: Vocab Test */ ?&gt;\n&lt;?php\nget_header(); ?&gt;\n &lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n &lt;!-- page --&gt;\n &lt;?php\n $myoutput = insert_vocab_template();\n echo $myoutput;\n ?&gt;\n &lt;/main&gt;&lt;!-- .site-main --&gt;\n &lt;/div&gt;&lt;!-- .primary --&gt;\n&lt;?php get_sidebar(); ?&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<hr>\n\n<p><strong>Alternative via Functions.php</strong> (in a child theme)</p>\n\n<p>1 - <em>Enqueue function in Functions.php</em><br>\n2 - <em>The Javascript file</em> (themes/childtheme/js) - vocab2.js (identical to plugin version)<br>\n3 - <em>The Page Template</em> (page-vocab2.php) (Template name = Vocab2 Test)<br>\nPlus One Standard WordPress Page, template = \"Vocab Test2\"<br>\nNote: in this version, the paragraph of text (with id=\"demo\") was included in the WordPress page as content.</p>\n\n<p><strong>Extract from Functions.php</strong></p>\n\n<pre><code>// enqueue jquery and script\nfunction vocab2_scripts() {\n if (!is_admin()) {\n if (is_page(array('vocab2'))) { \n wp_enqueue_script('jquery');\n wp_enqueue_script('vocab2js', get_stylesheet_directory_uri(). '/js/vocab2.js', array( 'jquery' )); \n }\n }\n}\nadd_action( 'wp_enqueue_scripts', 'vocab2_scripts' );\n</code></pre>\n\n<p><strong>The Javascript file</strong> (themes/childtheme/js) - vocab2.js</p>\n\n<pre><code>jQuery(document).ready(function ($) {\n var words = [];\n\n words.push('vocabulary');\n words.push('lexicon');\n words.push('lexicons');\n\n function toggle(element) {\n if (element.innerHTML.split('_').join('').trim().length === 0) {\n element.innerHTML = element.getAttribute(\"word\");\n } else {\n element.innerHTML = \"_______\";\n }\n }\n\n $.each(words, function(index, value) {\n var replacestr = new RegExp('\\\\b'+value+'\\\\b', \"g\");\n $(\"p#demo:contains('\" + value + \"')\").html(function(_, html) {\n return html.replace(replacestr, ' &lt;span class = \"smallcaps\" word=\"' + value + '\" onclick=\"toggle(this)\"&gt;_______&lt;/span&gt;')\n });\n });\n});\n</code></pre>\n\n<p><strong>The Page Template</strong> (page-vocab2.php) (Template name = Vocab2 Test)</p>\n\n<pre><code>&lt;?php /* Template Name: Vocab Test2 */ ?&gt;\n&lt;?php\nget_header(); ?&gt;\n&lt;div id=\"primary\" class=\"content-area\"&gt;\n &lt;main id=\"main\" class=\"site-main\" role=\"main\"&gt;\n &lt;!-- page --&gt;\n &lt;?php\n while ( have_posts() ) : the_post();\n ?&gt;\n &lt;article id=\"post-&lt;?php the_ID(); ?&gt;\" &lt;?php post_class(); ?&gt;&gt;\n &lt;header class=\"entry-header\"&gt;\n &lt;?php the_title( '&lt;h1 class=\"entry-title\"&gt;', '&lt;/h1&gt;' ); ?&gt;\n &lt;/header&gt;&lt;!-- .entry-header --&gt;\n\n &lt;div class=\"entry-content\"&gt;\n &lt;?php the_content();?&gt;\n &lt;/div&gt;&lt;!-- .entry-content --&gt;\n &lt;/article&gt;&lt;!-- #post-## --&gt;\n &lt;?php\n // End of the loop.\n endwhile;\n ?&gt;\n &lt;/main&gt;&lt;!-- .site-main --&gt;\n&lt;/div&gt;&lt;!-- .content-area --&gt;\n&lt;?php get_sidebar(); ?&gt;\n&lt;?php get_footer(); ?&gt;\n</code></pre>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>I can now get the code to work by calling \"toggle\" from with the \"$.each\" statement but the Console is still giving errors - now changed to:<br>\n<em>\"Uncaught TypeError: Cannot read property 'innerHTML' of undefined\"</em>\n<a href=\"https://i.stack.imgur.com/ZWUgY.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ZWUgY.jpg\" alt=\"enter image description here\"></a></p>\n\n<p>The Javascript file now looks like this: </p>\n\n<pre><code>function toggle(element) {\n if (element.innerHTML.split('_').join('').trim().length === 0) {\n element.innerHTML = element.getAttribute(\"word\");\n } else {\n element.innerHTML = \"_______\";\n }\n}\n\njQuery(document).ready(function ($) {\n var words = [];\n\n words.push('vocabulary');\n words.push('lexicon');\n words.push('lexicons');\n $.each(words, function(index, value) {\n var replacestr = new RegExp('\\\\b'+value+'\\\\b', \"g\");\n $(\"p#demo:contains('\" + value + \"')\").html(function(_, html) {\n return html.replace(replacestr, ' &lt;span class = \"smallcaps\" word=\"' + value + '\" onclick=\"toggle(this)\"&gt;_______&lt;/span&gt;')\n });\n });\n toggle();\n});\n</code></pre>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312296", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64282/" ]
I have a script that requires jQuery, and I don't know how to add it into a post correctly. I've read [How to include jQuery and JavaScript files correctly?](https://wordpress.stackexchange.com/q/45437/64282) and [Using JavaScript and JQuery in Page](https://wordpress.stackexchange.com/q/285383/64282) but they are too advanced for me to understand. The Scripts 'n Styles plugin has the *Include Scripts* section, which I suspect is another way to use [`wp_enqueue_script`](https://developer.wordpress.org/reference/functions/wp_enqueue_script/), but I don't know which one to choose: ![](https://i.imgur.com/dXqI7ji.png) So far, I only add the `<head>` and `<body>` elements without the jQuery, and while it ultimately worked, it didn't work at the beginning and I had to tried many times. So is there a proper and easy way to do this? FYI: [How to add JavaScript code on WordPress correctly?](https://wordpress.stackexchange.com/q/312124/64282) --- The code is below. ``` <head> <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> var words = []; words.push('vocabulary'); words.push('lexicon'); words.push('lexicons'); </script> </head> <body> <p id="demo">A vocabulary is a list of words that an individual knows or uses regularly. vocabulary is different from lexicon because vocabulary is about what an individual or group of people know, whereas lexicon is about the language itself. In this paragraph, lexicons is a new word that's added, so don't forget to push 'lexicons' in your array. </p> <script> function toggle(element) { if (element.innerHTML.split('_').join('').trim().length === 0) { element.innerHTML = element.getAttribute("word"); } else { element.innerHTML = "_______"; } } $.each(words, function(index, value) { var replacestr = new RegExp('\\b'+value+'\\b', "g"); $("p#demo:contains('" + value + "')").html(function(_, html) { return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>') }); }); </script> </body> </html> ```
assuming you have enqueued everything ( script files and style files ) properly in your wordpress theme's folder following would be ( just assume ) your theme files ``` wp-content/themes/your-theme-dir/ assets/ css/ ( this is directory/folder ) styles.css ( this is file ) js/ scripts.js index.php functions.php ``` lets say your code shown above is in index.php now assuming you've included your scripts.js file from functions.php file the content in your scripts.js file should look like: ``` (function($){ var words = []; words.push('vocabulary'); words.push('lexicon'); words.push('lexicons'); function toggle(element) { if (element.innerHTML.split('_').join('').trim().length === 0) { element.innerHTML = element.getAttribute("word"); } else { element.innerHTML = "_______"; } } $.each(words, function(index, value) { var replacestr = new RegExp('\\b'+value+'\\b', "g"); $("p#demo:contains('" + value + "')").html(function(_, html) { return html.replace(replacestr, ' <span class = "smallcaps" word="' + value + '" onclick="toggle(this)">_______</span>') }); }); })(jQuery); ``` Remember when enqueunig scripts your file should be dependent upon jquery like ``` wp_enqueue_script( 'file-id', 'path-to-file', array( 'jquery' ), 'version-number', 'true' ); ``` for getting path to file, you have two options 1. if your theme is parent theme use: `get_template_directory_uri()` e.g. get\_template\_directory\_uri().'/assets/js/scripts.js' 2. if your theme is child theme use: `get_stylesheet_directory_uri()` e.g. get\_stylesheet\_directory\_uri().'/assets/js/scripts.js'
312,324
<p>I know how to query posts with my custom query var, but I am trying to rewrite the following URL from this...</p> <p><a href="https://www.fashionavocado.com/category/healthy-living/relationships/?tag=flock" rel="nofollow noreferrer">https://www.fashionavocado.com/category/healthy-living/relationships/?tag=flock</a></p> <p>to this...</p> <p><a href="https://www.fashionavocado.com/category/healthy-living/relationships/tag/flock" rel="nofollow noreferrer">https://www.fashionavocado.com/category/healthy-living/relationships/tag/flock</a></p> <p>I can't seem to combine the pre-existing category/subcategory with the tag.</p> <p>Here's some code I started with</p> <pre><code>function myplugin_rewrite_tag_rule() { add_rewrite_tag( '%tag%', '([^&amp;]+)' ); add_rewrite_rule( '^tag/([^/]*)/?', 'index.php?tag=$matches[1]','top' ); } add_action('init', 'myplugin_rewrite_tag_rule', 10, 0); </code></pre> <p>I know this won't work because I need the category parameter as a query var.</p>
[ { "answer_id": 312354, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 4, "selected": true, "text": "<p>These should work for you:</p>\n\n<pre><code>function myplugin_rewrite_tag_rule() {\n add_rewrite_rule(\n 'category/(.+?)/tag/([^/]+)/?$',\n 'index.php?category_name=$matches[1]&amp;tag=$matches[2]',\n 'top'\n );\n add_rewrite_rule(\n 'category/(.+?)/tag/([^/]+)/page/?([0-9]{1,})/?$',\n 'index.php?category_name=$matches[1]&amp;tag=$matches[2]&amp;paged=$matches[3]',\n 'top'\n );\n}\nadd_action('init', 'myplugin_rewrite_tag_rule', 10, 0);\n</code></pre>\n\n<p>The second rule is to support pagination so you can have:</p>\n\n<pre><code>https://example.com/category/healthy-living/relationships/tag/flock\n</code></pre>\n\n<p>as well as:</p>\n\n<pre><code>https://example.com/category/healthy-living/relationships/tag/flock/page/2/\n</code></pre>\n\n<p>Note that you don't need to add a rewrite tag, as it's already added by core.</p>\n" }, { "answer_id": 357245, "author": "Kate", "author_id": 181666, "author_profile": "https://wordpress.stackexchange.com/users/181666", "pm_score": 0, "selected": false, "text": "<p>Try to apply your code into woocommerce category with tag, but it does not work. Something wrong with my code?</p>\n\n<pre><code>function myplugin_rewrite_tag_rule() {\n add_rewrite_rule(\n 'store/(.+?)/product_tag/([^/]+)/?$',\n 'index.php?product_cat=$matches[1]&amp;product_tag=$matches[2]',\n 'top'\n );\n add_rewrite_rule(\n 'store/(.+?)/product_tag/([^/]+)/page/?([0-9]{1,})/?$',\n 'index.php?product_cat=$matches[1]&amp;product_tag=$matches[2]&amp;paged=$matches[3]',\n 'top'\n );\n}\nadd_action('init', 'myplugin_rewrite_tag_rule', 10, 0);\n</code></pre>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312324", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/64309/" ]
I know how to query posts with my custom query var, but I am trying to rewrite the following URL from this... <https://www.fashionavocado.com/category/healthy-living/relationships/?tag=flock> to this... <https://www.fashionavocado.com/category/healthy-living/relationships/tag/flock> I can't seem to combine the pre-existing category/subcategory with the tag. Here's some code I started with ``` function myplugin_rewrite_tag_rule() { add_rewrite_tag( '%tag%', '([^&]+)' ); add_rewrite_rule( '^tag/([^/]*)/?', 'index.php?tag=$matches[1]','top' ); } add_action('init', 'myplugin_rewrite_tag_rule', 10, 0); ``` I know this won't work because I need the category parameter as a query var.
These should work for you: ``` function myplugin_rewrite_tag_rule() { add_rewrite_rule( 'category/(.+?)/tag/([^/]+)/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]', 'top' ); add_rewrite_rule( 'category/(.+?)/tag/([^/]+)/page/?([0-9]{1,})/?$', 'index.php?category_name=$matches[1]&tag=$matches[2]&paged=$matches[3]', 'top' ); } add_action('init', 'myplugin_rewrite_tag_rule', 10, 0); ``` The second rule is to support pagination so you can have: ``` https://example.com/category/healthy-living/relationships/tag/flock ``` as well as: ``` https://example.com/category/healthy-living/relationships/tag/flock/page/2/ ``` Note that you don't need to add a rewrite tag, as it's already added by core.
312,327
<p>I am copying this tutorial to make my own custom meta box <a href="https://www.sitepoint.com/adding-meta-boxes-post-types-wordpress/" rel="nofollow noreferrer">https://www.sitepoint.com/adding-meta-boxes-post-types-wordpress/</a></p> <p>It works perfectly, however I need to be able to enter script tags into this meta box and save the script and output it on the page.</p> <p>When I enter anything like script tags or div tags, it will clear the meta box field and not save or output what I entered, after updating the page.</p> <p>I noticed the code has this:</p> <pre><code>// Sanitize user input. $my_data = sanitize_text_field( $_POST['global_notice'] ); </code></pre> <p>But even after I remove that line, it will still not save or output my script in the meta box.</p> <p>Is there something else I need to do to make this work with scripts and tags? Is there a reason why this isn't working?</p> <p>Thank you.</p> <p>*EDIT</p> <p>Here is the full code I'm using in a plugin to create the metabox and a shortcode to output the metabox content.</p> <pre><code>&lt;?php /* Plugin Name: VBO Tickets Plugin Embed Plugin URI: https://www.vbotickets.com Description: Add your plugin code to any page or post on your WordPress site. Version: 0.1 Author: VBO Tickets */ function global_notice_meta_box() { $screens = get_post_types(); foreach ( $screens as $screen ) { add_meta_box( 'global-notice', __( 'VBO Plugin Embed', 'vbotickets' ), 'global_notice_meta_box_callback', $screen ); } } add_action( 'add_meta_boxes', 'global_notice_meta_box' ); function global_notice_meta_box_callback( $post ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'global_notice_nonce', 'global_notice_nonce' ); $value = get_post_meta( $post-&gt;ID, '_global_notice', true ); echo '&lt;p&gt;&lt;strong&gt;Paste your VBO plugin embed code in the text area below:&lt;/strong&gt;&lt;/p&gt;'; echo '&lt;textarea style="width:100%;min-height:150px;" id="global_notice" name="global_notice"&gt;' . esc_attr( $value ) . '&lt;/textarea&gt;'; echo '&lt;p&gt;&lt;strong&gt;Next, copy/paste&lt;/strong&gt; &lt;code&gt;[vbo-plugin-embed]&lt;/code&gt; &lt;strong&gt;into the content area where you want the plugin to load on this page.&lt;/strong&gt;&lt;/p&gt;'; } /** * When the post is saved, saves our custom data. * * @param int $post_id */ function save_global_notice_meta_box_data( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['global_notice_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['global_notice_nonce'], 'global_notice_nonce' ) ) { return; } // If this is an autosave, our form has not been submitted, so we don't want to do anything. if ( defined( 'DOING_AUTOSAVE' ) &amp;&amp; DOING_AUTOSAVE ) { return; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) &amp;&amp; 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } /* OK, it's safe for us to save the data now. */ // Make sure that it is set. if ( ! isset( $_POST['global_notice'] ) ) { return; } // Sanitize user input. //$my_data = sanitize_text_field( $_POST['global_notice'] ); $my_data = $_POST['global_notice']; // Update the meta field in the database. update_post_meta( $post_id, '_global_notice', $my_data ); } add_action( 'save_post', 'save_global_notice_meta_box_data' ); // Add shortcode [vbo-plugin-embed] function vbo_embed_sc( $atts ){ global $post; // retrieve the global notice for the current post $global_notice = esc_attr( get_post_meta( $post-&gt;ID, '_global_notice', true ) ); return $global_notice; } add_shortcode( 'vbo-plugin-embed', 'vbo_embed_sc' ); </code></pre> <p>Here is the URL I am testing this on <a href="https://demo.vbotickets.com/photos/" rel="nofollow noreferrer">https://demo.vbotickets.com/photos/</a></p> <p>The problem now is that I have gotten scrtips/HTML to save in the metabox, but the output is plain text rather than actually running the code/script. Is there a way to run it as well?</p> <p>Thanks!</p>
[ { "answer_id": 312345, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>You cannot just remove the line to skip sanitizing of your data.\nThe line is:\n<code>$my_data = sanitize_text_field( $_POST['global_notice'] );</code>\nIf you remove it, you have nothing sent to <code>$my_data</code></p>\n\n<p>For testing, try replacing it with just:\n<code>$my_data = $_POST['global_notice'];</code></p>\n\n<p>I suggest for a live environment, you DO sanitize it somehow though.</p>\n" }, { "answer_id": 313199, "author": "Jerrick", "author_id": 149856, "author_profile": "https://wordpress.stackexchange.com/users/149856", "pm_score": 1, "selected": false, "text": "<p>Your using \"esc_attr()\" to escape the data, That is why it's being converted to plan text. If you used echo it will likely work. However, your saving the script tags into the database. </p>\n\n<p>I'm still on the learning journey just like you but here is what I would do. </p>\n\n<p>TO SAVE THE DATA</p>\n\n<pre><code>//$my_data = sanitize_text_field( $_POST['global_notice'] );\n//$my_data = $_POST['global_notice'];\n$my_data = htmlspecialchars($_POST['global_notice']);\n</code></pre>\n\n<p>Then to output the data</p>\n\n<pre><code>if(!empty($global_notice)) {\n $myvar = htmlspecialchars_decode($global_notice);\n return $myvar;\n}\n</code></pre>\n\n<p>If \"return\" does not work you could use \"echo\". </p>\n\n<p>Hope this helps. </p>\n\n<p>Also, when creating shortcode you may want to learn about ob_start();\nand return_ob_clean(); if your shortcode is being displayed on the front end in the incorrect position. You can always use the same code is a template file fyi. </p>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312327", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/24617/" ]
I am copying this tutorial to make my own custom meta box <https://www.sitepoint.com/adding-meta-boxes-post-types-wordpress/> It works perfectly, however I need to be able to enter script tags into this meta box and save the script and output it on the page. When I enter anything like script tags or div tags, it will clear the meta box field and not save or output what I entered, after updating the page. I noticed the code has this: ``` // Sanitize user input. $my_data = sanitize_text_field( $_POST['global_notice'] ); ``` But even after I remove that line, it will still not save or output my script in the meta box. Is there something else I need to do to make this work with scripts and tags? Is there a reason why this isn't working? Thank you. \*EDIT Here is the full code I'm using in a plugin to create the metabox and a shortcode to output the metabox content. ``` <?php /* Plugin Name: VBO Tickets Plugin Embed Plugin URI: https://www.vbotickets.com Description: Add your plugin code to any page or post on your WordPress site. Version: 0.1 Author: VBO Tickets */ function global_notice_meta_box() { $screens = get_post_types(); foreach ( $screens as $screen ) { add_meta_box( 'global-notice', __( 'VBO Plugin Embed', 'vbotickets' ), 'global_notice_meta_box_callback', $screen ); } } add_action( 'add_meta_boxes', 'global_notice_meta_box' ); function global_notice_meta_box_callback( $post ) { // Add a nonce field so we can check for it later. wp_nonce_field( 'global_notice_nonce', 'global_notice_nonce' ); $value = get_post_meta( $post->ID, '_global_notice', true ); echo '<p><strong>Paste your VBO plugin embed code in the text area below:</strong></p>'; echo '<textarea style="width:100%;min-height:150px;" id="global_notice" name="global_notice">' . esc_attr( $value ) . '</textarea>'; echo '<p><strong>Next, copy/paste</strong> <code>[vbo-plugin-embed]</code> <strong>into the content area where you want the plugin to load on this page.</strong></p>'; } /** * When the post is saved, saves our custom data. * * @param int $post_id */ function save_global_notice_meta_box_data( $post_id ) { // Check if our nonce is set. if ( ! isset( $_POST['global_notice_nonce'] ) ) { return; } // Verify that the nonce is valid. if ( ! wp_verify_nonce( $_POST['global_notice_nonce'], 'global_notice_nonce' ) ) { return; } // 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; } // Check the user's permissions. if ( isset( $_POST['post_type'] ) && 'page' == $_POST['post_type'] ) { if ( ! current_user_can( 'edit_page', $post_id ) ) { return; } } else { if ( ! current_user_can( 'edit_post', $post_id ) ) { return; } } /* OK, it's safe for us to save the data now. */ // Make sure that it is set. if ( ! isset( $_POST['global_notice'] ) ) { return; } // Sanitize user input. //$my_data = sanitize_text_field( $_POST['global_notice'] ); $my_data = $_POST['global_notice']; // Update the meta field in the database. update_post_meta( $post_id, '_global_notice', $my_data ); } add_action( 'save_post', 'save_global_notice_meta_box_data' ); // Add shortcode [vbo-plugin-embed] function vbo_embed_sc( $atts ){ global $post; // retrieve the global notice for the current post $global_notice = esc_attr( get_post_meta( $post->ID, '_global_notice', true ) ); return $global_notice; } add_shortcode( 'vbo-plugin-embed', 'vbo_embed_sc' ); ``` Here is the URL I am testing this on <https://demo.vbotickets.com/photos/> The problem now is that I have gotten scrtips/HTML to save in the metabox, but the output is plain text rather than actually running the code/script. Is there a way to run it as well? Thanks!
Your using "esc\_attr()" to escape the data, That is why it's being converted to plan text. If you used echo it will likely work. However, your saving the script tags into the database. I'm still on the learning journey just like you but here is what I would do. TO SAVE THE DATA ``` //$my_data = sanitize_text_field( $_POST['global_notice'] ); //$my_data = $_POST['global_notice']; $my_data = htmlspecialchars($_POST['global_notice']); ``` Then to output the data ``` if(!empty($global_notice)) { $myvar = htmlspecialchars_decode($global_notice); return $myvar; } ``` If "return" does not work you could use "echo". Hope this helps. Also, when creating shortcode you may want to learn about ob\_start(); and return\_ob\_clean(); if your shortcode is being displayed on the front end in the incorrect position. You can always use the same code is a template file fyi.
312,328
<p>I'm running localhost server on xampp. I 'm connecting properly with my host computer from other devices with IP address but once i go into wordpress directory i got redirected. Every device i was testing changed entered IP/wordpress to localhost/wordpress. </p> <p>Strange fact is that i have 3 exact copies of wordpress. One of wchich is installed on Windows8, second Windows10 and 3rd one on Ubuntu. There's no problem to connect with windows installations even from Ubuntu but not the reverse.</p> <p>I've already tried to change <strong>wp-config.php</strong> file by modifying :</p> <pre><code>define('WP_SITEURL', 'http://LOCAL_HOST_IP/wordpress'); define('WP_HOME', 'http://LOCAL_HOST_IP/wordpress'); </code></pre> <p>And it works but only partial. iOS device is connecting properly with host wordpress but windows computer and android based tablet isn't. What can cause such problem?</p>
[ { "answer_id": 312355, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 2, "selected": false, "text": "<p>Trying to change edit the <code>wp-config.php</code> file was a good idea, let's try some extra things to see if they solve the problem. Let's add these lines to the bottom of your <code>functions.php</code>:</p>\n\n<pre><code>update_option( 'siteurl', 'http://LOCAL_HOST_IP/wordpress' );\nupdate_option( 'home', 'http://LOCAL_HOST_IP/wordpress' );\n</code></pre>\n\n<hr>\n\n<h2>Using Relocate method</h2>\n\n<p>Edit your <code>wp-config.php</code> file inserting: </p>\n\n<pre><code>define('RELOCATE',true); \n</code></pre>\n\n<p>After that, from your browser manually access to <code>wp-login.php</code>. For example, type <code>http://LOCAL_HOST_IP/wordpress/wp-login.php</code> into your browser's address bar, and then login as usual.</p>\n\n<hr>\n\n<h2>Changing the URL directly in the database</h2>\n\n<ol>\n<li>Login to phpMyAdmin.</li>\n<li>Find your DB and then the table <code>wp_options</code></li>\n<li>Look for <code>siteurl</code> and <code>home</code> within that table</li>\n<li>Use <code>http://LOCAL_HOST_IP/wordpress</code> for both and save.</li>\n</ol>\n\n<p>Check the full <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">Codex Changing Site URL</a> guide.</p>\n" }, { "answer_id": 312393, "author": "Bartosz Was", "author_id": 140315, "author_profile": "https://wordpress.stackexchange.com/users/140315", "pm_score": 1, "selected": false, "text": "<p><strong>Problem solved</strong> </p>\n\n<p>Wordpress and its configuration wasn't the issue here. The real reason why site was working on some devices and on others don't was cached files in browsers.\nSolution was to clear cached files or trying to develop in private mode browsing which isn't caching files.</p>\n\n<p>Also i want to point out that when you want to access host from other computer you have to disable firewall. Strange fact about all this is when you can access to host and see it's dashboard while firewall is enabled going into wordpress directory will cause error.</p>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312328", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/140315/" ]
I'm running localhost server on xampp. I 'm connecting properly with my host computer from other devices with IP address but once i go into wordpress directory i got redirected. Every device i was testing changed entered IP/wordpress to localhost/wordpress. Strange fact is that i have 3 exact copies of wordpress. One of wchich is installed on Windows8, second Windows10 and 3rd one on Ubuntu. There's no problem to connect with windows installations even from Ubuntu but not the reverse. I've already tried to change **wp-config.php** file by modifying : ``` define('WP_SITEURL', 'http://LOCAL_HOST_IP/wordpress'); define('WP_HOME', 'http://LOCAL_HOST_IP/wordpress'); ``` And it works but only partial. iOS device is connecting properly with host wordpress but windows computer and android based tablet isn't. What can cause such problem?
Trying to change edit the `wp-config.php` file was a good idea, let's try some extra things to see if they solve the problem. Let's add these lines to the bottom of your `functions.php`: ``` update_option( 'siteurl', 'http://LOCAL_HOST_IP/wordpress' ); update_option( 'home', 'http://LOCAL_HOST_IP/wordpress' ); ``` --- Using Relocate method --------------------- Edit your `wp-config.php` file inserting: ``` define('RELOCATE',true); ``` After that, from your browser manually access to `wp-login.php`. For example, type `http://LOCAL_HOST_IP/wordpress/wp-login.php` into your browser's address bar, and then login as usual. --- Changing the URL directly in the database ----------------------------------------- 1. Login to phpMyAdmin. 2. Find your DB and then the table `wp_options` 3. Look for `siteurl` and `home` within that table 4. Use `http://LOCAL_HOST_IP/wordpress` for both and save. Check the full [Codex Changing Site URL](https://codex.wordpress.org/Changing_The_Site_URL) guide.
312,329
<p>I have local Instance of WordPress and I want to edit the code of Pages which I created using WordPress Dashboard but I can't find those pages in my local environment folders so how can I find those pages .php files?</p>
[ { "answer_id": 312355, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 2, "selected": false, "text": "<p>Trying to change edit the <code>wp-config.php</code> file was a good idea, let's try some extra things to see if they solve the problem. Let's add these lines to the bottom of your <code>functions.php</code>:</p>\n\n<pre><code>update_option( 'siteurl', 'http://LOCAL_HOST_IP/wordpress' );\nupdate_option( 'home', 'http://LOCAL_HOST_IP/wordpress' );\n</code></pre>\n\n<hr>\n\n<h2>Using Relocate method</h2>\n\n<p>Edit your <code>wp-config.php</code> file inserting: </p>\n\n<pre><code>define('RELOCATE',true); \n</code></pre>\n\n<p>After that, from your browser manually access to <code>wp-login.php</code>. For example, type <code>http://LOCAL_HOST_IP/wordpress/wp-login.php</code> into your browser's address bar, and then login as usual.</p>\n\n<hr>\n\n<h2>Changing the URL directly in the database</h2>\n\n<ol>\n<li>Login to phpMyAdmin.</li>\n<li>Find your DB and then the table <code>wp_options</code></li>\n<li>Look for <code>siteurl</code> and <code>home</code> within that table</li>\n<li>Use <code>http://LOCAL_HOST_IP/wordpress</code> for both and save.</li>\n</ol>\n\n<p>Check the full <a href=\"https://codex.wordpress.org/Changing_The_Site_URL\" rel=\"nofollow noreferrer\">Codex Changing Site URL</a> guide.</p>\n" }, { "answer_id": 312393, "author": "Bartosz Was", "author_id": 140315, "author_profile": "https://wordpress.stackexchange.com/users/140315", "pm_score": 1, "selected": false, "text": "<p><strong>Problem solved</strong> </p>\n\n<p>Wordpress and its configuration wasn't the issue here. The real reason why site was working on some devices and on others don't was cached files in browsers.\nSolution was to clear cached files or trying to develop in private mode browsing which isn't caching files.</p>\n\n<p>Also i want to point out that when you want to access host from other computer you have to disable firewall. Strange fact about all this is when you can access to host and see it's dashboard while firewall is enabled going into wordpress directory will cause error.</p>\n" } ]
2018/08/23
[ "https://wordpress.stackexchange.com/questions/312329", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149275/" ]
I have local Instance of WordPress and I want to edit the code of Pages which I created using WordPress Dashboard but I can't find those pages in my local environment folders so how can I find those pages .php files?
Trying to change edit the `wp-config.php` file was a good idea, let's try some extra things to see if they solve the problem. Let's add these lines to the bottom of your `functions.php`: ``` update_option( 'siteurl', 'http://LOCAL_HOST_IP/wordpress' ); update_option( 'home', 'http://LOCAL_HOST_IP/wordpress' ); ``` --- Using Relocate method --------------------- Edit your `wp-config.php` file inserting: ``` define('RELOCATE',true); ``` After that, from your browser manually access to `wp-login.php`. For example, type `http://LOCAL_HOST_IP/wordpress/wp-login.php` into your browser's address bar, and then login as usual. --- Changing the URL directly in the database ----------------------------------------- 1. Login to phpMyAdmin. 2. Find your DB and then the table `wp_options` 3. Look for `siteurl` and `home` within that table 4. Use `http://LOCAL_HOST_IP/wordpress` for both and save. Check the full [Codex Changing Site URL](https://codex.wordpress.org/Changing_The_Site_URL) guide.
312,391
<p>I have added a custom field (checkbox) to product variations with the following code:</p> <pre><code>/** * Create new fields for variations * */ function variation_settings_fields( $loop, $variation_data, $variation ) { woocommerce_wp_checkbox( array( 'id' =&gt; '_wholesale_checkbox[' . $variation-&gt;ID . ']', 'label' =&gt; 'Visa endast för företagskunder', 'description' =&gt; '', 'value' =&gt; get_post_meta( $variation-&gt;ID, '_wholesale_checkbox', true ), ) ); } /** * Save new fields for variations * */ function save_variation_settings_fields( $post_id ) { // Checkbox $checkbox = isset( $_POST['_wholesale_checkbox'][ $post_id ] ) ? 'yes' : 'no'; update_post_meta( $post_id, '_wholesale_checkbox', $checkbox ); } add_action( 'woocommerce_variation_options', 'variation_settings_fields', 10, 3 ); add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 ); </code></pre> <p>It adds the checkbox as desired as seen in the screenshot. </p> <p><a href="https://i.stack.imgur.com/xkCD1.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xkCD1.jpg" alt="enter image description here"></a></p> <p>Now I want to conditionally hide or show the product variation in the frontend based on this field. The problem is I have some custom variation list in place (not my work) and I couldn't figure out how to get hold of the _wholesale_checkbox field to skip the variation (for which the checkbox is checked) in the loop that is outputting the list. See code for outputting the custom variation list below:</p> <pre><code>/** * Convert WooCommerce variation dropdown to radio buttons. * * @param string $html Original dropdown html. * @param array $args Arguments. */ function ac_variation_radio_buttons( $html, $args ) { $options = $args['options']; $product = $args['product']; $attribute = $args['attribute']; $name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute ); $id = $args['id'] ? $args['id'] : sanitize_title( $attribute ); if ( empty( $options ) &amp;&amp; ! empty( $product ) &amp;&amp; ! empty( $attribute ) ) { $attributes = $product-&gt;get_variation_attributes(); $options = $attributes[ $attribute ]; } // Output original dropdown element. echo $html; /* Create custom radio input list */ $html = '&lt;section for="' . esc_attr( $id ) . '" class="ac_variation_list_block"&gt;'; if ( ! empty( $options ) ) { if ( $product &amp;&amp; taxonomy_exists( $attribute ) ) { // Get terms if this is a taxonomy - ordered. We need the names too. $terms = wc_get_product_terms( $product-&gt;get_id(), $attribute, [ 'fields' =&gt; 'all', ] ); // var_dump($options); foreach ( $terms as $term ) { /* if (**CUSTOM_FIELD is checked** )) { continue; } */ if ( in_array( $term-&gt;slug, $options, true ) ) { $html .= '&lt;section class="ac_variation_option"&gt;'; $html .= '&lt;input id="' . esc_attr( $term-&gt;slug ) . '_v" type="radio" name="' . esc_attr( $name ) . '_g" value="' . esc_attr( $term-&gt;slug ) . '" ' . checked( sanitize_title( $args['selected'] ), $term-&gt;slug, false ) . '/&gt;'; $html .= '&lt;label for="' . esc_attr( $term-&gt;slug ) . '_v"&gt;&lt;span&gt;&lt;/span&gt;' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term-&gt;name ) ) . '&lt;/label&gt;'; $html .= '&lt;/section&gt;'; } } } } $html .= '&lt;/section&gt;'; echo $html; } add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'ac_variation_radio_buttons', 10, 2 ); </code></pre>
[ { "answer_id": 312909, "author": "Out of Orbit", "author_id": 148251, "author_profile": "https://wordpress.stackexchange.com/users/148251", "pm_score": 1, "selected": false, "text": "<p>I ultimately solved this by manipulating the $options array. See full code below for conditionally hiding a product variation by a custom field, and display variations as radio buttons. Solution marked with comments</p>\n\n<pre><code>/**\n* Convert WooCommerce variation dropdown to radio buttons.\n*\n* @param string $html Original dropdown html.\n* @param array $args Arguments.\n*/\nfunction ac_variation_radio_buttons( $html, $args ) {\n$options = $args['options'];\n$product = $args['product'];\n$attribute = $args['attribute'];\n$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );\n$id = $args['id'] ? $args['id'] : sanitize_title( $attribute );\n\nif ( empty( $options ) &amp;&amp; ! empty( $product ) &amp;&amp; ! empty( $attribute ) ) {\n $attributes = $product-&gt;get_variation_attributes();\n $options = $attributes[ $attribute ];\n}\n\n// Output original dropdown element.\necho $html;\n\n/**** ADDED CODE *****/\n//Remove wholesale products for regular users\nif($product-&gt;is_type( 'variable' )){\n $user = wp_get_current_user();\n if(!in_array('fretagskund', $user-&gt;roles)){\n foreach ( $product-&gt;get_children() as $child_id ) {\n $variation = wc_get_product( $child_id );\n\n if ( ! $variation || ! $variation-&gt;exists() ) {\n continue;\n }\n\n if(get_post_meta($variation-&gt;get_id(), '_wholesale_checkbox', true) === \"yes\" ){\n $attribute_name = get_post_meta($variation-&gt;get_id(), 'attribute_pa_storlek', true);\n\n if ( in_array( $attribute_name, $options, true ) ) {\n $options = array_diff($options, array($attribute_name));\n }\n\n }\n\n }\n }\n}\n\n/* Create custom radio input list */\n$html = '&lt;section for=\"' . esc_attr( $id ) . '\" class=\"ac_variation_list_block\"&gt;';\n\nif ( ! empty( $options ) ) {\n if ( $product &amp;&amp; taxonomy_exists( $attribute ) ) {\n // Get terms if this is a taxonomy - ordered. We need the names too.\n $terms = wc_get_product_terms( $product-&gt;get_id(), $attribute, [\n 'fields' =&gt; 'all',\n ] );\n\n foreach ( $terms as $term ) {\n if ( in_array( $term-&gt;slug, $options, true ) ) {\n $html .= '&lt;section class=\"ac_variation_option\"&gt;';\n $html .= '&lt;input id=\"' . esc_attr( $term-&gt;slug ) . '_v\" type=\"radio\" name=\"' . esc_attr( $name ) . '_g\" value=\"' . esc_attr( $term-&gt;slug ) . '\" ' . checked( sanitize_title( $args['selected'] ), $term-&gt;slug, false ) . '/&gt;';\n $html .= '&lt;label for=\"' . esc_attr( $term-&gt;slug ) . '_v\"&gt;&lt;span&gt;&lt;/span&gt;' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term-&gt;name ) ) . '&lt;/label&gt;';\n $html .= '&lt;/section&gt;';\n }\n }\n }\n}\n\n$html .= '&lt;/section&gt;';\n\necho $html;\n}\n\n\nadd_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'ac_variation_radio_buttons', 10, 2 );\n</code></pre>\n" }, { "answer_id": 410401, "author": "eoink", "author_id": 226622, "author_profile": "https://wordpress.stackexchange.com/users/226622", "pm_score": 0, "selected": false, "text": "<p>Code to hide these variations from the standard WC dropdown:</p>\n<p>Notes - 1. I'm using &quot;b2bcustomer&quot; role name, change as needed, 2. &quot;gewicht&quot; is my attribute slug, change as needed.</p>\n<pre><code>function hide_b2b_variations( $html, $args ) {\n$options = $args['options'];\n$product = $args['product'];\n$attribute = $args['attribute'];\n$name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute );\n$id = $args['id'] ? $args['id'] : sanitize_title( $attribute );\n\nif ( empty( $options ) &amp;&amp; ! empty( $product ) &amp;&amp; ! empty( $attribute ) ) {\n $attributes = $product-&gt;get_variation_attributes();\n $options = $attributes[ $attribute ];\n}\n\nif($product-&gt;is_type( 'variable' )){\n $user = wp_get_current_user();\n if(in_array('b2bcustomer', $user-&gt;roles)){\n foreach ( $product-&gt;get_children() as $child_id ) {\n $variation = wc_get_product( $child_id );\n\n if ( ! $variation || ! $variation-&gt;exists() ) {\n continue;\n }\n\n if(get_post_meta($variation-&gt;get_id(), '_wholesale_checkbox', true) === &quot;yes&quot; ){\n $attribute_name = get_post_meta($variation-&gt;get_id(), 'attribute_pa_gewicht', true);\n if ( in_array( $attribute_name, $options, true ) ) {\n $options = array_diff($options, array($attribute_name));\n }\n\n }\n\n }\n }\n}\n \n\n$html = '&lt;select id=&quot;' . esc_attr( $id ) .'1'. '&quot; class name=&quot;attribute_pa_gewicht&quot; data-attribute_name=&quot;attribute_pa_gewicht&quot; data-show_option_none=&quot;yes&quot;&gt; ';\n\nif ( ! empty( $options ) ) {\n if ( $product &amp;&amp; taxonomy_exists( $attribute ) ) {\n\n $terms = wc_get_product_terms( $product-&gt;get_id(), $attribute, [\n 'fields' =&gt; 'all',\n ] );\n $html .='&lt;option value&gt;Choose an option&lt;/option&gt;';\n foreach ( $terms as $term ) {\n if ( in_array( $term-&gt;slug, $options, true ) ) {\n $html .= '&lt;option value=&quot;' .esc_attr( $term-&gt;slug) .'&quot; class=&quot;attached enabled&quot;&gt;' .esc_attr( $term-&gt;name) .'&lt;/option&gt;';\n\n }\n }\n }\n}\n\n$html .= '&lt;/select&gt;';\n\necho $html;\n\n\n}\n\nadd_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'hide_b2b_variations', 10, 2 );\n</code></pre>\n<p>Also code for showing the new lowest price when hiding variations, or when showing all variations:\nNote - I'm using &quot;von&quot; for the prefix, change it to &quot;From&quot; or something if needed</p>\n<pre><code>function variable_price_format( $price, $product ) {\n\n$prefix = 'von ';\n\n $user = wp_get_current_user();\n if(in_array('b2bcustomer', $user-&gt;roles)){\n $min_price_regular = 1000;\n $min_price_sale = 0;\n foreach ( $product-&gt;get_children() as $child_id ) {\n $variation = wc_get_product( $child_id );\n\n if ( ! $variation || ! $variation-&gt;exists() ) {\n continue;\n }\n\n if(get_post_meta($variation-&gt;get_id(), '_wholesale_checkbox', true) === &quot;no&quot; ){\n $attribute_name = get_post_meta($variation-&gt;get_id(), 'attribute_pa_gewicht', true);\n $price_regular = get_post_meta($variation-&gt;get_id(), '_regular_price', true);\n $price_sale = get_post_meta($variation-&gt;get_id(), '_sale_price', true);\n\n if (($price_regular &lt;= $min_price_regular)){\n $min_price_regular = $price_regular; \n }\n if (($price_sale &gt; $min_price_sale)){\n $min_price_sale = $price_sale;\n }\n }\n }\n\n if ($min_price_regular &gt; $min_price_sale){\n return sprintf('%s%s', $prefix, wc_price($min_price_regular));\n }\n else return sprintf('%s%s', $prefix, wc_price($min_price_sale));\n }\n \n else \n {\n $min_price_regular = $product-&gt;get_variation_regular_price( 'min', true );\n $min_price_sale = $product-&gt;get_variation_sale_price( 'min', true );\n $max_price = $product-&gt;get_variation_price( 'max', true );\n $min_price = $product-&gt;get_variation_price( 'min', true );\n\n\n $price = ( $min_price_sale == $min_price_regular ) ?\n \n wc_price( $min_price_regular ) :\n '' . wc_price( $min_price_regular ) . '' . '' . wc_price( $min_price_sale ) . '';\n return ( $min_price == $max_price ) ?\n $price :\n sprintf('%s%s', $prefix, $price);\n }\n}\n\nadd_filter( 'woocommerce_variable_sale_price_html', 'variable_price_format', 10, 2 );\nadd_filter( 'woocommerce_variable_price_html', 'variable_price_format', 10, 2 );\n</code></pre>\n" } ]
2018/08/24
[ "https://wordpress.stackexchange.com/questions/312391", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148251/" ]
I have added a custom field (checkbox) to product variations with the following code: ``` /** * Create new fields for variations * */ function variation_settings_fields( $loop, $variation_data, $variation ) { woocommerce_wp_checkbox( array( 'id' => '_wholesale_checkbox[' . $variation->ID . ']', 'label' => 'Visa endast för företagskunder', 'description' => '', 'value' => get_post_meta( $variation->ID, '_wholesale_checkbox', true ), ) ); } /** * Save new fields for variations * */ function save_variation_settings_fields( $post_id ) { // Checkbox $checkbox = isset( $_POST['_wholesale_checkbox'][ $post_id ] ) ? 'yes' : 'no'; update_post_meta( $post_id, '_wholesale_checkbox', $checkbox ); } add_action( 'woocommerce_variation_options', 'variation_settings_fields', 10, 3 ); add_action( 'woocommerce_save_product_variation', 'save_variation_settings_fields', 10, 2 ); ``` It adds the checkbox as desired as seen in the screenshot. [![enter image description here](https://i.stack.imgur.com/xkCD1.jpg)](https://i.stack.imgur.com/xkCD1.jpg) Now I want to conditionally hide or show the product variation in the frontend based on this field. The problem is I have some custom variation list in place (not my work) and I couldn't figure out how to get hold of the \_wholesale\_checkbox field to skip the variation (for which the checkbox is checked) in the loop that is outputting the list. See code for outputting the custom variation list below: ``` /** * Convert WooCommerce variation dropdown to radio buttons. * * @param string $html Original dropdown html. * @param array $args Arguments. */ function ac_variation_radio_buttons( $html, $args ) { $options = $args['options']; $product = $args['product']; $attribute = $args['attribute']; $name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute ); $id = $args['id'] ? $args['id'] : sanitize_title( $attribute ); if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) { $attributes = $product->get_variation_attributes(); $options = $attributes[ $attribute ]; } // Output original dropdown element. echo $html; /* Create custom radio input list */ $html = '<section for="' . esc_attr( $id ) . '" class="ac_variation_list_block">'; if ( ! empty( $options ) ) { if ( $product && taxonomy_exists( $attribute ) ) { // Get terms if this is a taxonomy - ordered. We need the names too. $terms = wc_get_product_terms( $product->get_id(), $attribute, [ 'fields' => 'all', ] ); // var_dump($options); foreach ( $terms as $term ) { /* if (**CUSTOM_FIELD is checked** )) { continue; } */ if ( in_array( $term->slug, $options, true ) ) { $html .= '<section class="ac_variation_option">'; $html .= '<input id="' . esc_attr( $term->slug ) . '_v" type="radio" name="' . esc_attr( $name ) . '_g" value="' . esc_attr( $term->slug ) . '" ' . checked( sanitize_title( $args['selected'] ), $term->slug, false ) . '/>'; $html .= '<label for="' . esc_attr( $term->slug ) . '_v"><span></span>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) ) . '</label>'; $html .= '</section>'; } } } } $html .= '</section>'; echo $html; } add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'ac_variation_radio_buttons', 10, 2 ); ```
I ultimately solved this by manipulating the $options array. See full code below for conditionally hiding a product variation by a custom field, and display variations as radio buttons. Solution marked with comments ``` /** * Convert WooCommerce variation dropdown to radio buttons. * * @param string $html Original dropdown html. * @param array $args Arguments. */ function ac_variation_radio_buttons( $html, $args ) { $options = $args['options']; $product = $args['product']; $attribute = $args['attribute']; $name = $args['name'] ? $args['name'] : 'attribute_' . sanitize_title( $attribute ); $id = $args['id'] ? $args['id'] : sanitize_title( $attribute ); if ( empty( $options ) && ! empty( $product ) && ! empty( $attribute ) ) { $attributes = $product->get_variation_attributes(); $options = $attributes[ $attribute ]; } // Output original dropdown element. echo $html; /**** ADDED CODE *****/ //Remove wholesale products for regular users if($product->is_type( 'variable' )){ $user = wp_get_current_user(); if(!in_array('fretagskund', $user->roles)){ foreach ( $product->get_children() as $child_id ) { $variation = wc_get_product( $child_id ); if ( ! $variation || ! $variation->exists() ) { continue; } if(get_post_meta($variation->get_id(), '_wholesale_checkbox', true) === "yes" ){ $attribute_name = get_post_meta($variation->get_id(), 'attribute_pa_storlek', true); if ( in_array( $attribute_name, $options, true ) ) { $options = array_diff($options, array($attribute_name)); } } } } } /* Create custom radio input list */ $html = '<section for="' . esc_attr( $id ) . '" class="ac_variation_list_block">'; if ( ! empty( $options ) ) { if ( $product && taxonomy_exists( $attribute ) ) { // Get terms if this is a taxonomy - ordered. We need the names too. $terms = wc_get_product_terms( $product->get_id(), $attribute, [ 'fields' => 'all', ] ); foreach ( $terms as $term ) { if ( in_array( $term->slug, $options, true ) ) { $html .= '<section class="ac_variation_option">'; $html .= '<input id="' . esc_attr( $term->slug ) . '_v" type="radio" name="' . esc_attr( $name ) . '_g" value="' . esc_attr( $term->slug ) . '" ' . checked( sanitize_title( $args['selected'] ), $term->slug, false ) . '/>'; $html .= '<label for="' . esc_attr( $term->slug ) . '_v"><span></span>' . esc_html( apply_filters( 'woocommerce_variation_option_name', $term->name ) ) . '</label>'; $html .= '</section>'; } } } } $html .= '</section>'; echo $html; } add_filter( 'woocommerce_dropdown_variation_attribute_options_html', 'ac_variation_radio_buttons', 10, 2 ); ```
312,444
<p>in my single.php i took a data from one $_GET[] value and i'm using this like</p> <p><strong>domain.com/example-slug/?holder=value</strong></p> <p>The thing i want is <strong>domain.com/example-slug/value</strong> or <strong>domain.com/example-slug/holder/value</strong></p> <p>so, how i can to this?</p>
[ { "answer_id": 312450, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 0, "selected": false, "text": "<p>You can rewrite your URL using Rewrite rule like this </p>\n\n<pre><code>Options +FollowSymLinks\nRewriteEngine on\n\nRewriteCond %{HTTP_HOST} ^domain.com [NC]\nRewriteRule ^(.*)$ domain.com/$1 [L,R=301,NC]\n\nRewriteRule ^example-slug/value $ example-slug/?holder=$1 [L]\n</code></pre>\n" }, { "answer_id": 312477, "author": "scytale", "author_id": 128374, "author_profile": "https://wordpress.stackexchange.com/users/128374", "pm_score": 0, "selected": false, "text": "<p>You can add a rewrite function filter to your \"site specific functions plugin\" or to theme's functions.php</p>\n\n<p>After editing functions.php or activating your plugin you will need to <strong>flush WP's rewrite rules</strong>. Go to Admin Dashboard >Settings > Permalinks and click save (your new rules will then be applied)</p>\n\n<p>Examples (not tested):</p>\n\n<p><strong>For posts:</strong></p>\n\n<pre><code>&lt;?php\n/*\nPlugin Name: my post rewrite plugin\n*/\nfunction my_post_rules($rules)\n{\n global $wp_rewrite;\n $my_rule = array(\n '(.+?)/(.+?)$' =&gt; 'index.php?category_name=$matches[1]&amp;holder=$matches[2]'\n// or\n 'example-slug/(.+?)$' =&gt; 'index.php?category_name=example-slug&amp;holder=$matches[1]'\n );\n return array_merge($my_rule, $rules);\n}\nadd_filter('post_rewrite_rules', 'my_post_rules');\n</code></pre>\n\n<p><strong>For pages:</strong></p>\n\n<pre><code>function my_page_rules($rules)\n{\n global $wp_rewrite;\n $my_rule = array(\n '(.+?)/(.+?)$' =&gt; 'index.php?page_name=$matches[1]&amp;holder=$matches[2]'\n// or\n 'example-slug/(.+?)$' =&gt; 'index.php?page_name=' . 'example-slug&amp;holder=$matches[1]'\n );\n return array_merge($my_rule, $rules);\n}\nadd_filter('page_rewrite_rules', 'my_page_rules');\n</code></pre>\n\n<p>Use of WP's <em><a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\">get_query_var</a></em> function in your template is probably unnecessary in your case, but it might be needed for \"GET values\" used in other circumstances. So it is a good habit to use <em>get_query_var</em> in your template and \"declare\" the query var via <em><a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars\" rel=\"nofollow noreferrer\">query_var filter</a></em>.</p>\n" }, { "answer_id": 312793, "author": "Tedinoz", "author_id": 24711, "author_profile": "https://wordpress.stackexchange.com/users/24711", "pm_score": 1, "selected": false, "text": "<p>You don't need to do anything with rewrite rules. </p>\n\n<p>Your example (\"domain.com/example-slug/?holder=value\") is a perfect example of \"Plain\" Permalinks. So your starting point is to set Permalinks (Settings > Permalinks) to something other than \"Plain\". This will take the \"/?\" component out of the URL, and generate a URL in your preferred format.</p>\n\n<p>The second thing is to capture the URL, parse it and get the \"value\" (to use your words). You can do this with a function like the one below. Put this function in your functions.php (or a plugin if you prefer). Then call it on the page/post where you want to get the \"value\". The function will yield the \"value\" as a variable $myvalue. You can expand the function to do more stuff, or you could return the value elsewhere to do something with it.</p>\n\n<pre><code>function getslug(){\n\n // get the url\n $myurl = home_url( $wp-&gt;request );\n //echo \"&lt;p&gt;The page url is \".$myurl.\" &lt;/p&gt;\"; //DEBUG\n\n // Explode the url to get access to the taxonomy and terms\n $pageterms = explode('/', $myurl);\n //echo \"the exploded components of the URL &lt;pre&gt;\";print_r($pageterms);echo \"&lt;/pre&gt;\"; //DEBUG\n\n // the value is always the last element in the url, so we'll count the number of elements\n $mycount = count($pageterms);\n //echo \"&lt;p&gt;The element count is \".$mycount.\" &lt;/p&gt;\"; //DEBUG\n\n // since array keys always start with zero, the key for the value will be the count minus 1 (to allow for the zero)\n $myvalue = $pageterms[$mycount-1];\n //echo \"&lt;p&gt;My value is \".$myvalue.\" &lt;/p&gt;\"; //DEBUG\n\n}\n</code></pre>\n\n<p><strong>PS</strong>: I've left my echo statements (used for Debugging) in this example; you can just delete them if you don't need/want them.</p>\n" } ]
2018/08/25
[ "https://wordpress.stackexchange.com/questions/312444", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149362/" ]
in my single.php i took a data from one $\_GET[] value and i'm using this like **domain.com/example-slug/?holder=value** The thing i want is **domain.com/example-slug/value** or **domain.com/example-slug/holder/value** so, how i can to this?
You don't need to do anything with rewrite rules. Your example ("domain.com/example-slug/?holder=value") is a perfect example of "Plain" Permalinks. So your starting point is to set Permalinks (Settings > Permalinks) to something other than "Plain". This will take the "/?" component out of the URL, and generate a URL in your preferred format. The second thing is to capture the URL, parse it and get the "value" (to use your words). You can do this with a function like the one below. Put this function in your functions.php (or a plugin if you prefer). Then call it on the page/post where you want to get the "value". The function will yield the "value" as a variable $myvalue. You can expand the function to do more stuff, or you could return the value elsewhere to do something with it. ``` function getslug(){ // get the url $myurl = home_url( $wp->request ); //echo "<p>The page url is ".$myurl." </p>"; //DEBUG // Explode the url to get access to the taxonomy and terms $pageterms = explode('/', $myurl); //echo "the exploded components of the URL <pre>";print_r($pageterms);echo "</pre>"; //DEBUG // the value is always the last element in the url, so we'll count the number of elements $mycount = count($pageterms); //echo "<p>The element count is ".$mycount." </p>"; //DEBUG // since array keys always start with zero, the key for the value will be the count minus 1 (to allow for the zero) $myvalue = $pageterms[$mycount-1]; //echo "<p>My value is ".$myvalue." </p>"; //DEBUG } ``` **PS**: I've left my echo statements (used for Debugging) in this example; you can just delete them if you don't need/want them.
312,492
<p>I need to query all of my posts as an array in example:</p> <pre><code>'options' =&gt; [ 'Post ID' =&gt; __('Post Name'), 'Post ID' =&gt; __('Post Name'), ], </code></pre> <p>How can i do it? </p> <p>tried this but it gives me only the ID's:</p> <pre><code>function query_posts_as_array(){ $args = array( 'post_status' =&gt; 'publish', 'fields' =&gt; 'ids', ); $result_query = new WP_Query( $args ); $ID_array = $result_query-&gt;posts; wp_reset_postdata(); return $ID_array; </code></pre>
[ { "answer_id": 312499, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>You're trying to make <code>WP_Query</code> give you everything in a single API call, but that won't work.</p>\n\n<p>Instead, break it down into multiple steps, e.g.:</p>\n\n<ul>\n<li>Create an empty list</li>\n<li>fetch all the posts</li>\n<li>foreach post:\n\n<ul>\n<li>add its ID and name to the list</li>\n</ul></li>\n<li>you now have alist of ID's and names</li>\n</ul>\n" }, { "answer_id": 312542, "author": "Wojciech Wyszyński", "author_id": 149398, "author_profile": "https://wordpress.stackexchange.com/users/149398", "pm_score": 0, "selected": false, "text": "<p>I found that this code: </p>\n\n<pre><code>$args = array( 'posts_per_page' =&gt; -1, 'fields' =&gt; '', ); \n$posts_from_query = get_posts( $args ); \n$id_list = []; \n\nforeach( $posts_from_query as $single) { \n $id_list[ $single-&gt;ID ] = $single-&gt;post_title; \n} \nreturn $id_list; \n</code></pre>\n\n<p>prints this: </p>\n\n<pre><code>Array ( [0] =&gt; Nulla molestie venenatis odio nec pulvinar. [1] =&gt; Video Post ) \n</code></pre>\n\n<p>It prints numbers from 0... instead of post ID's. What could i do wrong? </p>\n" }, { "answer_id": 312650, "author": "Anson W Han", "author_id": 129547, "author_profile": "https://wordpress.stackexchange.com/users/129547", "pm_score": 0, "selected": false, "text": "<p>If you just need the post ID and post title, you can use a simple SQL query and avoid the multiple steps and php loops with the standard Wordpress query functions.</p>\n\n<pre><code>global $wpdb;\n$option_list = $wpdb-&gt;get_results( \"SELECT id, post_title FROM wp_6gdyzh_posts\" );\n</code></pre>\n\n<p>This approach is <strong><em>a bit more efficient as it cuts down on the amount of querying/processing done by your webserver for this particular need</em></strong>. </p>\n\n<p>However, with either this direct SQL query approach or the approach where you query all the posts and then loop through to get the title/build the array, you'll want to make sure you apply a limit to the main query if the posts/post-types you are querying are frequently being added to the site. If this does end up being the case, you may want to add a sort option and limit option to the query.</p>\n" } ]
2018/08/26
[ "https://wordpress.stackexchange.com/questions/312492", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149398/" ]
I need to query all of my posts as an array in example: ``` 'options' => [ 'Post ID' => __('Post Name'), 'Post ID' => __('Post Name'), ], ``` How can i do it? tried this but it gives me only the ID's: ``` function query_posts_as_array(){ $args = array( 'post_status' => 'publish', 'fields' => 'ids', ); $result_query = new WP_Query( $args ); $ID_array = $result_query->posts; wp_reset_postdata(); return $ID_array; ```
You're trying to make `WP_Query` give you everything in a single API call, but that won't work. Instead, break it down into multiple steps, e.g.: * Create an empty list * fetch all the posts * foreach post: + add its ID and name to the list * you now have alist of ID's and names
312,545
<p>I just come up with this issue for a project that uses a lot of taxonomies and I need to list posts using the taxonomies itself, not only the terms.</p> <p>I have a taxonomy called "Colors", so the terms can be "red", "blue" etc and we can see all posts using the terms visiting:</p> <pre><code>site.com/colors/red site.com/colors/blue </code></pre> <p><strong>I want to be able to access "site.com/colors" and there list everything using any term from "Colors" taxonomy</strong> That's is, I want to list posts using the taxo not only terms.</p> <p>For a small project, I created a <a href="https://developer.wordpress.org/themes/template-files-section/page-template-files/" rel="nofollow noreferrer">page template</a> for a static page with a custom query that did this, but on this current project I have about 8 taxonomies and to create static pages for each taxo to do the same thing seems a bit lame.</p>
[ { "answer_id": 312499, "author": "Tom J Nowell", "author_id": 736, "author_profile": "https://wordpress.stackexchange.com/users/736", "pm_score": 2, "selected": true, "text": "<p>You're trying to make <code>WP_Query</code> give you everything in a single API call, but that won't work.</p>\n\n<p>Instead, break it down into multiple steps, e.g.:</p>\n\n<ul>\n<li>Create an empty list</li>\n<li>fetch all the posts</li>\n<li>foreach post:\n\n<ul>\n<li>add its ID and name to the list</li>\n</ul></li>\n<li>you now have alist of ID's and names</li>\n</ul>\n" }, { "answer_id": 312542, "author": "Wojciech Wyszyński", "author_id": 149398, "author_profile": "https://wordpress.stackexchange.com/users/149398", "pm_score": 0, "selected": false, "text": "<p>I found that this code: </p>\n\n<pre><code>$args = array( 'posts_per_page' =&gt; -1, 'fields' =&gt; '', ); \n$posts_from_query = get_posts( $args ); \n$id_list = []; \n\nforeach( $posts_from_query as $single) { \n $id_list[ $single-&gt;ID ] = $single-&gt;post_title; \n} \nreturn $id_list; \n</code></pre>\n\n<p>prints this: </p>\n\n<pre><code>Array ( [0] =&gt; Nulla molestie venenatis odio nec pulvinar. [1] =&gt; Video Post ) \n</code></pre>\n\n<p>It prints numbers from 0... instead of post ID's. What could i do wrong? </p>\n" }, { "answer_id": 312650, "author": "Anson W Han", "author_id": 129547, "author_profile": "https://wordpress.stackexchange.com/users/129547", "pm_score": 0, "selected": false, "text": "<p>If you just need the post ID and post title, you can use a simple SQL query and avoid the multiple steps and php loops with the standard Wordpress query functions.</p>\n\n<pre><code>global $wpdb;\n$option_list = $wpdb-&gt;get_results( \"SELECT id, post_title FROM wp_6gdyzh_posts\" );\n</code></pre>\n\n<p>This approach is <strong><em>a bit more efficient as it cuts down on the amount of querying/processing done by your webserver for this particular need</em></strong>. </p>\n\n<p>However, with either this direct SQL query approach or the approach where you query all the posts and then loop through to get the title/build the array, you'll want to make sure you apply a limit to the main query if the posts/post-types you are querying are frequently being added to the site. If this does end up being the case, you may want to add a sort option and limit option to the query.</p>\n" } ]
2018/08/26
[ "https://wordpress.stackexchange.com/questions/312545", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/17048/" ]
I just come up with this issue for a project that uses a lot of taxonomies and I need to list posts using the taxonomies itself, not only the terms. I have a taxonomy called "Colors", so the terms can be "red", "blue" etc and we can see all posts using the terms visiting: ``` site.com/colors/red site.com/colors/blue ``` **I want to be able to access "site.com/colors" and there list everything using any term from "Colors" taxonomy** That's is, I want to list posts using the taxo not only terms. For a small project, I created a [page template](https://developer.wordpress.org/themes/template-files-section/page-template-files/) for a static page with a custom query that did this, but on this current project I have about 8 taxonomies and to create static pages for each taxo to do the same thing seems a bit lame.
You're trying to make `WP_Query` give you everything in a single API call, but that won't work. Instead, break it down into multiple steps, e.g.: * Create an empty list * fetch all the posts * foreach post: + add its ID and name to the list * you now have alist of ID's and names
312,579
<p>i want to disable click our product image on archives product page. so, user only can click from the button.</p> <p><a href="https://i.stack.imgur.com/RsApZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RsApZ.png" alt="enter image description here"></a></p>
[ { "answer_id": 312582, "author": "Carlos Faria", "author_id": 39047, "author_profile": "https://wordpress.stackexchange.com/users/39047", "pm_score": 2, "selected": true, "text": "<p>In your functions.php</p>\n\n<pre><code>remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 );\nremove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 );\n</code></pre>\n" }, { "answer_id": 312618, "author": "Angga Pradipta", "author_id": 141909, "author_profile": "https://wordpress.stackexchange.com/users/141909", "pm_score": -1, "selected": false, "text": "<pre><code>cursor: default !important;\npointer-events: none !important;\n</code></pre>\n" } ]
2018/08/27
[ "https://wordpress.stackexchange.com/questions/312579", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141909/" ]
i want to disable click our product image on archives product page. so, user only can click from the button. [![enter image description here](https://i.stack.imgur.com/RsApZ.png)](https://i.stack.imgur.com/RsApZ.png)
In your functions.php ``` remove_action( 'woocommerce_before_shop_loop_item', 'woocommerce_template_loop_product_link_open', 10 ); remove_action( 'woocommerce_after_shop_loop_item', 'woocommerce_template_loop_product_link_close', 5 ); ```
312,587
<p>I tested posting a blog post to Facebook it shows a too large pic of the header title design you made for the home page not blog image. It doesn't show the feature photo from that blog post. Also, when I share a blog post link via text, it doesn't show a thumbnail photo of that blog post's feature photo, just words. When I post to Twitter, it only shows the URL, no photo. In Instagram it open account but no sharing functionality. Here is my code.</p> <pre><code> &lt;a href="http://www.facebook.com/sharer.php?u=&lt;?php echo urlencode(get_permalink()); ?&gt;" target="_blank" class="link" title="&lt;?php esc_attr_e('Share on Facebook', 'cheerup'); ?&gt;"&gt;&lt;i class="fa fa-facebook"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="http://twitter.com/home?status=&lt;?php echo urlencode(get_permalink()); ?&gt;" target="_blank" class="link" title="&lt;?php esc_attr_e('Share on Twitter', 'cheerup'); ?&gt;"&gt;&lt;i class="fa fa-twitter"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="https://www.instagram.com/share?url=&lt;?php echo urlencode(get_permalink()); ?&gt;" target="_blank" class="link" title="&lt;?php esc_attr_e('Share on Instagram', 'cheerup'); ?&gt;"&gt;&lt;i class="fa fa-instagram"&gt;&lt;/i&gt;&lt;/a&gt; &lt;a href="http://pinterest.com/pin/create/button/?url=&lt;?php echo urlencode(get_permalink()); ?&gt;&amp;amp;media=&lt;?php echo urlencode($media); ?&gt;&amp;amp;description=&lt;?php echo urlencode($title); ?&gt;" target="_blank" class="link" title="&lt;?php esc_attr_e('Share on Pinterest', 'cheerup'); ?&gt;"&gt;&lt;i class="fa fa-pinterest-p"&gt;&lt;/i&gt;&lt;/a&gt; </code></pre>
[ { "answer_id": 312594, "author": "user141080", "author_id": 141080, "author_profile": "https://wordpress.stackexchange.com/users/141080", "pm_score": 0, "selected": false, "text": "<p>Most of the social media platforms use there own \"social media tags\" to structure the content of a website. The platforms use the information from these tags to display a webseite with more information for instance Facebook shows your link with the thumbnail. </p>\n\n<p>I suspect that your website haven`t these \"social media tags\".</p>\n\n<p>The easiest way to add these \"social media tags\" to your page would be to use a plugin like <a href=\"https://wordpress.org/plugins/wordpress-seo/\" rel=\"nofollow noreferrer\">yoast</a>.</p>\n\n<p>If you are a little bit more interested in this topic, then the following links may be helpful:</p>\n\n<ul>\n<li>Facebook use the <a href=\"http://ogp.me/\" rel=\"nofollow noreferrer\">Open Graph protocol</a></li>\n<li>Twitter use the <a href=\"https://developer.twitter.com/en/docs/tweets/optimize-with-cards/guides/getting-started.html\" rel=\"nofollow noreferrer\">card markup</a></li>\n</ul>\n" }, { "answer_id": 327282, "author": "Alex MacArthur", "author_id": 89080, "author_profile": "https://wordpress.stackexchange.com/users/89080", "pm_score": 1, "selected": false, "text": "<p>Your pages need to have the Open Graph meta tags required for social networks to parse the needed information &amp; display it correctly. If you're looking for a simple, straightforward solution to this, you should check out Complete Open Graph, a plugin I wrote to handle it. Much less bloat than something like Yoast, because instead of trying to do all the things, it focuses on doing one thing well -- Open Graph management. Activate it, and it'll work right out of the box.</p>\n\n<p><a href=\"https://wordpress.org/plugins/complete-open-graph/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/complete-open-graph/</a></p>\n" } ]
2018/08/27
[ "https://wordpress.stackexchange.com/questions/312587", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149459/" ]
I tested posting a blog post to Facebook it shows a too large pic of the header title design you made for the home page not blog image. It doesn't show the feature photo from that blog post. Also, when I share a blog post link via text, it doesn't show a thumbnail photo of that blog post's feature photo, just words. When I post to Twitter, it only shows the URL, no photo. In Instagram it open account but no sharing functionality. Here is my code. ``` <a href="http://www.facebook.com/sharer.php?u=<?php echo urlencode(get_permalink()); ?>" target="_blank" class="link" title="<?php esc_attr_e('Share on Facebook', 'cheerup'); ?>"><i class="fa fa-facebook"></i></a> <a href="http://twitter.com/home?status=<?php echo urlencode(get_permalink()); ?>" target="_blank" class="link" title="<?php esc_attr_e('Share on Twitter', 'cheerup'); ?>"><i class="fa fa-twitter"></i></a> <a href="https://www.instagram.com/share?url=<?php echo urlencode(get_permalink()); ?>" target="_blank" class="link" title="<?php esc_attr_e('Share on Instagram', 'cheerup'); ?>"><i class="fa fa-instagram"></i></a> <a href="http://pinterest.com/pin/create/button/?url=<?php echo urlencode(get_permalink()); ?>&amp;media=<?php echo urlencode($media); ?>&amp;description=<?php echo urlencode($title); ?>" target="_blank" class="link" title="<?php esc_attr_e('Share on Pinterest', 'cheerup'); ?>"><i class="fa fa-pinterest-p"></i></a> ```
Your pages need to have the Open Graph meta tags required for social networks to parse the needed information & display it correctly. If you're looking for a simple, straightforward solution to this, you should check out Complete Open Graph, a plugin I wrote to handle it. Much less bloat than something like Yoast, because instead of trying to do all the things, it focuses on doing one thing well -- Open Graph management. Activate it, and it'll work right out of the box. <https://wordpress.org/plugins/complete-open-graph/>
312,592
<p>I've added some custom fields into the user profile. It's "Date of Birth".</p> <p>There are "<strong>month_of_birth</strong>", "<strong>day_of_birth</strong>", "<strong>year_of_birth</strong>".</p> <p>How to store them in one meta key ('<strong>birth_date</strong>') ?</p> <p>Here's the code for the custom field :</p> <pre><code>// ADD EXTRA PROFILE FIELD - BIRTH DATE add_action( 'show_user_profile', 'birthdate_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'birthdate_show_extra_profile_fields' ); function birthdate_show_extra_profile_fields( $user ) { ?&gt; &lt;h3 class="birthdate-info"&gt;Date of Birth&lt;/h3&gt; &lt;table class="form-table"&gt; &lt;tr&gt; &lt;th&gt;&lt;label for="birth_date"&gt;Date of Birth&lt;/label&gt;&lt;/th&gt; &lt;td width="30%"&gt; &lt;select name="month_of_birth" id="month_of_birth"&gt; &lt;?php $_value = trim( get_user_meta( $user-&gt;ID, 'month_of_birth', true ) ); foreach ( array( 'not-selected' =&gt; '', 'january' =&gt; 'January', 'february' =&gt; 'February', 'march' =&gt; 'March', 'april' =&gt; 'April', 'may' =&gt; 'May', 'june' =&gt; 'June', 'july' =&gt; 'July', 'august' =&gt; 'August', 'september' =&gt; 'September', 'october' =&gt; 'October', 'november' =&gt; 'November', 'december' =&gt; 'December', ) as $value =&gt; $label ) : $selected = selected( $value, $_value, false ); ?&gt; &lt;option value="&lt;?php echo esc_attr( $value ); ?&gt;"&lt;?php echo $selected; ?&gt;&gt;&lt;?php echo esc_html( $label ); ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td width="20%"&gt; &lt;select name="day_of_birth" id="day_of_birth"&gt; &lt;?php $_value = trim( get_user_meta( $user-&gt;ID, 'day_of_birth', true ) ); foreach ( array( 'not-selected' =&gt; '', '1' =&gt; '1', '2' =&gt; '2', '3' =&gt; '3', '4' =&gt; '4', '5' =&gt; '5', '6' =&gt; '6', '7' =&gt; '7', '8' =&gt; '8', '9' =&gt; '9', '10' =&gt; '10', '11' =&gt; '11', '12' =&gt; '12', '13' =&gt; '13', '14' =&gt; '14', '15' =&gt; '15', '16' =&gt; '16', '17' =&gt; '17', '18' =&gt; '18', '19' =&gt; '19', '20' =&gt; '20', '21' =&gt; '21', '22' =&gt; '22', '23' =&gt; '23', '24' =&gt; '24', '25' =&gt; '25', '26' =&gt; '26', '27' =&gt; '27', '28' =&gt; '28', '29' =&gt; '29', '30' =&gt; '30', '31' =&gt; '31', ) as $value =&gt; $label ) : $selected = selected( $value, $_value, false ); ?&gt; &lt;option value="&lt;?php echo esc_attr( $value ); ?&gt;"&lt;?php echo $selected; ?&gt;&gt;&lt;?php echo esc_html( $label ); ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;td width="25%"&gt; &lt;select name="year_of_birth" id="year_of_birth"&gt; &lt;?php $_value = trim( get_user_meta( $user-&gt;ID, 'year_of_birth', true ) ); foreach ( array( 'not-selected' =&gt; '', '1905' =&gt; '1905', '1906' =&gt; '1906', '1907' =&gt; '1907', '1908' =&gt; '1908', '1909' =&gt; '1909', '1910' =&gt; '1910', '1911' =&gt; '1911', '1912' =&gt; '1912', '1913' =&gt; '1913', '1914' =&gt; '1914', '1915' =&gt; '1915', '1916' =&gt; '1916', '1917' =&gt; '1917', '1918' =&gt; '1918', '1919' =&gt; '1919', '1920' =&gt; '1920', '1921' =&gt; '1921', '1922' =&gt; '1922', '1923' =&gt; '1923', '1924' =&gt; '1924', '1925' =&gt; '1925', '1926' =&gt; '1926', '1927' =&gt; '1927', '1928' =&gt; '1928', '1929' =&gt; '1929', '1930' =&gt; '1930', '1931' =&gt; '1931', '1932' =&gt; '1932', '1933' =&gt; '1933', '1934' =&gt; '1934', '1935' =&gt; '1935', '1936' =&gt; '1936', '1937' =&gt; '1937', '1938' =&gt; '1938', '1939' =&gt; '1939', '1940' =&gt; '1940', '1941' =&gt; '1941', '1942' =&gt; '1942', '1943' =&gt; '1943', '1944' =&gt; '1944', '1945' =&gt; '1945', '1946' =&gt; '1946', '1947' =&gt; '1947', '1948' =&gt; '1948', '1949' =&gt; '1949', '1950' =&gt; '1950', '1951' =&gt; '1951', '1952' =&gt; '1952', '1953' =&gt; '1953', '1954' =&gt; '1954', '1955' =&gt; '1955', '1956' =&gt; '1956', '1957' =&gt; '1957', '1958' =&gt; '1958', '1959' =&gt; '1959', '1960' =&gt; '1960', '1961' =&gt; '1961', '1962' =&gt; '1962', '1963' =&gt; '1963', '1964' =&gt; '1964', '1965' =&gt; '1965', '1966' =&gt; '1966', '1967' =&gt; '1967', '1968' =&gt; '1968', '1969' =&gt; '1969', '1970' =&gt; '1970', '1971' =&gt; '1971', '1972' =&gt; '1972', '1973' =&gt; '1973', '1974' =&gt; '1974', '1975' =&gt; '1975', '1976' =&gt; '1976', '1977' =&gt; '1977', '1978' =&gt; '1978', '1979' =&gt; '1979', '1980' =&gt; '1980', '1981' =&gt; '1981', '1982' =&gt; '1982', '1983' =&gt; '1983', '1984' =&gt; '1984', '1985' =&gt; '1985', '1986' =&gt; '1986', '1987' =&gt; '1987', '1988' =&gt; '1988', '1989' =&gt; '1989', '1990' =&gt; '1990', '1991' =&gt; '1991', '1992' =&gt; '1992', '1993' =&gt; '1993', '1994' =&gt; '1994', '1995' =&gt; '1995', '1996' =&gt; '1996', '1997' =&gt; '1997', '1998' =&gt; '1998', '1999' =&gt; '1999', '2000' =&gt; '2000', '2001' =&gt; '2001', '2002' =&gt; '2002', '2003' =&gt; '2003', '2004' =&gt; '2004', '2005' =&gt; '2005', '2006' =&gt; '2006', '2007' =&gt; '2007', '2008' =&gt; '2008', '2009' =&gt; '2009', '2010' =&gt; '2010', '2011' =&gt; '2011', '2012' =&gt; '2012', '2013' =&gt; '2013', '2014' =&gt; '2014', '2015' =&gt; '2015', '2016' =&gt; '2016', '2017' =&gt; '2017', '2018' =&gt; '2018', ) as $value =&gt; $label ) : $selected = selected( $value, $_value, false ); ?&gt; &lt;option value="&lt;?php echo esc_attr( $value ); ?&gt;"&lt;?php echo $selected; ?&gt;&gt;&lt;?php echo esc_html( $label ); ?&gt;&lt;/option&gt; &lt;?php endforeach; ?&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;/table&gt; </code></pre> <p> <pre><code>// SAVE EXTRA PROFILE FIELD - BIRTH DATE add_action( 'personal_options_update', 'birthdate_save_extra_user_profile_fields' ); add_action( 'edit_user_profile_update', 'birthdate_save_extra_user_profile_fields' ); function birthdate_save_extra_user_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id,'month_of_birth', $_POST['month_of_birth'] ); if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id,'day_of_birth', $_POST['day_of_birth'] ); if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id,'year_of_birth', $_POST['year_of_birth'] ); } </code></pre> <p><strong>UPDATE 2:</strong> SHORTCODE -</p> <pre><code>function user_birthdate_info_shortcode() { if(is_user_logged_in()) { $user_id = get_current_user_id(); $birth_date = get_user_meta($user_id, 'birth_date', false); foreach($birth_date as $key =&gt; $value){ echo $value['month'] . '&amp;nbsp;' . $value['day'] . '&amp;nbsp;' . $value['year']; } }} add_shortcode('currentuser_show_birthdate_info', 'user_birthdate_info_shortcode'); </code></pre>
[ { "answer_id": 312600, "author": "Baikare Sandeep", "author_id": 99404, "author_profile": "https://wordpress.stackexchange.com/users/99404", "pm_score": 0, "selected": false, "text": "<p>You can save these fields in the single user meta field like below:</p>\n\n<pre><code>\n // SAVE EXTRA PROFILE FIELD - BIRTH DATE\nadd_action( 'personal_options_update', 'birthdate_save_extra_user_profile_fields' );\nadd_action( 'edit_user_profile_update', 'birthdate_save_extra_user_profile_fields' );\n\nfunction birthdate_save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) )\n return false;\n\n // Use this fields to save the selected the options\n update_user_meta( $user_id,'month_of_birth', $_POST['month_of_birth'] );\n update_user_meta( $user_id,'day_of_birth', $_POST['day_of_birth'] );\n update_user_meta( $user_id,'year_of_birth', $_POST['year_of_birth'] );\n\n\n $date_of_birth = array();\n $date_of_birth[] = sanitize_text_field( $_POST['year_of_birth'] );\n $date_of_birth[] = sanitize_text_field( $_POST['month_of_birth'] );\n $date_of_birth[] = sanitize_text_field( $_POST['day_of_birth'] );\n\n // Use this fields to show and perform any operations\n // Delete the birth_date if all fields are empty.\n if( empty( $date_of_birth ) && count($date_of_birth) == 0 )\n delete_user_meta( $user_id, 'birth_date' );\n else\n update_user_meta( $user_id, 'birth_date', join('/', $date_of_birth ) ); \n}\n\n</code></pre>\n\n<p>Note: Comments in the code are importants.</p>\n\n<p>Regards,\nBaikare Sandeep.</p>\n" }, { "answer_id": 312615, "author": "Sally CJ", "author_id": 137402, "author_profile": "https://wordpress.stackexchange.com/users/137402", "pm_score": 2, "selected": true, "text": "<blockquote>\n <p>There are \"<strong>month_of_birth</strong>\", \"<strong>day_of_birth</strong>\",\n \"<strong>year_of_birth</strong>\".</p>\n \n <p>How to store them in one meta key ('<strong>birth_date</strong>') ?</p>\n</blockquote>\n\n<p>If you mean to replace all the three meta keys with one single meta key, then you can save the <code>birth_date</code> meta as an <code>array</code>, so that the value would be something like this:</p>\n\n<pre><code>array(\n 'month' =&gt; 'august',\n 'day' =&gt; '27',\n 'year' =&gt; '2018'\n)\n</code></pre>\n\n<p><strong>Here are the steps:</strong></p>\n\n<ol>\n<li><p>In the <code>birthdate_show_extra_profile_fields()</code>, retrieve the\n<code>birth_date</code> meta value like this:</p>\n\n<pre><code>function birthdate_show_extra_profile_fields( $user ) {\n // Get the birth date, which is an array of month, day, and year.\n $birth_date = (array) get_user_meta( $user-&gt;ID, 'birth_date', true );\n ?&gt;\n</code></pre></li>\n<li><p>Then replace the <code>name</code> of the drop-down menus (i.e. <code>select</code>\nfields), and replace the code for retrieving the individual birth\nmonth, day, and year:</p>\n\n<p>For the birth <em>month</em> menu:</p>\n\n<pre><code>&lt;select name=\"month_of_birth\" id=\"month_of_birth\"&gt; &lt;!-- before --&gt;\n&lt;select name=\"birth_date[month]\" id=\"month_of_birth\"&gt; &lt;!-- after --&gt;\n\n$_value = trim( get_user_meta( $user-&gt;ID, 'month_of_birth', true ) ); // before\n$_value = isset( $birth_date['month'] ) ? $birth_date['month'] : ''; // after\n</code></pre>\n\n<p>For the birth <em>day</em> menu:</p>\n\n<pre><code>&lt;select name=\"day_of_birth\" id=\"day_of_birth\"&gt; &lt;!-- before --&gt;\n&lt;select name=\"birth_date[day]\" id=\"day_of_birth\"&gt; &lt;!-- after --&gt;\n\n$_value = trim( get_user_meta( $user-&gt;ID, 'day_of_birth', true ) ); // before\n$_value = isset( $birth_date['day'] ) ? $birth_date['day'] : ''; // after\n</code></pre>\n\n<p>For the birth <em>year</em> menu:</p>\n\n<pre><code>&lt;select name=\"year_of_birth\" id=\"year_of_birth\"&gt; &lt;!-- before --&gt;\n&lt;select name=\"birth_date[year]\" id=\"year_of_birth\"&gt; &lt;!-- after --&gt;\n\n$_value = trim( get_user_meta( $user-&gt;ID, 'year_of_birth', true ) ); // before\n$_value = isset( $birth_date['year'] ) ? $birth_date['year'] : ''; // after\n</code></pre></li>\n<li><p>Then use this for saving the <code>birth_date</code> meta value:</p>\n\n<pre><code>function birthdate_save_extra_user_profile_fields( $user_id ) {\n if ( !current_user_can( 'edit_user', $user_id ) )\n return false;\n\n // Make sure we have a valid POSTed data, and if yes, then\n // sanitize/clean each array item.\n $birth_date = isset( $_POST['birth_date'] ) ?\n array_map( 'sanitize_text_field', $_POST['birth_date'] ) : array();\n\n update_user_meta( $user_id, 'birth_date', $birth_date );\n}\n</code></pre></li>\n</ol>\n\n<h2>UPDATE</h2>\n\n<p>You can retrieve the saved <code>birth_date</code> meta value like this:</p>\n\n<pre><code>// Note that the last/third parameter is TRUE and not FALSE.\n$birth_date = get_user_meta( $user_id, 'birth_date', true );\n\necho $birth_date['month']; // e.g. august\necho $birth_date['day']; // e.g. 27\necho $birth_date['year']; // e.g. 2018\n</code></pre>\n\n<p>If you want the month name to start in uppercase, apply <code>ucfirst()</code> on the month name, like this:</p>\n\n<pre><code>echo ucfirst( $birth_date['month'] ); // e.g. August\n</code></pre>\n\n<p>So your <code>user_birthdate_info_shortcode()</code> could be rewritten into this:</p>\n\n<pre><code>function user_birthdate_info_shortcode() {\n if(is_user_logged_in()) {\n $user_id = get_current_user_id();\n $birth_date = get_user_meta($user_id, 'birth_date', true);\n\n echo ucfirst( $birth_date['month'] ) . '&amp;nbsp;' . // apply ucfirst()\n $birth_date['day'] . '&amp;nbsp;' . $birth_date['year'];\n }\n}\n</code></pre>\n\n<hr>\n\n<p><strong>Alternatively, just save the month <em>name</em> (e.g. <code>August</code>) instead of its slug/key (e.g. <code>august</code>).</strong> So in the <code>birthdate_show_extra_profile_fields()</code> function, change this: (you'd need to re-indent the code)</p>\n\n<pre><code>foreach ( array(\n 'not-selected' =&gt; '',\n 'january' =&gt; 'January',\n 'february' =&gt; 'February',\n 'march' =&gt; 'March',\n 'april' =&gt; 'April',\n 'may' =&gt; 'May',\n 'june' =&gt; 'June',\n 'july' =&gt; 'July',\n 'august' =&gt; 'August',\n 'september' =&gt; 'September',\n 'october' =&gt; 'October',\n 'november' =&gt; 'November',\n 'december' =&gt; 'December',\n) as $value =&gt; $label ) :\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>foreach ( array(\n '',\n 'January', 'February', 'March', 'April', 'May', 'June',\n 'July', 'August', 'September', 'October', 'November', 'December',\n) as $label ) :\n $value = $label; // use the label as the value\n</code></pre>\n\n<p>So your <code>user_birthdate_info_shortcode()</code> could be rewritten into this:</p>\n\n<pre><code>function user_birthdate_info_shortcode() {\n if(is_user_logged_in()) {\n $user_id = get_current_user_id();\n $birth_date = get_user_meta($user_id, 'birth_date', true);\n\n echo $birth_date['month'] . '&amp;nbsp;' . // ucfirst() not necessary\n $birth_date['day'] . '&amp;nbsp;' . $birth_date['year'];\n }\n}\n</code></pre>\n" } ]
2018/08/27
[ "https://wordpress.stackexchange.com/questions/312592", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149236/" ]
I've added some custom fields into the user profile. It's "Date of Birth". There are "**month\_of\_birth**", "**day\_of\_birth**", "**year\_of\_birth**". How to store them in one meta key ('**birth\_date**') ? Here's the code for the custom field : ``` // ADD EXTRA PROFILE FIELD - BIRTH DATE add_action( 'show_user_profile', 'birthdate_show_extra_profile_fields' ); add_action( 'edit_user_profile', 'birthdate_show_extra_profile_fields' ); function birthdate_show_extra_profile_fields( $user ) { ?> <h3 class="birthdate-info">Date of Birth</h3> <table class="form-table"> <tr> <th><label for="birth_date">Date of Birth</label></th> <td width="30%"> <select name="month_of_birth" id="month_of_birth"> <?php $_value = trim( get_user_meta( $user->ID, 'month_of_birth', true ) ); foreach ( array( 'not-selected' => '', 'january' => 'January', 'february' => 'February', 'march' => 'March', 'april' => 'April', 'may' => 'May', 'june' => 'June', 'july' => 'July', 'august' => 'August', 'september' => 'September', 'october' => 'October', 'november' => 'November', 'december' => 'December', ) as $value => $label ) : $selected = selected( $value, $_value, false ); ?> <option value="<?php echo esc_attr( $value ); ?>"<?php echo $selected; ?>><?php echo esc_html( $label ); ?></option> <?php endforeach; ?> </select> </td> <td width="20%"> <select name="day_of_birth" id="day_of_birth"> <?php $_value = trim( get_user_meta( $user->ID, 'day_of_birth', true ) ); foreach ( array( 'not-selected' => '', '1' => '1', '2' => '2', '3' => '3', '4' => '4', '5' => '5', '6' => '6', '7' => '7', '8' => '8', '9' => '9', '10' => '10', '11' => '11', '12' => '12', '13' => '13', '14' => '14', '15' => '15', '16' => '16', '17' => '17', '18' => '18', '19' => '19', '20' => '20', '21' => '21', '22' => '22', '23' => '23', '24' => '24', '25' => '25', '26' => '26', '27' => '27', '28' => '28', '29' => '29', '30' => '30', '31' => '31', ) as $value => $label ) : $selected = selected( $value, $_value, false ); ?> <option value="<?php echo esc_attr( $value ); ?>"<?php echo $selected; ?>><?php echo esc_html( $label ); ?></option> <?php endforeach; ?> </select> </td> <td width="25%"> <select name="year_of_birth" id="year_of_birth"> <?php $_value = trim( get_user_meta( $user->ID, 'year_of_birth', true ) ); foreach ( array( 'not-selected' => '', '1905' => '1905', '1906' => '1906', '1907' => '1907', '1908' => '1908', '1909' => '1909', '1910' => '1910', '1911' => '1911', '1912' => '1912', '1913' => '1913', '1914' => '1914', '1915' => '1915', '1916' => '1916', '1917' => '1917', '1918' => '1918', '1919' => '1919', '1920' => '1920', '1921' => '1921', '1922' => '1922', '1923' => '1923', '1924' => '1924', '1925' => '1925', '1926' => '1926', '1927' => '1927', '1928' => '1928', '1929' => '1929', '1930' => '1930', '1931' => '1931', '1932' => '1932', '1933' => '1933', '1934' => '1934', '1935' => '1935', '1936' => '1936', '1937' => '1937', '1938' => '1938', '1939' => '1939', '1940' => '1940', '1941' => '1941', '1942' => '1942', '1943' => '1943', '1944' => '1944', '1945' => '1945', '1946' => '1946', '1947' => '1947', '1948' => '1948', '1949' => '1949', '1950' => '1950', '1951' => '1951', '1952' => '1952', '1953' => '1953', '1954' => '1954', '1955' => '1955', '1956' => '1956', '1957' => '1957', '1958' => '1958', '1959' => '1959', '1960' => '1960', '1961' => '1961', '1962' => '1962', '1963' => '1963', '1964' => '1964', '1965' => '1965', '1966' => '1966', '1967' => '1967', '1968' => '1968', '1969' => '1969', '1970' => '1970', '1971' => '1971', '1972' => '1972', '1973' => '1973', '1974' => '1974', '1975' => '1975', '1976' => '1976', '1977' => '1977', '1978' => '1978', '1979' => '1979', '1980' => '1980', '1981' => '1981', '1982' => '1982', '1983' => '1983', '1984' => '1984', '1985' => '1985', '1986' => '1986', '1987' => '1987', '1988' => '1988', '1989' => '1989', '1990' => '1990', '1991' => '1991', '1992' => '1992', '1993' => '1993', '1994' => '1994', '1995' => '1995', '1996' => '1996', '1997' => '1997', '1998' => '1998', '1999' => '1999', '2000' => '2000', '2001' => '2001', '2002' => '2002', '2003' => '2003', '2004' => '2004', '2005' => '2005', '2006' => '2006', '2007' => '2007', '2008' => '2008', '2009' => '2009', '2010' => '2010', '2011' => '2011', '2012' => '2012', '2013' => '2013', '2014' => '2014', '2015' => '2015', '2016' => '2016', '2017' => '2017', '2018' => '2018', ) as $value => $label ) : $selected = selected( $value, $_value, false ); ?> <option value="<?php echo esc_attr( $value ); ?>"<?php echo $selected; ?>><?php echo esc_html( $label ); ?></option> <?php endforeach; ?> </select> </td> </tr> </table> ``` ``` // SAVE EXTRA PROFILE FIELD - BIRTH DATE add_action( 'personal_options_update', 'birthdate_save_extra_user_profile_fields' ); add_action( 'edit_user_profile_update', 'birthdate_save_extra_user_profile_fields' ); function birthdate_save_extra_user_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id,'month_of_birth', $_POST['month_of_birth'] ); if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id,'day_of_birth', $_POST['day_of_birth'] ); if ( !current_user_can( 'edit_user', $user_id ) ) return false; update_user_meta( $user_id,'year_of_birth', $_POST['year_of_birth'] ); } ``` **UPDATE 2:** SHORTCODE - ``` function user_birthdate_info_shortcode() { if(is_user_logged_in()) { $user_id = get_current_user_id(); $birth_date = get_user_meta($user_id, 'birth_date', false); foreach($birth_date as $key => $value){ echo $value['month'] . '&nbsp;' . $value['day'] . '&nbsp;' . $value['year']; } }} add_shortcode('currentuser_show_birthdate_info', 'user_birthdate_info_shortcode'); ```
> > There are "**month\_of\_birth**", "**day\_of\_birth**", > "**year\_of\_birth**". > > > How to store them in one meta key ('**birth\_date**') ? > > > If you mean to replace all the three meta keys with one single meta key, then you can save the `birth_date` meta as an `array`, so that the value would be something like this: ``` array( 'month' => 'august', 'day' => '27', 'year' => '2018' ) ``` **Here are the steps:** 1. In the `birthdate_show_extra_profile_fields()`, retrieve the `birth_date` meta value like this: ``` function birthdate_show_extra_profile_fields( $user ) { // Get the birth date, which is an array of month, day, and year. $birth_date = (array) get_user_meta( $user->ID, 'birth_date', true ); ?> ``` 2. Then replace the `name` of the drop-down menus (i.e. `select` fields), and replace the code for retrieving the individual birth month, day, and year: For the birth *month* menu: ``` <select name="month_of_birth" id="month_of_birth"> <!-- before --> <select name="birth_date[month]" id="month_of_birth"> <!-- after --> $_value = trim( get_user_meta( $user->ID, 'month_of_birth', true ) ); // before $_value = isset( $birth_date['month'] ) ? $birth_date['month'] : ''; // after ``` For the birth *day* menu: ``` <select name="day_of_birth" id="day_of_birth"> <!-- before --> <select name="birth_date[day]" id="day_of_birth"> <!-- after --> $_value = trim( get_user_meta( $user->ID, 'day_of_birth', true ) ); // before $_value = isset( $birth_date['day'] ) ? $birth_date['day'] : ''; // after ``` For the birth *year* menu: ``` <select name="year_of_birth" id="year_of_birth"> <!-- before --> <select name="birth_date[year]" id="year_of_birth"> <!-- after --> $_value = trim( get_user_meta( $user->ID, 'year_of_birth', true ) ); // before $_value = isset( $birth_date['year'] ) ? $birth_date['year'] : ''; // after ``` 3. Then use this for saving the `birth_date` meta value: ``` function birthdate_save_extra_user_profile_fields( $user_id ) { if ( !current_user_can( 'edit_user', $user_id ) ) return false; // Make sure we have a valid POSTed data, and if yes, then // sanitize/clean each array item. $birth_date = isset( $_POST['birth_date'] ) ? array_map( 'sanitize_text_field', $_POST['birth_date'] ) : array(); update_user_meta( $user_id, 'birth_date', $birth_date ); } ``` UPDATE ------ You can retrieve the saved `birth_date` meta value like this: ``` // Note that the last/third parameter is TRUE and not FALSE. $birth_date = get_user_meta( $user_id, 'birth_date', true ); echo $birth_date['month']; // e.g. august echo $birth_date['day']; // e.g. 27 echo $birth_date['year']; // e.g. 2018 ``` If you want the month name to start in uppercase, apply `ucfirst()` on the month name, like this: ``` echo ucfirst( $birth_date['month'] ); // e.g. August ``` So your `user_birthdate_info_shortcode()` could be rewritten into this: ``` function user_birthdate_info_shortcode() { if(is_user_logged_in()) { $user_id = get_current_user_id(); $birth_date = get_user_meta($user_id, 'birth_date', true); echo ucfirst( $birth_date['month'] ) . '&nbsp;' . // apply ucfirst() $birth_date['day'] . '&nbsp;' . $birth_date['year']; } } ``` --- **Alternatively, just save the month *name* (e.g. `August`) instead of its slug/key (e.g. `august`).** So in the `birthdate_show_extra_profile_fields()` function, change this: (you'd need to re-indent the code) ``` foreach ( array( 'not-selected' => '', 'january' => 'January', 'february' => 'February', 'march' => 'March', 'april' => 'April', 'may' => 'May', 'june' => 'June', 'july' => 'July', 'august' => 'August', 'september' => 'September', 'october' => 'October', 'november' => 'November', 'december' => 'December', ) as $value => $label ) : ``` to: ``` foreach ( array( '', 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December', ) as $label ) : $value = $label; // use the label as the value ``` So your `user_birthdate_info_shortcode()` could be rewritten into this: ``` function user_birthdate_info_shortcode() { if(is_user_logged_in()) { $user_id = get_current_user_id(); $birth_date = get_user_meta($user_id, 'birth_date', true); echo $birth_date['month'] . '&nbsp;' . // ucfirst() not necessary $birth_date['day'] . '&nbsp;' . $birth_date['year']; } } ```
312,625
<p>I'm trying to output an SVG file in a template, and PHPCS is telling me I need to escape the output. So I tried with KSES and it doesn't seem to want to include the viewbox attribute.</p> <pre><code> $allowed_html = array( 'svg' =&gt; array( 'xmlns' =&gt; array (), 'viewBox' =&gt; true ), 'path' =&gt; array( 'd'=&gt; array(), ), ); wp_kses(file_get_contents( $logo ), $allowed_html ) </code></pre> <p>Any ideas why this doesn't work?</p>
[ { "answer_id": 316943, "author": "mrwweb", "author_id": 9844, "author_profile": "https://wordpress.stackexchange.com/users/9844", "pm_score": 5, "selected": true, "text": "<p>I found your question as I was searching for an answer. I tried experimenting a bit more with <code>wp_kses()</code> (<a href=\"https://developer.wordpress.org/reference/functions/wp_kses/\" rel=\"nofollow noreferrer\">code reference</a>) found that lower-casing <code>viewBox</code> in the arguments seems to fix the issue. You do not have to put the actual attribute on the SVG in lowercase, just in the <code>$allowed_html</code> parameter that you pass to the function.</p>\n<p>Here is an example that you can start with:</p>\n<pre><code>&lt;?php\n$kses_defaults = wp_kses_allowed_html( 'post' );\n\n$svg_args = array(\n 'svg' =&gt; array(\n 'class' =&gt; true,\n 'aria-hidden' =&gt; true,\n 'aria-labelledby' =&gt; true,\n 'role' =&gt; true,\n 'xmlns' =&gt; true,\n 'width' =&gt; true,\n 'height' =&gt; true,\n 'viewbox' =&gt; true // &lt;= Must be lower case!\n ),\n 'g' =&gt; array( 'fill' =&gt; true ),\n 'title' =&gt; array( 'title' =&gt; true ),\n 'path' =&gt; array( \n 'd' =&gt; true, \n 'fill' =&gt; true \n )\n);\n\n$allowed_tags = array_merge( $kses_defaults, $svg_args );\n\necho wp_kses( $rich_text_that_might_include_SVGs, $allowed_tags );\n</code></pre>\n<p>List all SVG elements at the same level regardless of how they are organized in the SVG code itself. Make sure for each SVG element, all attributes are represented. You do not need to indicate the attribute value in the <code>$svg_args</code> array.</p>\n<p>Take for instance this SVG code:</p>\n<pre class=\"lang-html prettyprint-override\"><code>&lt;svg width=&quot;19px&quot; height=&quot;17px&quot; viewBox=&quot;0 0 19 17&quot; version=&quot;1.1&quot; xmlns=&quot;http://www.w3.org/2000/svg&quot; xmlns:xlink=&quot;http://www.w3.org/1999/xlink&quot;&gt;\n &lt;title&gt;View Page&lt;/title&gt;\n &lt;g id=&quot;Page-1&quot; stroke=&quot;none&quot; stroke-width=&quot;1&quot; fill=&quot;none&quot; fill-rule=&quot;evenodd&quot;&gt;\n &lt;g id=&quot;View Page&quot; stroke=&quot;#1892FF&quot; stroke-width=&quot;2&quot;&gt;\n &lt;line x1=&quot;0&quot; y1=&quot;8&quot; x2=&quot;17&quot; y2=&quot;8&quot; id=&quot;Path-3&quot;&gt;&lt;/line&gt;\n &lt;polyline id=&quot;Path-4&quot; points=&quot;9 0.5 17 8 9 15.5&quot;&gt;&lt;/polyline&gt;\n &lt;/g&gt;\n &lt;/g&gt;\n&lt;/svg&gt;\n</code></pre>\n<p>You may think your <code>$svg_args</code> need to be like this:</p>\n<pre class=\"lang-php prettyprint-override\"><code> // Passing this arg to wp_kses() will not display the svg.\n $svg_args = array( \n 'svg' =&gt; array(\n 'title' =&gt; true,\n 'g' =&gt; array(\n 'id' =&gt; true,\n 'stroke' =&gt; true,\n 'stroke-width' =&gt; true,\n 'fill' =&gt; true,\n 'fill-rule' =&gt; true,\n 'g' =&gt; array(\n 'line' =&gt; array ( \n 'id' =&gt; true,\n 'x1' =&gt; true,\n 'y1' =&gt; true,\n 'x2' =&gt; true,\n 'y2' =&gt; true\n ),\n 'polyline' =&gt; array ( \n 'id' =&gt; true,\n 'points' =&gt; true\n )\n )\n )\n )\n );\n</code></pre>\n<p>I want to re-clarify that the correct syntax (for this specific example) is:</p>\n<pre class=\"lang-php prettyprint-override\"><code> $svg_args = array(\n 'svg' =&gt; array(\n 'class' =&gt; true,\n 'aria-hidden' =&gt; true,\n 'aria-labelledby' =&gt; true,\n 'role' =&gt; true,\n 'xmlns' =&gt; true,\n 'width' =&gt; true,\n 'height' =&gt; true,\n 'viewbox' =&gt; true // &lt;= Must be lower case!\n ),\n 'g' =&gt; array( 'fill' =&gt; true ),\n 'title' =&gt; array( 'title' =&gt; true ),\n 'line' =&gt; array ( \n 'id' =&gt; true,\n 'x1' =&gt; true,\n 'y1' =&gt; true,\n 'x2' =&gt; true,\n 'y2' =&gt; true\n ),\n 'polyline' =&gt; array ( \n 'id' =&gt; true,\n 'points' =&gt; true\n ),\n );\n</code></pre>\n<p>The correct syntax: You list every SVG element in your arguments at the the same level. Make sure to replace <code>[]</code> in these examples with the actual array of attributes that make up the element. You can find all the elements you need to allow and their attributes by observing the SVG code itself.</p>\n" }, { "answer_id": 346595, "author": "bennybensen", "author_id": 164031, "author_profile": "https://wordpress.stackexchange.com/users/164031", "pm_score": 2, "selected": false, "text": "<p>great solution @mrwweb </p>\n\n<p>if you want to use this in functions.php</p>\n\n<pre><code>&lt;?php\nfunction get_kses_extended_ruleset() {\n $kses_defaults = wp_kses_allowed_html( 'post' );\n\n $svg_args = array(\n 'svg' =&gt; array(\n 'class' =&gt; true,\n 'aria-hidden' =&gt; true,\n 'aria-labelledby' =&gt; true,\n 'role' =&gt; true,\n 'xmlns' =&gt; true,\n 'width' =&gt; true,\n 'height' =&gt; true,\n 'viewbox' =&gt; true, // &lt;= Must be lower case!\n ),\n 'g' =&gt; array( 'fill' =&gt; true ),\n 'title' =&gt; array( 'title' =&gt; true ),\n 'path' =&gt; array(\n 'd' =&gt; true,\n 'fill' =&gt; true,\n ),\n );\n return array_merge( $kses_defaults, $svg_args );\n}\n</code></pre>\n\n<p>template:</p>\n\n<pre><code>&lt;?php\n\necho wp_kses( $svg_code, get_kses_extended_ruleset() );\n</code></pre>\n" } ]
2018/08/27
[ "https://wordpress.stackexchange.com/questions/312625", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/5302/" ]
I'm trying to output an SVG file in a template, and PHPCS is telling me I need to escape the output. So I tried with KSES and it doesn't seem to want to include the viewbox attribute. ``` $allowed_html = array( 'svg' => array( 'xmlns' => array (), 'viewBox' => true ), 'path' => array( 'd'=> array(), ), ); wp_kses(file_get_contents( $logo ), $allowed_html ) ``` Any ideas why this doesn't work?
I found your question as I was searching for an answer. I tried experimenting a bit more with `wp_kses()` ([code reference](https://developer.wordpress.org/reference/functions/wp_kses/)) found that lower-casing `viewBox` in the arguments seems to fix the issue. You do not have to put the actual attribute on the SVG in lowercase, just in the `$allowed_html` parameter that you pass to the function. Here is an example that you can start with: ``` <?php $kses_defaults = wp_kses_allowed_html( 'post' ); $svg_args = array( 'svg' => array( 'class' => true, 'aria-hidden' => true, 'aria-labelledby' => true, 'role' => true, 'xmlns' => true, 'width' => true, 'height' => true, 'viewbox' => true // <= Must be lower case! ), 'g' => array( 'fill' => true ), 'title' => array( 'title' => true ), 'path' => array( 'd' => true, 'fill' => true ) ); $allowed_tags = array_merge( $kses_defaults, $svg_args ); echo wp_kses( $rich_text_that_might_include_SVGs, $allowed_tags ); ``` List all SVG elements at the same level regardless of how they are organized in the SVG code itself. Make sure for each SVG element, all attributes are represented. You do not need to indicate the attribute value in the `$svg_args` array. Take for instance this SVG code: ```html <svg width="19px" height="17px" viewBox="0 0 19 17" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink"> <title>View Page</title> <g id="Page-1" stroke="none" stroke-width="1" fill="none" fill-rule="evenodd"> <g id="View Page" stroke="#1892FF" stroke-width="2"> <line x1="0" y1="8" x2="17" y2="8" id="Path-3"></line> <polyline id="Path-4" points="9 0.5 17 8 9 15.5"></polyline> </g> </g> </svg> ``` You may think your `$svg_args` need to be like this: ```php // Passing this arg to wp_kses() will not display the svg. $svg_args = array( 'svg' => array( 'title' => true, 'g' => array( 'id' => true, 'stroke' => true, 'stroke-width' => true, 'fill' => true, 'fill-rule' => true, 'g' => array( 'line' => array ( 'id' => true, 'x1' => true, 'y1' => true, 'x2' => true, 'y2' => true ), 'polyline' => array ( 'id' => true, 'points' => true ) ) ) ) ); ``` I want to re-clarify that the correct syntax (for this specific example) is: ```php $svg_args = array( 'svg' => array( 'class' => true, 'aria-hidden' => true, 'aria-labelledby' => true, 'role' => true, 'xmlns' => true, 'width' => true, 'height' => true, 'viewbox' => true // <= Must be lower case! ), 'g' => array( 'fill' => true ), 'title' => array( 'title' => true ), 'line' => array ( 'id' => true, 'x1' => true, 'y1' => true, 'x2' => true, 'y2' => true ), 'polyline' => array ( 'id' => true, 'points' => true ), ); ``` The correct syntax: You list every SVG element in your arguments at the the same level. Make sure to replace `[]` in these examples with the actual array of attributes that make up the element. You can find all the elements you need to allow and their attributes by observing the SVG code itself.
312,629
<p>I have been trying desesperately and in vain to highlight the button I have for "Blog" whenever I am in the the main page (I had created a custom link with my homepage)...it is really driving nuts!</p> <p>The only time I have been able to highlight it was when I used the ".menu-item-has-children", but then it stays highlighted even when I enter other pages or menus (e.g.: "About" or "Archives").</p> <p>Is there any way to solve this using just any CSS command or perhaps a conditional? I must say I am totally a zero with <em>html</em> and would like to avoid to use it (if possible, of course).</p> <p>Many thanks in advance, Andreas</p>
[ { "answer_id": 312631, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 0, "selected": false, "text": "<p>You have to play with this CSS selector. I don't really know what do you mean by highlight, it may be a background in which case:</p>\n\n<pre><code>.home #menu-item-1258, .current-menu-item {\n background: blue;\n}\n</code></pre>\n\n<p>If you want to elaborate, what do you mean by highlight, I can help you in case it's nothing crazy, or you can learn a bit of CSS and play with it.</p>\n\n<p>In case you don't know how to add CSS, <a href=\"https://en.support.wordpress.com/custom-design/editing-css/\" rel=\"nofollow noreferrer\">check this out</a>.</p>\n" }, { "answer_id": 312689, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>Wordpress marks the currently displayed page in the menu with CSS classes <code>.current-menu-item</code>, <code>.current-menu-parent</code>, <code>.current-menu-ancestor</code>. Add the required styles to highlight items using these classes.</p>\n\n<p>Sample Menu:</p>\n\n<pre><code>* Blog\n * First Category\n * Second Category\n* About\n* Contact\n</code></pre>\n\n<p>When you open <strong>blog</strong> page, the corresponding menu item (\"<strong>Blog</strong>\") has a class <code>.current-menu-item</code>. Similarly, when you open a <strong>contact</strong> page, the corresponding menu item will have a class <code>.current-menu-item</code>. </p>\n\n<p>if you go to the page <strong>second category</strong>, the menu item \"<strong>Second Category</strong>\" will have class <code>.current-menu-item</code> and \"<strong>Blog</strong>\" item will have class <code>.current-menu-parent</code>. </p>\n\n<hr>\n\n<h3>UPDATE (Highlight similar to hover)</h3>\n\n<p>To highlight \"<strong>Blog</strong>\" on your site when you are on the home page or one of the categories (\"Music &amp; Party\", \"Travel &amp; Culture\", etc.) add to styles:</p>\n\n<pre><code>.home #menu-item-1258 &gt; a span, \n#menu-main &gt; .current-menu-item &gt; a span, \n#menu-main &gt; .current-menu-parent &gt; a span, \n#menu-main ul .current-menu-item, \n#menu-main ul .current-menu-parent { \n background-color: #37cadd; \n}\n</code></pre>\n" } ]
2018/08/27
[ "https://wordpress.stackexchange.com/questions/312629", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149490/" ]
I have been trying desesperately and in vain to highlight the button I have for "Blog" whenever I am in the the main page (I had created a custom link with my homepage)...it is really driving nuts! The only time I have been able to highlight it was when I used the ".menu-item-has-children", but then it stays highlighted even when I enter other pages or menus (e.g.: "About" or "Archives"). Is there any way to solve this using just any CSS command or perhaps a conditional? I must say I am totally a zero with *html* and would like to avoid to use it (if possible, of course). Many thanks in advance, Andreas
Wordpress marks the currently displayed page in the menu with CSS classes `.current-menu-item`, `.current-menu-parent`, `.current-menu-ancestor`. Add the required styles to highlight items using these classes. Sample Menu: ``` * Blog * First Category * Second Category * About * Contact ``` When you open **blog** page, the corresponding menu item ("**Blog**") has a class `.current-menu-item`. Similarly, when you open a **contact** page, the corresponding menu item will have a class `.current-menu-item`. if you go to the page **second category**, the menu item "**Second Category**" will have class `.current-menu-item` and "**Blog**" item will have class `.current-menu-parent`. --- ### UPDATE (Highlight similar to hover) To highlight "**Blog**" on your site when you are on the home page or one of the categories ("Music & Party", "Travel & Culture", etc.) add to styles: ``` .home #menu-item-1258 > a span, #menu-main > .current-menu-item > a span, #menu-main > .current-menu-parent > a span, #menu-main ul .current-menu-item, #menu-main ul .current-menu-parent { background-color: #37cadd; } ```
312,630
<p>In my <code>home.php</code> file I have only this code:</p> <pre><code>&lt;?php global $post; print_r($post-&gt;ID); die(); ?&gt; </code></pre> <p>This is printing the ID of the latest blog post, but what I want is to get the ID of the current page (the page I set as the Posts Page in Settings). It seems that I am already in "The Loop". How can I get the global <code>$post</code> object for the current page rather than the first post in the loop?</p>
[ { "answer_id": 312631, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 0, "selected": false, "text": "<p>You have to play with this CSS selector. I don't really know what do you mean by highlight, it may be a background in which case:</p>\n\n<pre><code>.home #menu-item-1258, .current-menu-item {\n background: blue;\n}\n</code></pre>\n\n<p>If you want to elaborate, what do you mean by highlight, I can help you in case it's nothing crazy, or you can learn a bit of CSS and play with it.</p>\n\n<p>In case you don't know how to add CSS, <a href=\"https://en.support.wordpress.com/custom-design/editing-css/\" rel=\"nofollow noreferrer\">check this out</a>.</p>\n" }, { "answer_id": 312689, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 2, "selected": true, "text": "<p>Wordpress marks the currently displayed page in the menu with CSS classes <code>.current-menu-item</code>, <code>.current-menu-parent</code>, <code>.current-menu-ancestor</code>. Add the required styles to highlight items using these classes.</p>\n\n<p>Sample Menu:</p>\n\n<pre><code>* Blog\n * First Category\n * Second Category\n* About\n* Contact\n</code></pre>\n\n<p>When you open <strong>blog</strong> page, the corresponding menu item (\"<strong>Blog</strong>\") has a class <code>.current-menu-item</code>. Similarly, when you open a <strong>contact</strong> page, the corresponding menu item will have a class <code>.current-menu-item</code>. </p>\n\n<p>if you go to the page <strong>second category</strong>, the menu item \"<strong>Second Category</strong>\" will have class <code>.current-menu-item</code> and \"<strong>Blog</strong>\" item will have class <code>.current-menu-parent</code>. </p>\n\n<hr>\n\n<h3>UPDATE (Highlight similar to hover)</h3>\n\n<p>To highlight \"<strong>Blog</strong>\" on your site when you are on the home page or one of the categories (\"Music &amp; Party\", \"Travel &amp; Culture\", etc.) add to styles:</p>\n\n<pre><code>.home #menu-item-1258 &gt; a span, \n#menu-main &gt; .current-menu-item &gt; a span, \n#menu-main &gt; .current-menu-parent &gt; a span, \n#menu-main ul .current-menu-item, \n#menu-main ul .current-menu-parent { \n background-color: #37cadd; \n}\n</code></pre>\n" } ]
2018/08/27
[ "https://wordpress.stackexchange.com/questions/312630", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/63238/" ]
In my `home.php` file I have only this code: ``` <?php global $post; print_r($post->ID); die(); ?> ``` This is printing the ID of the latest blog post, but what I want is to get the ID of the current page (the page I set as the Posts Page in Settings). It seems that I am already in "The Loop". How can I get the global `$post` object for the current page rather than the first post in the loop?
Wordpress marks the currently displayed page in the menu with CSS classes `.current-menu-item`, `.current-menu-parent`, `.current-menu-ancestor`. Add the required styles to highlight items using these classes. Sample Menu: ``` * Blog * First Category * Second Category * About * Contact ``` When you open **blog** page, the corresponding menu item ("**Blog**") has a class `.current-menu-item`. Similarly, when you open a **contact** page, the corresponding menu item will have a class `.current-menu-item`. if you go to the page **second category**, the menu item "**Second Category**" will have class `.current-menu-item` and "**Blog**" item will have class `.current-menu-parent`. --- ### UPDATE (Highlight similar to hover) To highlight "**Blog**" on your site when you are on the home page or one of the categories ("Music & Party", "Travel & Culture", etc.) add to styles: ``` .home #menu-item-1258 > a span, #menu-main > .current-menu-item > a span, #menu-main > .current-menu-parent > a span, #menu-main ul .current-menu-item, #menu-main ul .current-menu-parent { background-color: #37cadd; } ```
312,653
<p>I applied a filter to remove all theme styles, but I want this to happen only if the url ends with <b>/amp/</b>.</p> <p>The code below is removing the .css styles on all pages, not filtering the term <b>/amp/</b> of the permalink.</p> <p>I am using the <a href="https://wordpress.org/plugins/amp/" rel="nofollow noreferrer" title="AMP for Wordpress">AMP for Wordpress</a> plugin, which adds <b>/amp/</b> at the end of the URL. Examplo: mysite.com/category/post-slug/amp/</p> <pre><code>function remove_all_theme_styles() { if ( get_permalink($post-&gt;ID) . '/amp/' ) { global $wp_styles; $wp_styles-&gt;queue = array(); } } add_action('wp_print_styles', 'remove_all_theme_styles', 100); </code></pre> <p>They said to add, but neither is working.</p> <pre><code>function remove_all_theme_styles() { if ( $_SERVER['REQUEST_URI'] == get_permalink($post-&gt;ID) . '/amp/' ) { </code></pre>
[ { "answer_id": 312667, "author": "Nathan Kinkead", "author_id": 148750, "author_profile": "https://wordpress.stackexchange.com/users/148750", "pm_score": 1, "selected": false, "text": "<p>In your example, <code>$_SERVER['REQUEST_URI']</code> would return <code>/category/post-slug/amp/</code> which is not the same as <code>get_permalink($post-&gt;ID)</code> which would return <code>https://example.com/category/post-slug/</code></p>\n\n<p>There are lots of ways to go about this, but one easy one that comes to mind is...</p>\n\n<p><code>if ( strpos($_SERVER['REQUEST_URI'], '/amp/' ) !== false ) {</code></p>\n\n<p>The <code>strpos()</code> PHP function finds the position of 2nd string within the 1st string, and returns false if it's not found.</p>\n\n<p>So, that essentially searches the Request URI for the existence of '/amp/' and if it's found, then it proceeds with the rest of our function.</p>\n" }, { "answer_id": 312678, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>Add this function somewhere (Rename to something you wish) </p>\n\n<pre><code>function force_relative_url ($url) {\n return preg_replace ('/^(http)?s?:?\\/\\/[^\\/]*(\\/?.*)$/i', '$2', '' . $url);\n}\n</code></pre>\n\n<p>Now you can:</p>\n\n<pre><code>if ( $_SERVER['REQUEST_URI'] == force_relative_url( get_permalink( $post-&gt;ID ) ) . '/amp/' ) {\n</code></pre>\n" }, { "answer_id": 318519, "author": "DrLightman", "author_id": 4053, "author_profile": "https://wordpress.stackexchange.com/users/4053", "pm_score": 0, "selected": false, "text": "<p>Based on the plugin you're using, take a look at its <code>is_amp_endpoint()</code> function.</p>\n\n<p>You may perform the test this way in another plugin on your theme's functions.php:</p>\n\n<pre><code>if( function_exists('is_amp_endpoint') &amp;&amp; is_amp_endpoint() ) {\n // ... do stuff in AMP\n}\n</code></pre>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312653", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/12990/" ]
I applied a filter to remove all theme styles, but I want this to happen only if the url ends with **/amp/**. The code below is removing the .css styles on all pages, not filtering the term **/amp/** of the permalink. I am using the [AMP for Wordpress](https://wordpress.org/plugins/amp/ "AMP for Wordpress") plugin, which adds **/amp/** at the end of the URL. Examplo: mysite.com/category/post-slug/amp/ ``` function remove_all_theme_styles() { if ( get_permalink($post->ID) . '/amp/' ) { global $wp_styles; $wp_styles->queue = array(); } } add_action('wp_print_styles', 'remove_all_theme_styles', 100); ``` They said to add, but neither is working. ``` function remove_all_theme_styles() { if ( $_SERVER['REQUEST_URI'] == get_permalink($post->ID) . '/amp/' ) { ```
In your example, `$_SERVER['REQUEST_URI']` would return `/category/post-slug/amp/` which is not the same as `get_permalink($post->ID)` which would return `https://example.com/category/post-slug/` There are lots of ways to go about this, but one easy one that comes to mind is... `if ( strpos($_SERVER['REQUEST_URI'], '/amp/' ) !== false ) {` The `strpos()` PHP function finds the position of 2nd string within the 1st string, and returns false if it's not found. So, that essentially searches the Request URI for the existence of '/amp/' and if it's found, then it proceeds with the rest of our function.
312,660
<p>I installed the Gutenberg plugin today to try it out.</p> <p>I’m getting an error message both at the top of my WP dashboard, and when I go to view the site in a browser:</p> <blockquote> <p>Warning: call_user_func_array() expects parameter 1 to be a valid callback, function ‘ikreativ_tinymce_fix’ not found or invalid function name in /home1/asharp/public_html/andreasharp.com/wp-includes/class-wp-hook.php on line 288</p> </blockquote> <p>A few days ago, I got so sick of years of WP stripping out my tags when I go back to Code-View after switching to Visual — that I finally decided to find a way to solve that problem. I found somebody’s solution <a href="https://ikreativ.com/stop-wordpress-removing-html/" rel="nofollow noreferrer">https://ikreativ.com/stop-wordpress-removing-html/</a></p> <p>It didn’t work, so I deleted the file that I made with this suggestion’s code, and put my backed-up, unchanged functions.php file back where it was before I fiddled with this.</p> <p>The warning message seems to indicate that the class-wp-hook.php file was changed by the code from the ikreativ site that I put into the functions.php file. As mentioned above, I did replace the ikreativ code with the backed-up, unchanged functions.php file.</p> <p>I searched for ikreativ_tinymce_fix in my WP files, but it doesn't search file contents, so that didn't help. I looked for </p> <p>I looked at line 288 in wp-includes/class-wp-hook.php. It is blank. </p> <p>I’ll paste the whole section below a line of *** below.</p> <p>The first line is line 286.</p> <p>The indents don’t carry over the copy/paste step, so it might be hard to see that the entirety of line 287 is</p> <pre><code>$this-&gt;current_priority[ $nesting_level ] = $priority = current( $this-&gt;iterations[ $nesting_level ] ); </code></pre> <p>Then a blank line for 288.</p> <pre><code>And line 289 is foreach ( $this-&gt;callbacks[ $priority ] as $the_ ) { ******************************************************************** do { $this-&gt;current_priority[ $nesting_level ] = $priority = current( $this-&gt;iterations[ $nesting_level ] ); foreach ( $this-&gt;callbacks[ $priority ] as $the_ ) { if( ! $this-&gt;doing_action ) { $args[ 0 ] = $value; } // Avoid the array_slice if possible. if ( $the_[‘accepted_args’] == 0 ) { $value = call_user_func_array( $the_[‘function’], array() ); } elseif ( $the_[‘accepted_args’] &gt;= $num_args ) { $value = call_user_func_array( $the_[‘function’], $args ); } else { $value = call_user_func_array( $the_[‘function’], array_slice( $args, 0, (int)$the_[‘accepted_args’] ) ); } } } while ( false !== next( $this-&gt;iterations[ $nesting_level ] ) ); </code></pre> <p>I don't know what to do to fix line 288 of the class-wp-hook.php file. </p> <p>Hoping someone can send what needs to be there, and that I can just paste it in and save, and that it’ll fix the whole problem.</p> <p>What should line 288 say?</p> <p>Actually, how can I fix this?</p>
[ { "answer_id": 312667, "author": "Nathan Kinkead", "author_id": 148750, "author_profile": "https://wordpress.stackexchange.com/users/148750", "pm_score": 1, "selected": false, "text": "<p>In your example, <code>$_SERVER['REQUEST_URI']</code> would return <code>/category/post-slug/amp/</code> which is not the same as <code>get_permalink($post-&gt;ID)</code> which would return <code>https://example.com/category/post-slug/</code></p>\n\n<p>There are lots of ways to go about this, but one easy one that comes to mind is...</p>\n\n<p><code>if ( strpos($_SERVER['REQUEST_URI'], '/amp/' ) !== false ) {</code></p>\n\n<p>The <code>strpos()</code> PHP function finds the position of 2nd string within the 1st string, and returns false if it's not found.</p>\n\n<p>So, that essentially searches the Request URI for the existence of '/amp/' and if it's found, then it proceeds with the rest of our function.</p>\n" }, { "answer_id": 312678, "author": "De Coder", "author_id": 144159, "author_profile": "https://wordpress.stackexchange.com/users/144159", "pm_score": 0, "selected": false, "text": "<p>Add this function somewhere (Rename to something you wish) </p>\n\n<pre><code>function force_relative_url ($url) {\n return preg_replace ('/^(http)?s?:?\\/\\/[^\\/]*(\\/?.*)$/i', '$2', '' . $url);\n}\n</code></pre>\n\n<p>Now you can:</p>\n\n<pre><code>if ( $_SERVER['REQUEST_URI'] == force_relative_url( get_permalink( $post-&gt;ID ) ) . '/amp/' ) {\n</code></pre>\n" }, { "answer_id": 318519, "author": "DrLightman", "author_id": 4053, "author_profile": "https://wordpress.stackexchange.com/users/4053", "pm_score": 0, "selected": false, "text": "<p>Based on the plugin you're using, take a look at its <code>is_amp_endpoint()</code> function.</p>\n\n<p>You may perform the test this way in another plugin on your theme's functions.php:</p>\n\n<pre><code>if( function_exists('is_amp_endpoint') &amp;&amp; is_amp_endpoint() ) {\n // ... do stuff in AMP\n}\n</code></pre>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312660", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149513/" ]
I installed the Gutenberg plugin today to try it out. I’m getting an error message both at the top of my WP dashboard, and when I go to view the site in a browser: > > Warning: call\_user\_func\_array() expects parameter 1 to be a valid callback, function ‘ikreativ\_tinymce\_fix’ not found or invalid function name in /home1/asharp/public\_html/andreasharp.com/wp-includes/class-wp-hook.php on line 288 > > > A few days ago, I got so sick of years of WP stripping out my tags when I go back to Code-View after switching to Visual — that I finally decided to find a way to solve that problem. I found somebody’s solution <https://ikreativ.com/stop-wordpress-removing-html/> It didn’t work, so I deleted the file that I made with this suggestion’s code, and put my backed-up, unchanged functions.php file back where it was before I fiddled with this. The warning message seems to indicate that the class-wp-hook.php file was changed by the code from the ikreativ site that I put into the functions.php file. As mentioned above, I did replace the ikreativ code with the backed-up, unchanged functions.php file. I searched for ikreativ\_tinymce\_fix in my WP files, but it doesn't search file contents, so that didn't help. I looked for I looked at line 288 in wp-includes/class-wp-hook.php. It is blank. I’ll paste the whole section below a line of \*\*\* below. The first line is line 286. The indents don’t carry over the copy/paste step, so it might be hard to see that the entirety of line 287 is ``` $this->current_priority[ $nesting_level ] = $priority = current( $this->iterations[ $nesting_level ] ); ``` Then a blank line for 288. ``` And line 289 is foreach ( $this->callbacks[ $priority ] as $the_ ) { ******************************************************************** do { $this->current_priority[ $nesting_level ] = $priority = current( $this->iterations[ $nesting_level ] ); foreach ( $this->callbacks[ $priority ] as $the_ ) { if( ! $this->doing_action ) { $args[ 0 ] = $value; } // Avoid the array_slice if possible. if ( $the_[‘accepted_args’] == 0 ) { $value = call_user_func_array( $the_[‘function’], array() ); } elseif ( $the_[‘accepted_args’] >= $num_args ) { $value = call_user_func_array( $the_[‘function’], $args ); } else { $value = call_user_func_array( $the_[‘function’], array_slice( $args, 0, (int)$the_[‘accepted_args’] ) ); } } } while ( false !== next( $this->iterations[ $nesting_level ] ) ); ``` I don't know what to do to fix line 288 of the class-wp-hook.php file. Hoping someone can send what needs to be there, and that I can just paste it in and save, and that it’ll fix the whole problem. What should line 288 say? Actually, how can I fix this?
In your example, `$_SERVER['REQUEST_URI']` would return `/category/post-slug/amp/` which is not the same as `get_permalink($post->ID)` which would return `https://example.com/category/post-slug/` There are lots of ways to go about this, but one easy one that comes to mind is... `if ( strpos($_SERVER['REQUEST_URI'], '/amp/' ) !== false ) {` The `strpos()` PHP function finds the position of 2nd string within the 1st string, and returns false if it's not found. So, that essentially searches the Request URI for the existence of '/amp/' and if it's found, then it proceeds with the rest of our function.
312,670
<h2>The Issue With Customise:</h2> <p>Wouldn't it be nice if WordPress made the <strong>Customise</strong> area shown in the below image resizable?</p> <p>As it is at the moment, it can be a little tricky working in a squashed sidebar.</p> <p>Because of this I usually do all my CSS in an external editor then copy it into the sidebar area.</p> <h2>It's Under Discussion at WordPress</h2> <p>The WordPress devs were looking at improving the Customizer UI, which you can see <a href="https://core.trac.wordpress.org/ticket/38707" rel="nofollow noreferrer">here</a>. This would solve the issue, but until then...</p> <h2>This Question is Not About CSS</h2> <p>This question isn't about why I've used the Customizer for CSS - I have my reasons - That's another topic altogether.</p> <hr> <h2>The Question:</h2> <p>What is the best way of customising this WordPress area to make it expandable or wider without the need for a plugin? This would make it easier to work with all customizations, not just CSS.</p> <blockquote> <p>*This change must be part of the <strong>child theme</strong> to prevent being overwritten by updates.</p> </blockquote> <hr> <p><a href="https://i.stack.imgur.com/Yi7Bc.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Yi7Bc.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/iq3Z8.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/iq3Z8.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 312676, "author": "Eh Jewel", "author_id": 75264, "author_profile": "https://wordpress.stackexchange.com/users/75264", "pm_score": 3, "selected": true, "text": "<p>You can expand the WordPress customize area without plugins by applying a simple line of CSS.</p>\n\n<pre><code>.wp-full-overlay-sidebar {\n width: 30% !important; /* The width of the customize area */\n}\n.wp-full-overlay.expanded {\n margin-left: 30%; /* Here would be the width as same as the customize window width you set */\n}\n</code></pre>\n\n<p>Hook the CSS to <code>admin_enqueue_scripts()</code> function to load it in the WordPress customize area.\nThe CSS file enqueueing example is given below-</p>\n\n<pre><code>add_action('admin_enqueue_scripts', function() {\n wp_enqueue_style('your-prefix-admin', get_template_directory_uri().'/assets/css/admin.css');\n});\n</code></pre>\n\n<p>Note: This code should put into your theme's <code>functions.php</code> file. You should create a file named <code>admin.css</code> in the assets/css directory (create the directory if it doesn't exist) in your theme. </p>\n\n<p>For child theme, you should the <code>get_stylesheet_directory_uri()</code> function instead of the <code>get_template_directory_uri()</code> function.</p>\n" }, { "answer_id": 312680, "author": "Mark Kaplun", "author_id": 23970, "author_profile": "https://wordpress.stackexchange.com/users/23970", "pm_score": 0, "selected": false, "text": "<p>I would say that it is generally unwise to do major CSS changes via the customizer. In addition to the limited space it is hard to locate specific CSS rule you might need to modify and you have no history of when and why you have made the change in the first place.</p>\n\n<p>You should add CSS rules in your theme, which whether it is a main or a child theme should be under GIT.</p>\n\n<p>Yes, it will take slightly more time working like that, but you will recover all of your investment the first time you will need to understand why you have a specific rule.</p>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312670", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148986/" ]
The Issue With Customise: ------------------------- Wouldn't it be nice if WordPress made the **Customise** area shown in the below image resizable? As it is at the moment, it can be a little tricky working in a squashed sidebar. Because of this I usually do all my CSS in an external editor then copy it into the sidebar area. It's Under Discussion at WordPress ---------------------------------- The WordPress devs were looking at improving the Customizer UI, which you can see [here](https://core.trac.wordpress.org/ticket/38707). This would solve the issue, but until then... This Question is Not About CSS ------------------------------ This question isn't about why I've used the Customizer for CSS - I have my reasons - That's another topic altogether. --- The Question: ------------- What is the best way of customising this WordPress area to make it expandable or wider without the need for a plugin? This would make it easier to work with all customizations, not just CSS. > > \*This change must be part of the **child theme** to prevent being overwritten by updates. > > > --- [![enter image description here](https://i.stack.imgur.com/Yi7Bc.jpg)](https://i.stack.imgur.com/Yi7Bc.jpg) [![enter image description here](https://i.stack.imgur.com/iq3Z8.jpg)](https://i.stack.imgur.com/iq3Z8.jpg)
You can expand the WordPress customize area without plugins by applying a simple line of CSS. ``` .wp-full-overlay-sidebar { width: 30% !important; /* The width of the customize area */ } .wp-full-overlay.expanded { margin-left: 30%; /* Here would be the width as same as the customize window width you set */ } ``` Hook the CSS to `admin_enqueue_scripts()` function to load it in the WordPress customize area. The CSS file enqueueing example is given below- ``` add_action('admin_enqueue_scripts', function() { wp_enqueue_style('your-prefix-admin', get_template_directory_uri().'/assets/css/admin.css'); }); ``` Note: This code should put into your theme's `functions.php` file. You should create a file named `admin.css` in the assets/css directory (create the directory if it doesn't exist) in your theme. For child theme, you should the `get_stylesheet_directory_uri()` function instead of the `get_template_directory_uri()` function.
312,694
<p>i found many questions like this but nothing matching to my requirement.Here i need to lock a specific page named settings,not to be deleted by other admins.But it should able to edit. Is there any way to lock a specific page.</p>
[ { "answer_id": 312768, "author": "Adarsh", "author_id": 143452, "author_profile": "https://wordpress.stackexchange.com/users/143452", "pm_score": 0, "selected": false, "text": "<p>found the solution</p>\n\n<pre><code>function restrict_page_deletion($post_ID)\n{\n $restricted_pageId = 177;\n\n if(($post_ID == $restricted_pageId))\n {\n echo \"You are not authorized to delete this page.\";\n exit;\n }\n}\nadd_action('wp_trash_post', 'restrict_page_deletion', 10, 1);\n</code></pre>\n" }, { "answer_id": 312810, "author": "Jacob Peattie", "author_id": 39152, "author_profile": "https://wordpress.stackexchange.com/users/39152", "pm_score": 2, "selected": true, "text": "<p>Preventing the trash post action is a crude way of approaching it. You have to kill the application and display an ugly error message, and the UI for deleting the post will still be there.</p>\n\n<p>Instead I suggest using the <code>map_meta_cap</code> filter. This will allow you to change a user's <a href=\"https://developer.wordpress.org/plugins/users/roles-and-capabilities/\" rel=\"nofollow noreferrer\">capabilities</a> for a single post.</p>\n\n<p>Normally when WordPress checks if a user can delete a post it checks \"can the user <code>delete_post</code> for this post?\". The way it figures this out is with the <code>map_meta_cap</code> function. </p>\n\n<p>This function decides which capabilities <code>delete_post</code> maps to. For example, if the user created the post then the function maps <code>delete_post</code> to <code>delete_posts</code>. So if the user has the <code>delete_posts</code> capability then they can delete the post. If the user did <em>not</em> create the post, then the function maps <code>delete_post</code> to <code>delete_others_posts</code>.</p>\n\n<p>The <code>map_meta_cap</code> filter allows us change this mapping. So we'll use it to map <code>delete_post</code> to <code>do_not_allow</code> for this specific post. Then no users will be able to delete that post.</p>\n\n<p>This is the function for doing this:</p>\n\n<pre><code>function wpse_312694_restrict_page_deletion( $caps, $cap, $user_id, $args ) {\n $post_id = $args[0];\n\n if ( $cap === 'delete_post' &amp;&amp; $post_id === 117 ) {\n $caps[] = 'do_not_allow';\n }\n\n return $caps;\n}\nadd_filter( 'map_meta_cap', 'wpse_312694_restrict_page_deletion', 10, 4 );\n</code></pre>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312694", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/143452/" ]
i found many questions like this but nothing matching to my requirement.Here i need to lock a specific page named settings,not to be deleted by other admins.But it should able to edit. Is there any way to lock a specific page.
Preventing the trash post action is a crude way of approaching it. You have to kill the application and display an ugly error message, and the UI for deleting the post will still be there. Instead I suggest using the `map_meta_cap` filter. This will allow you to change a user's [capabilities](https://developer.wordpress.org/plugins/users/roles-and-capabilities/) for a single post. Normally when WordPress checks if a user can delete a post it checks "can the user `delete_post` for this post?". The way it figures this out is with the `map_meta_cap` function. This function decides which capabilities `delete_post` maps to. For example, if the user created the post then the function maps `delete_post` to `delete_posts`. So if the user has the `delete_posts` capability then they can delete the post. If the user did *not* create the post, then the function maps `delete_post` to `delete_others_posts`. The `map_meta_cap` filter allows us change this mapping. So we'll use it to map `delete_post` to `do_not_allow` for this specific post. Then no users will be able to delete that post. This is the function for doing this: ``` function wpse_312694_restrict_page_deletion( $caps, $cap, $user_id, $args ) { $post_id = $args[0]; if ( $cap === 'delete_post' && $post_id === 117 ) { $caps[] = 'do_not_allow'; } return $caps; } add_filter( 'map_meta_cap', 'wpse_312694_restrict_page_deletion', 10, 4 ); ```
312,706
<p>i have a multiple meta (custom field) in posts as "cd_meta" that it (cd_meta) have a meta as "artist", also "artist" meta maybe have one or more value in array</p> <p>i want to getting posts that "artist" meta have specific value and number of them</p> <p>look below picture for more info <a href="https://i.stack.imgur.com/HHSt6.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HHSt6.jpg" alt="enter image description here"></a></p>
[ { "answer_id": 312708, "author": "Dharmishtha Patel", "author_id": 135085, "author_profile": "https://wordpress.stackexchange.com/users/135085", "pm_score": 0, "selected": false, "text": "<p>Please change your SQL Query </p>\n\n<pre><code>$args = array(\n 'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'cp_annonceur',\n 'value' =&gt; 'professionnel',\n 'compare' =&gt; '=',\n )\n )\n);\n$query = new WP_Query($args);\n</code></pre>\n" }, { "answer_id": 312769, "author": "nmr", "author_id": 147428, "author_profile": "https://wordpress.stackexchange.com/users/147428", "pm_score": 1, "selected": false, "text": "<p>When you store an array as <code>meta_value</code> you are storing a string with serialized data that represents the original array. This format is appropriated for data that are <strong>only</strong> intended to display. </p>\n\n<p>Data that you plan to use for ordering or searching by or in any other way that is not just display the information should <strong>NOT</strong> be stored as serialized array. You should store each array key in its own meta field.</p>\n\n<p>In you example you want to search post by <code>artist</code> meta field, so think about the change from array <code>artist[1599, 5240]</code> to two single value meta fields (all with \"<strong>artist</strong>\" as <code>meta_key</code>, you can store a key more than once):</p>\n\n<blockquote>\n <p>[artist] => '1599'<br>\n [artist] => '5240'</p>\n</blockquote>\n\n<hr>\n\n<h3>Update</h3>\n\n<blockquote>\n <p>it's serialized and must search in serialized, how do it ?</p>\n</blockquote>\n\n<p>It is technically possible to search text with the LIKE operator and surrounding value with <code>\"</code>, but it's inefficient query. You have no guarantee of the results consistent, because searched value can appear in other array key (e.g. <code>rev</code>, <code>master</code>, etc.). Storing <code>artist</code> as separate meta fields is a preferable solution.</p>\n\n<pre><code>'meta_query' =&gt; array(\n array(\n 'key' =&gt; 'cp_meta',\n 'value' =&gt; '\"1599\"', // OR ':\"1599\"'\n 'compare' =&gt; 'LIKE',\n),\n</code></pre>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312706", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/141766/" ]
i have a multiple meta (custom field) in posts as "cd\_meta" that it (cd\_meta) have a meta as "artist", also "artist" meta maybe have one or more value in array i want to getting posts that "artist" meta have specific value and number of them look below picture for more info [![enter image description here](https://i.stack.imgur.com/HHSt6.jpg)](https://i.stack.imgur.com/HHSt6.jpg)
When you store an array as `meta_value` you are storing a string with serialized data that represents the original array. This format is appropriated for data that are **only** intended to display. Data that you plan to use for ordering or searching by or in any other way that is not just display the information should **NOT** be stored as serialized array. You should store each array key in its own meta field. In you example you want to search post by `artist` meta field, so think about the change from array `artist[1599, 5240]` to two single value meta fields (all with "**artist**" as `meta_key`, you can store a key more than once): > > [artist] => '1599' > > [artist] => '5240' > > > --- ### Update > > it's serialized and must search in serialized, how do it ? > > > It is technically possible to search text with the LIKE operator and surrounding value with `"`, but it's inefficient query. You have no guarantee of the results consistent, because searched value can appear in other array key (e.g. `rev`, `master`, etc.). Storing `artist` as separate meta fields is a preferable solution. ``` 'meta_query' => array( array( 'key' => 'cp_meta', 'value' => '"1599"', // OR ':"1599"' 'compare' => 'LIKE', ), ```
312,716
<p>I need a query to show all posts in the site but not repeat the ones with same tag, I mean only show one post with the same tag.</p> <p>My current query is</p> <pre><code> &lt;?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' =&gt; array('post'), 'posts_per_page' =&gt; 30, 'paged' =&gt; $paged, 'order' =&gt; 'ASC', 'orderby' =&gt; 'name' ); query_posts($args); ?&gt; </code></pre> <p>How can I show only post with the same tag?</p> <p>Thanks!</p>
[ { "answer_id": 312717, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>You can try something like this:</p>\n\n<pre><code>&lt;?php\n\n$tags_array = get_tags();\n$news_query = new WP_Query;\n\nforeach ( $tags_array as $tags ) :\n $news_query-&gt;query( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n\n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while ( $news_query-&gt;have_posts() ) : $news_query-&gt;the_post() ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n" }, { "answer_id": 312756, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": -1, "selected": false, "text": "<p>I think @Castiblanco has the right answer, with maybe a little tweaking? His solution should certainly work, but I would do it just a tiny bit differently, like this:</p>\n\n<pre><code> &lt;?php\n\n $tags_array = get_tags();\n\n foreach ( $tags_array as $tags ) :\n $args( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n query_posts($args);\n if (have_posts()) : \n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while (have_posts()) : the_post(); ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n\n<p>The reason I'd do it this way is just to simplify the query and create a new object rather than using ->query also as previously noted be sure to reset postdata and if there are other loops on the page be sure to reset the query using wp_reset_query() after your endwhile.</p>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312716", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149480/" ]
I need a query to show all posts in the site but not repeat the ones with same tag, I mean only show one post with the same tag. My current query is ``` <?php $paged = (get_query_var('paged')) ? get_query_var('paged') : 1; $args = array( 'post_type' => array('post'), 'posts_per_page' => 30, 'paged' => $paged, 'order' => 'ASC', 'orderby' => 'name' ); query_posts($args); ?> ``` How can I show only post with the same tag? Thanks!
You can try something like this: ``` <?php $tags_array = get_tags(); $news_query = new WP_Query; foreach ( $tags_array as $tags ) : $news_query->query( array( 'cat' => $tags->term_id, 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, )); ?> <h2><?php echo esc_html( $tags->name ) ?></h2> <?php while ( $news_query->have_posts() ) : $news_query->the_post() ?> <div class="post"> <?php the_title() ?> <!-- do whatever you else you want that you can do in a normal loop --> </div> <?php endwhile ?> <?php endforeach ?> ```
312,732
<p>I have an external html form that I would like to add to my wordpress developed site. </p> <p>The form links to other areas in the business like the cashiers, so when customers fill the form out, the content is added to their system. </p> <p>I have seen different ways such as adding raw html and adding as media however these do not allow me to edit the form as the visual composer stops working after I paste in the html code. </p> <p>What other options do I have if any. </p>
[ { "answer_id": 312717, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>You can try something like this:</p>\n\n<pre><code>&lt;?php\n\n$tags_array = get_tags();\n$news_query = new WP_Query;\n\nforeach ( $tags_array as $tags ) :\n $news_query-&gt;query( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n\n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while ( $news_query-&gt;have_posts() ) : $news_query-&gt;the_post() ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n" }, { "answer_id": 312756, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": -1, "selected": false, "text": "<p>I think @Castiblanco has the right answer, with maybe a little tweaking? His solution should certainly work, but I would do it just a tiny bit differently, like this:</p>\n\n<pre><code> &lt;?php\n\n $tags_array = get_tags();\n\n foreach ( $tags_array as $tags ) :\n $args( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n query_posts($args);\n if (have_posts()) : \n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while (have_posts()) : the_post(); ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n\n<p>The reason I'd do it this way is just to simplify the query and create a new object rather than using ->query also as previously noted be sure to reset postdata and if there are other loops on the page be sure to reset the query using wp_reset_query() after your endwhile.</p>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312732", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149547/" ]
I have an external html form that I would like to add to my wordpress developed site. The form links to other areas in the business like the cashiers, so when customers fill the form out, the content is added to their system. I have seen different ways such as adding raw html and adding as media however these do not allow me to edit the form as the visual composer stops working after I paste in the html code. What other options do I have if any.
You can try something like this: ``` <?php $tags_array = get_tags(); $news_query = new WP_Query; foreach ( $tags_array as $tags ) : $news_query->query( array( 'cat' => $tags->term_id, 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, )); ?> <h2><?php echo esc_html( $tags->name ) ?></h2> <?php while ( $news_query->have_posts() ) : $news_query->the_post() ?> <div class="post"> <?php the_title() ?> <!-- do whatever you else you want that you can do in a normal loop --> </div> <?php endwhile ?> <?php endforeach ?> ```
312,736
<p>I'm trying to remove the distraction free mode button from the editor, but i can't make it disapear.</p> <p>Here is the code im using:</p> <pre><code> add_filter( 'wp_editor_settings', function($settings) { $settings['teeny']=true; $settings['media_buttons']=false; $settings['quicktags'] = false; $settings['dfw'] = false; return $settings; }); </code></pre> <p>Is there something i'm missing? Because this works on the regular editor.</p> <p>Thanks!</p>
[ { "answer_id": 312717, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>You can try something like this:</p>\n\n<pre><code>&lt;?php\n\n$tags_array = get_tags();\n$news_query = new WP_Query;\n\nforeach ( $tags_array as $tags ) :\n $news_query-&gt;query( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n\n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while ( $news_query-&gt;have_posts() ) : $news_query-&gt;the_post() ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n" }, { "answer_id": 312756, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": -1, "selected": false, "text": "<p>I think @Castiblanco has the right answer, with maybe a little tweaking? His solution should certainly work, but I would do it just a tiny bit differently, like this:</p>\n\n<pre><code> &lt;?php\n\n $tags_array = get_tags();\n\n foreach ( $tags_array as $tags ) :\n $args( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n query_posts($args);\n if (have_posts()) : \n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while (have_posts()) : the_post(); ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n\n<p>The reason I'd do it this way is just to simplify the query and create a new object rather than using ->query also as previously noted be sure to reset postdata and if there are other loops on the page be sure to reset the query using wp_reset_query() after your endwhile.</p>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312736", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/131119/" ]
I'm trying to remove the distraction free mode button from the editor, but i can't make it disapear. Here is the code im using: ``` add_filter( 'wp_editor_settings', function($settings) { $settings['teeny']=true; $settings['media_buttons']=false; $settings['quicktags'] = false; $settings['dfw'] = false; return $settings; }); ``` Is there something i'm missing? Because this works on the regular editor. Thanks!
You can try something like this: ``` <?php $tags_array = get_tags(); $news_query = new WP_Query; foreach ( $tags_array as $tags ) : $news_query->query( array( 'cat' => $tags->term_id, 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, )); ?> <h2><?php echo esc_html( $tags->name ) ?></h2> <?php while ( $news_query->have_posts() ) : $news_query->the_post() ?> <div class="post"> <?php the_title() ?> <!-- do whatever you else you want that you can do in a normal loop --> </div> <?php endwhile ?> <?php endforeach ?> ```
312,741
<p>I upload all images through the Media Library Drag and Drop Uploader with no problems. Every time I use a CSV file with several thousand products, I enter the image url for each product, which is located in the Media Library. Example: /wp-content/uploads/2018/08/oa901-essence-1oz.jpg</p> <p>As a result, the product page uses the image with the added -1 instead of the original or even a thumbnail of the original. Then when I download all of the products, the image url has the added -1 to the end of the image file name. I can't figure out why this is happening and how to fix it. I tried deactivating almost every plugin, even manually uploading single products, but it still does the same thing. I can't use the images with the added -1, or -2, or -3, or -4, because those images do not display in the Media Library. Any Ideas?</p> <p>Attached are some screen shots. <a href="https://i.stack.imgur.com/yn9ea.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yn9ea.png" alt="Replicated Images On The Server"></a> <a href="https://i.stack.imgur.com/rQgye.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rQgye.png" alt="Replicated Images In The Media Library"></a> <a href="https://i.stack.imgur.com/HnOSv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HnOSv.png" alt="Wrong Image Chosen With the Added -1"></a></p>
[ { "answer_id": 312717, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 1, "selected": false, "text": "<p>You can try something like this:</p>\n\n<pre><code>&lt;?php\n\n$tags_array = get_tags();\n$news_query = new WP_Query;\n\nforeach ( $tags_array as $tags ) :\n $news_query-&gt;query( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n\n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while ( $news_query-&gt;have_posts() ) : $news_query-&gt;the_post() ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n" }, { "answer_id": 312756, "author": "Trisha", "author_id": 56458, "author_profile": "https://wordpress.stackexchange.com/users/56458", "pm_score": -1, "selected": false, "text": "<p>I think @Castiblanco has the right answer, with maybe a little tweaking? His solution should certainly work, but I would do it just a tiny bit differently, like this:</p>\n\n<pre><code> &lt;?php\n\n $tags_array = get_tags();\n\n foreach ( $tags_array as $tags ) :\n $args( array(\n 'cat' =&gt; $tags-&gt;term_id,\n 'posts_per_page' =&gt; 1,\n 'no_found_rows' =&gt; true,\n 'ignore_sticky_posts' =&gt; true,\n ));\n query_posts($args);\n if (have_posts()) : \n ?&gt;\n\n &lt;h2&gt;&lt;?php echo esc_html( $tags-&gt;name ) ?&gt;&lt;/h2&gt;\n\n &lt;?php while (have_posts()) : the_post(); ?&gt;\n\n &lt;div class=\"post\"&gt;\n &lt;?php the_title() ?&gt;\n &lt;!-- do whatever you else you want that you can do in a normal loop --&gt;\n &lt;/div&gt; \n\n &lt;?php endwhile ?&gt;\n\n&lt;?php endforeach ?&gt;\n</code></pre>\n\n<p>The reason I'd do it this way is just to simplify the query and create a new object rather than using ->query also as previously noted be sure to reset postdata and if there are other loops on the page be sure to reset the query using wp_reset_query() after your endwhile.</p>\n" } ]
2018/08/28
[ "https://wordpress.stackexchange.com/questions/312741", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/112400/" ]
I upload all images through the Media Library Drag and Drop Uploader with no problems. Every time I use a CSV file with several thousand products, I enter the image url for each product, which is located in the Media Library. Example: /wp-content/uploads/2018/08/oa901-essence-1oz.jpg As a result, the product page uses the image with the added -1 instead of the original or even a thumbnail of the original. Then when I download all of the products, the image url has the added -1 to the end of the image file name. I can't figure out why this is happening and how to fix it. I tried deactivating almost every plugin, even manually uploading single products, but it still does the same thing. I can't use the images with the added -1, or -2, or -3, or -4, because those images do not display in the Media Library. Any Ideas? Attached are some screen shots. [![Replicated Images On The Server](https://i.stack.imgur.com/yn9ea.png)](https://i.stack.imgur.com/yn9ea.png) [![Replicated Images In The Media Library](https://i.stack.imgur.com/rQgye.png)](https://i.stack.imgur.com/rQgye.png) [![Wrong Image Chosen With the Added -1](https://i.stack.imgur.com/HnOSv.png)](https://i.stack.imgur.com/HnOSv.png)
You can try something like this: ``` <?php $tags_array = get_tags(); $news_query = new WP_Query; foreach ( $tags_array as $tags ) : $news_query->query( array( 'cat' => $tags->term_id, 'posts_per_page' => 1, 'no_found_rows' => true, 'ignore_sticky_posts' => true, )); ?> <h2><?php echo esc_html( $tags->name ) ?></h2> <?php while ( $news_query->have_posts() ) : $news_query->the_post() ?> <div class="post"> <?php the_title() ?> <!-- do whatever you else you want that you can do in a normal loop --> </div> <?php endwhile ?> <?php endforeach ?> ```
312,822
<p>I created a simple design for showing team members with there image and linked with a modal (bootstrap 4). Its shows as following:</p> <pre><code> &lt;div class="col-lg-4 col-sm-6 text-center mb-4"&gt; &lt;img class="rounded-circle img-fluid d-block mx-auto" src="&lt;?php echo get_template_directory_uri(); ?&gt;/images/bestuur/jonas.jpg" alt=""&gt; &lt;h3&gt;&lt;strong&gt;Jonas&lt;/strong&gt; &lt;small&gt;Trainer&lt;/small&gt; &lt;/h3&gt; &lt;p&gt;Ik sta in voor.. "korte beschrijving"&lt;/p&gt; &lt;!-- Button trigger modal --&gt; &lt;button type="button" class="btn" style="background-color: red; color: #ffff;" data-toggle="modal" data-target="#ModalJonas"&gt; Meer info &amp; contact &lt;/button&gt; &lt;div class="modal fade" id="ModalJonas" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"&gt; &lt;div class="modal-dialog" role="document"&gt; &lt;div class="modal-content"&gt; &lt;div class="modal-header"&gt; &lt;h5 class="modal-title" id="exampleModalLabel"&gt;&lt;i class="far fa-user-circle"&gt;&lt;/i&gt; &lt;strong&gt;Jonas &lt;/strong&gt; &lt;small&gt;Trainer&lt;/small&gt;&lt;/h5&gt; &lt;button type="button" class="close" data-dismiss="modal" aria-label="Close"&gt; &lt;span aria-hidden="true"&gt;&amp;times;&lt;/span&gt; &lt;/button&gt; &lt;/div&gt; &lt;div class="modal-body"&gt; &lt;p&gt;Beshrijven van persoon/functie &lt;br&gt; Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. &lt;/p&gt; &lt;div class=" text-left"&gt; &lt;p&gt;&lt;i class="fas fa-phone"&gt;&lt;/i&gt; 04 54 84 12&lt;/p&gt; &lt;p&gt;&lt;i class="far fa-envelope"&gt;&lt;/i&gt; [email protected]&lt;/p&gt; &lt;p&gt;&lt;i class="fas fa-map-marker-alt"&gt;&lt;/i&gt; 8 &lt;br&gt; 8560 &lt;/p&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="modal-footer"&gt; &lt;button type="button" class="btn btn-secondary" data-dismiss="modal"&gt;Close&lt;/button&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now the thing is, this takes allot of code. Is there away in wordpress to just enter value's like (name, description_small, description_large, img_patch, modalname.. etc) and than just use a php while lus to generate the content on my wordpress page? this makes is allot less messy + realy easy to add members to the page</p> <p>I hope you understand what i'm trying to do, anny suggestions?</p>
[ { "answer_id": 312824, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>What you can do is to use a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a>, for example, you can add them to your <code>functions.php</code> or <code>create a plugin</code> that does the same.</p>\n\n<p>Check <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress\" rel=\"nofollow noreferrer\">this guide</a>, but keep in mind there is a lot of information about WordPress and shortcodes. </p>\n\n<p>In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this:</p>\n\n<pre><code>[memberThing description=\"yes\"] //...\n</code></pre>\n" }, { "answer_id": 312852, "author": "Eric B.", "author_id": 118176, "author_profile": "https://wordpress.stackexchange.com/users/118176", "pm_score": 0, "selected": false, "text": "<p>This sounds like the perfect use case for a custom post type that you then use the loop to show each of those. That way you can add/edit/delete just like any other post. Just a thought. </p>\n" } ]
2018/08/29
[ "https://wordpress.stackexchange.com/questions/312822", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148864/" ]
I created a simple design for showing team members with there image and linked with a modal (bootstrap 4). Its shows as following: ``` <div class="col-lg-4 col-sm-6 text-center mb-4"> <img class="rounded-circle img-fluid d-block mx-auto" src="<?php echo get_template_directory_uri(); ?>/images/bestuur/jonas.jpg" alt=""> <h3><strong>Jonas</strong> <small>Trainer</small> </h3> <p>Ik sta in voor.. "korte beschrijving"</p> <!-- Button trigger modal --> <button type="button" class="btn" style="background-color: red; color: #ffff;" data-toggle="modal" data-target="#ModalJonas"> Meer info & contact </button> <div class="modal fade" id="ModalJonas" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel"><i class="far fa-user-circle"></i> <strong>Jonas </strong> <small>Trainer</small></h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Beshrijven van persoon/functie <br> Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. </p> <div class=" text-left"> <p><i class="fas fa-phone"></i> 04 54 84 12</p> <p><i class="far fa-envelope"></i> [email protected]</p> <p><i class="fas fa-map-marker-alt"></i> 8 <br> 8560 </p> </div> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </div> </div> </div> </div> ``` Now the thing is, this takes allot of code. Is there away in wordpress to just enter value's like (name, description\_small, description\_large, img\_patch, modalname.. etc) and than just use a php while lus to generate the content on my wordpress page? this makes is allot less messy + realy easy to add members to the page I hope you understand what i'm trying to do, anny suggestions?
What you can do is to use a [shortcode](https://codex.wordpress.org/Shortcode_API), for example, you can add them to your `functions.php` or `create a plugin` that does the same. Check [this guide](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress), but keep in mind there is a lot of information about WordPress and shortcodes. In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this: ``` [memberThing description="yes"] //... ```
312,839
<p>I followed this guide <a href="https://docs.woocommerce.com/document/template-structure/" rel="nofollow noreferrer">https://docs.woocommerce.com/document/template-structure/</a></p> <p>Then I installed a Woocommerce folder inside of my theme folder and added some lines in functions.php </p> <pre><code> function mytheme_add_woocommerce_support() { add_theme_support( 'woocommerce', array( 'thumbnail_image_width' =&gt; 150, 'single_image_width' =&gt; 300, 'product_grid' =&gt; array( 'default_rows' =&gt; 3, 'min_rows' =&gt; 2, 'max_rows' =&gt; 8, 'default_columns' =&gt; 4, 'min_columns' =&gt; 2, 'max_columns' =&gt; 5, ), ) ); } add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' ); </code></pre> <p>And I moved files from template folder to parent folder...</p> <p>I went to admin panel and nothing happens...</p>
[ { "answer_id": 312824, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>What you can do is to use a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a>, for example, you can add them to your <code>functions.php</code> or <code>create a plugin</code> that does the same.</p>\n\n<p>Check <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress\" rel=\"nofollow noreferrer\">this guide</a>, but keep in mind there is a lot of information about WordPress and shortcodes. </p>\n\n<p>In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this:</p>\n\n<pre><code>[memberThing description=\"yes\"] //...\n</code></pre>\n" }, { "answer_id": 312852, "author": "Eric B.", "author_id": 118176, "author_profile": "https://wordpress.stackexchange.com/users/118176", "pm_score": 0, "selected": false, "text": "<p>This sounds like the perfect use case for a custom post type that you then use the loop to show each of those. That way you can add/edit/delete just like any other post. Just a thought. </p>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312839", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149634/" ]
I followed this guide <https://docs.woocommerce.com/document/template-structure/> Then I installed a Woocommerce folder inside of my theme folder and added some lines in functions.php ``` function mytheme_add_woocommerce_support() { add_theme_support( 'woocommerce', array( 'thumbnail_image_width' => 150, 'single_image_width' => 300, 'product_grid' => array( 'default_rows' => 3, 'min_rows' => 2, 'max_rows' => 8, 'default_columns' => 4, 'min_columns' => 2, 'max_columns' => 5, ), ) ); } add_action( 'after_setup_theme', 'mytheme_add_woocommerce_support' ); ``` And I moved files from template folder to parent folder... I went to admin panel and nothing happens...
What you can do is to use a [shortcode](https://codex.wordpress.org/Shortcode_API), for example, you can add them to your `functions.php` or `create a plugin` that does the same. Check [this guide](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress), but keep in mind there is a lot of information about WordPress and shortcodes. In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this: ``` [memberThing description="yes"] //... ```
312,843
<p>On my ecommerce website, I don't want customers to leave my website and be directed to PayPal when paying via credit card. Is there a good plugin that shows a PayPal credit card form on my checkout page?</p> <p>Thanks!</p>
[ { "answer_id": 312824, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>What you can do is to use a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a>, for example, you can add them to your <code>functions.php</code> or <code>create a plugin</code> that does the same.</p>\n\n<p>Check <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress\" rel=\"nofollow noreferrer\">this guide</a>, but keep in mind there is a lot of information about WordPress and shortcodes. </p>\n\n<p>In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this:</p>\n\n<pre><code>[memberThing description=\"yes\"] //...\n</code></pre>\n" }, { "answer_id": 312852, "author": "Eric B.", "author_id": 118176, "author_profile": "https://wordpress.stackexchange.com/users/118176", "pm_score": 0, "selected": false, "text": "<p>This sounds like the perfect use case for a custom post type that you then use the loop to show each of those. That way you can add/edit/delete just like any other post. Just a thought. </p>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312843", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/113629/" ]
On my ecommerce website, I don't want customers to leave my website and be directed to PayPal when paying via credit card. Is there a good plugin that shows a PayPal credit card form on my checkout page? Thanks!
What you can do is to use a [shortcode](https://codex.wordpress.org/Shortcode_API), for example, you can add them to your `functions.php` or `create a plugin` that does the same. Check [this guide](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress), but keep in mind there is a lot of information about WordPress and shortcodes. In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this: ``` [memberThing description="yes"] //... ```
312,845
<p>I created a taxonomy called <code>animal</code> and a term meta field called <code>horse</code>. </p> <p>I created a function in my functios.php file to make it easier to display the data.</p> <p>Here is my code:</p> <pre><code>function regular_info_page() { $terms = get_the_terms($post-&gt;ID, 'animal'); $result = ""; if (is_array($terms) || is_object($terms)){ foreach ($terms as $term) { $term_id = $term-&gt;term_id; $result .= get_term_meta( $term_id, 'horse', true ); } } return $result; } </code></pre> <p>The meta field <code>horse</code> holds a link, and I would like to display the link on my page, but instead of it opening the link, it just reloads the current page.</p> <p>Here is the code I placed on the page:</p> <p><code>&lt;p&gt;&lt;a href="&lt;?php regular_info_page(); ?&gt;"&gt;For more info on this Bracha, click here.&lt;/a&gt;&lt;/p&gt;</code></p> <p>Any ideas?</p>
[ { "answer_id": 312824, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>What you can do is to use a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a>, for example, you can add them to your <code>functions.php</code> or <code>create a plugin</code> that does the same.</p>\n\n<p>Check <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress\" rel=\"nofollow noreferrer\">this guide</a>, but keep in mind there is a lot of information about WordPress and shortcodes. </p>\n\n<p>In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this:</p>\n\n<pre><code>[memberThing description=\"yes\"] //...\n</code></pre>\n" }, { "answer_id": 312852, "author": "Eric B.", "author_id": 118176, "author_profile": "https://wordpress.stackexchange.com/users/118176", "pm_score": 0, "selected": false, "text": "<p>This sounds like the perfect use case for a custom post type that you then use the loop to show each of those. That way you can add/edit/delete just like any other post. Just a thought. </p>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312845", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149636/" ]
I created a taxonomy called `animal` and a term meta field called `horse`. I created a function in my functios.php file to make it easier to display the data. Here is my code: ``` function regular_info_page() { $terms = get_the_terms($post->ID, 'animal'); $result = ""; if (is_array($terms) || is_object($terms)){ foreach ($terms as $term) { $term_id = $term->term_id; $result .= get_term_meta( $term_id, 'horse', true ); } } return $result; } ``` The meta field `horse` holds a link, and I would like to display the link on my page, but instead of it opening the link, it just reloads the current page. Here is the code I placed on the page: `<p><a href="<?php regular_info_page(); ?>">For more info on this Bracha, click here.</a></p>` Any ideas?
What you can do is to use a [shortcode](https://codex.wordpress.org/Shortcode_API), for example, you can add them to your `functions.php` or `create a plugin` that does the same. Check [this guide](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress), but keep in mind there is a lot of information about WordPress and shortcodes. In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this: ``` [memberThing description="yes"] //... ```
312,846
<p>Please forgive me if my question isn't the clearest and I'm not using this exactly correct... I've never posted before. </p> <p>I am trying to setup a query on a real estate website that I'm developing that will give precedence to the company's listings (a custom post type) before showing the other listings (of the same custom post type), based on the value of a custom field. Inside of my meta_query array, I can add an array such as the following below to show the office's listings by means of a custom field on the post:</p> <pre><code>array( 'key' =&gt; 'office_name', 'compare' =&gt; 'LIKE', 'value' =&gt; 'XYZ Realty' ), </code></pre> <p>Using the snippet above in my query grabs the office's listings as expected, but only "their" listings (or those posts that have their office name in the custom field). </p> <p>For sorting purposes, I am using the following to sort by price, which is another custom field on my custom post type ("listing"):</p> <pre><code>'meta_key' =&gt; 'price', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; 'DESC' </code></pre> <p>Which also works as intended. So with that... is it possible to tweak the query so that it will give the office's listings a priority or precedence to be shown first and then those that are not theirs immediately following? </p>
[ { "answer_id": 312824, "author": "Castiblanco", "author_id": 44370, "author_profile": "https://wordpress.stackexchange.com/users/44370", "pm_score": 3, "selected": true, "text": "<p>What you can do is to use a <a href=\"https://codex.wordpress.org/Shortcode_API\" rel=\"nofollow noreferrer\">shortcode</a>, for example, you can add them to your <code>functions.php</code> or <code>create a plugin</code> that does the same.</p>\n\n<p>Check <a href=\"https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress\" rel=\"nofollow noreferrer\">this guide</a>, but keep in mind there is a lot of information about WordPress and shortcodes. </p>\n\n<p>In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this:</p>\n\n<pre><code>[memberThing description=\"yes\"] //...\n</code></pre>\n" }, { "answer_id": 312852, "author": "Eric B.", "author_id": 118176, "author_profile": "https://wordpress.stackexchange.com/users/118176", "pm_score": 0, "selected": false, "text": "<p>This sounds like the perfect use case for a custom post type that you then use the loop to show each of those. That way you can add/edit/delete just like any other post. Just a thought. </p>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312846", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149639/" ]
Please forgive me if my question isn't the clearest and I'm not using this exactly correct... I've never posted before. I am trying to setup a query on a real estate website that I'm developing that will give precedence to the company's listings (a custom post type) before showing the other listings (of the same custom post type), based on the value of a custom field. Inside of my meta\_query array, I can add an array such as the following below to show the office's listings by means of a custom field on the post: ``` array( 'key' => 'office_name', 'compare' => 'LIKE', 'value' => 'XYZ Realty' ), ``` Using the snippet above in my query grabs the office's listings as expected, but only "their" listings (or those posts that have their office name in the custom field). For sorting purposes, I am using the following to sort by price, which is another custom field on my custom post type ("listing"): ``` 'meta_key' => 'price', 'orderby' => 'meta_value_num', 'order' => 'DESC' ``` Which also works as intended. So with that... is it possible to tweak the query so that it will give the office's listings a priority or precedence to be shown first and then those that are not theirs immediately following?
What you can do is to use a [shortcode](https://codex.wordpress.org/Shortcode_API), for example, you can add them to your `functions.php` or `create a plugin` that does the same. Check [this guide](https://www.elegantthemes.com/blog/tips-tricks/how-to-create-shortcodes-in-wordpress), but keep in mind there is a lot of information about WordPress and shortcodes. In the end, you will only have to call your shortcode wherever you want. Shortcodes can use attributes so you could end with something like this: ``` [memberThing description="yes"] //... ```
312,871
<p>I need to place <strong>Add to cart</strong> button at every product on the page of certain category as shown below <a href="https://i.stack.imgur.com/HCtd9.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/HCtd9.png" alt="page&#39;s screenshot"></a></p> <p>How can I achive this? Link to subject page <a href="https://oma-fitness.com.ua/orbitreki" rel="nofollow noreferrer">oma-fintess.com.ua</a></p>
[ { "answer_id": 312886, "author": "Pratik Patel", "author_id": 143123, "author_profile": "https://wordpress.stackexchange.com/users/143123", "pm_score": 0, "selected": false, "text": "<p>Please make sure that “Enable AJAX add to cart buttons on archives” is turned on in <strong>WooCommerce > Settings > Products > Display</strong>.</p>\n\n<p>Also please Check following code place in to your theme function file.</p>\n\n<pre><code>add_action( ‘woocommerce_after_shop_loop_item’, ‘woocommerce_template_loop_add_to_cart’, 10 );\n</code></pre>\n" }, { "answer_id": 312922, "author": "Twissell", "author_id": 101659, "author_profile": "https://wordpress.stackexchange.com/users/101659", "pm_score": 2, "selected": true, "text": "<pre><code>&lt;a href=\"&lt;?php the_permalink(); ?&gt;\" class=\"more\"&gt;More info&lt;/a&gt;&lt;?php\nif($available){?&gt;&lt;a href=\"&lt;?php\n $add_to_cart = do_shortcode('[add_to_cart_url id=\"'.$post-&gt;ID.'\"]');\n echo $add_to_cart;\n?&gt;\" class=\"more\"&gt;Buy now&lt;/a&gt;\n &lt;?php \n }\n</code></pre>\n\n<p>This code solve my problem as expected.</p>\n\n<p><a href=\"https://docs.woocommerce.com/document/woocommerce-shortcodes/#section-15\" rel=\"nofollow noreferrer\">WooCommerce documentation reference</a></p>\n" }, { "answer_id": 375517, "author": "Mohammad Arif", "author_id": 129500, "author_profile": "https://wordpress.stackexchange.com/users/129500", "pm_score": 3, "selected": false, "text": "<p>You can use the WooCommerce hook <code>woocommerce_after_add_to_cart_button</code>. This hook will add content after the &quot;Add To Cart&quot; button.</p>\n<p>If the customer clicks on this button, the product should get added to the cart, and the customer should be send to the checkout page.</p>\n<p>Add the below code in your child theme <code>functions.php</code></p>\n<pre><code>/* Create Buy Now Button dynamically after Add To Cart button */\n function add_content_after_addtocart() {\n \n // get the current post/product ID\n $current_product_id = get_the_ID();\n \n // get the product based on the ID\n $product = wc_get_product( $current_product_id );\n \n // get the &quot;Checkout Page&quot; URL\n $checkout_url = WC()-&gt;cart-&gt;get_checkout_url();\n \n // run only on simple products\n if( $product-&gt;is_type( 'simple' ) ){\n echo '&lt;a href=&quot;'.$checkout_url.'?add-to-cart='.$current_product_id.'&quot; class=&quot;buy-now button&quot;&gt;Buy Now&lt;/a&gt;';\n //echo '&lt;a href=&quot;'.$checkout_url.'&quot; class=&quot;buy-now button&quot;&gt;Buy Now&lt;/a&gt;';\n }\n }\n add_action( 'woocommerce_after_add_to_cart_button', 'add_content_after_addtocart' );\n</code></pre>\n" }, { "answer_id": 385511, "author": "Өлзийбат Нансалцог", "author_id": 159595, "author_profile": "https://wordpress.stackexchange.com/users/159595", "pm_score": 1, "selected": false, "text": "<p>Here is simple solution for it.</p>\n<pre><code>$product_object = wc_get_product( $product_id );\necho '&lt;a href=&quot;' . esc_url( $product_object-&gt;add_to_cart_url() ) . '&quot; class=&quot;buy-now button&quot;&gt;' . esc_html__( 'Buy Now', 'text-domain' ) . '&lt;/a&gt;';\n</code></pre>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312871", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/101659/" ]
I need to place **Add to cart** button at every product on the page of certain category as shown below [![page's screenshot](https://i.stack.imgur.com/HCtd9.png)](https://i.stack.imgur.com/HCtd9.png) How can I achive this? Link to subject page [oma-fintess.com.ua](https://oma-fitness.com.ua/orbitreki)
``` <a href="<?php the_permalink(); ?>" class="more">More info</a><?php if($available){?><a href="<?php $add_to_cart = do_shortcode('[add_to_cart_url id="'.$post->ID.'"]'); echo $add_to_cart; ?>" class="more">Buy now</a> <?php } ``` This code solve my problem as expected. [WooCommerce documentation reference](https://docs.woocommerce.com/document/woocommerce-shortcodes/#section-15)
312,879
<p>I need help with this one. What I want to do is to display specific posts of the custom post type. Everything working fine, just I can't display more than 1(one) post. doesn't matter how much posts I select it always return to me just one. Here is a full code</p> <pre><code>&lt;?php $post_objects = get_sub_field('choose_blocks'); $string = ""; if( $post_objects ): ?&gt; &lt;?php foreach( $post_objects as $post_object): $post_id = $post_object-&gt;ID; $string .= $post_id.','; endforeach; ?&gt; &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?&gt; &lt;?php endif; ?&gt; &lt;?php $string = rtrim($string, ','); ?&gt; &lt;?php $args = array( 'post_type'=&gt;'presentations', 'post_status'=&gt;'publish', 'post__in' =&gt; array( $string ) ); ?&gt; &lt;?php // the query $all_presentations = new WP_Query($args); ?&gt; &lt;?php if ( $all_presentations-&gt;have_posts() ) : ?&gt; &lt;?php while ( $all_presentations-&gt;have_posts() ) : $all_presentations-&gt;the_post(); ?&gt; &lt;?php get_template_part( 'includes/content', get_post_format() ); ?&gt; &lt;?php endwhile; ?&gt; &lt;!-- end of the loop --&gt; &lt;?php wp_reset_postdata(); ?&gt; &lt;?php else : ?&gt; &lt;!-- do nothing --&gt; &lt;?php endif; ?&gt; &lt;?php endif; ?&gt; </code></pre>
[ { "answer_id": 312889, "author": "Stefan", "author_id": 93082, "author_profile": "https://wordpress.stackexchange.com/users/93082", "pm_score": -1, "selected": false, "text": "<p>Here is a solution, i need to returns an array of string. It's not enough to pass string in array()</p>\n\n<pre><code>&lt;?php $arr = explode(',', $string); ?&gt;\n</code></pre>\n\n<p>Full code</p>\n\n<pre><code>&lt;?php\n\n$post_objects = get_sub_field('choose_blocks');\n$string = \"\";\nif( $post_objects ): ?&gt;\n\n &lt;?php foreach( $post_objects as $post_object):\n\n $post_id = $post_object-&gt;ID;\n\n $string .= $post_id.',';\n\n\n endforeach; ?&gt;\n\n &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?&gt;\n&lt;?php endif; ?&gt;\n\n&lt;?php $string = rtrim($string, ','); ?&gt;\n\n\n// THIS IS THAT I NEED TO GET IT WORK\n&lt;?php $arr = explode(',', $string); ?&gt;\n\n\n &lt;?php\n $args = array(\n 'post_type'=&gt;'presentations',\n 'post_status'=&gt;'publish',\n 'post__in' =&gt; array( $string )\n );\n?&gt;\n &lt;?php // the query\n $all_presentations = new WP_Query($args); ?&gt;\n\n &lt;?php if ( $all_presentations-&gt;have_posts() ) : ?&gt;\n\n &lt;?php while ( $all_presentations-&gt;have_posts() ) : $all_presentations-&gt;the_post(); ?&gt;\n\n &lt;?php get_template_part( 'includes/content', get_post_format() ); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;!-- end of the loop --&gt;\n\n\n &lt;?php wp_reset_postdata(); ?&gt;\n\n &lt;?php else : ?&gt;\n &lt;!-- do nothing --&gt;\n &lt;?php endif; ?&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 312980, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 1, "selected": false, "text": "<p>now we are getting there.. you really need to try to explain, what your problem is, its not very clear in your question.</p>\n\n<p>my assumption is, you tried this one, but it didn't work out:</p>\n\n<pre><code>foreach( $post_objects as $post_object):\n get_template_part( 'includes/content', get_post_format( $post_object-&gt;ID ) );\nendforeach;\n</code></pre>\n\n<p>and here is why: you call the template, but the global <code>$post</code> is still set to the previous post/page. you need to set the global <code>$post</code> variable as you do it later on in your code (<code>$all_presentations-&gt;the_post();</code>). it works differently, when you do it in a foreach and not with <code>WP_Query()</code>, but you can set the global <code>$post</code> variable when you hand and object of that post to <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow noreferrer\">setup_postdata</a>. when you do that, you can call all the other functions, like <code>the_title()</code> or <code>the_content()</code> and wp will grab it from the object, that you provided.</p>\n\n<p>here is how:</p>\n\n<pre><code>&lt;?php\n /**\n * when you call the_title() here, it will return the title of the current post/page (global $post defined by main query)\n */\nif( $post_objects ):\n foreach( $post_objects as $post): //!!the variable MUST be called $post\n setup_postdata($post); //set new $post_object\n /**\n * now we switched global $post, so the_title() will return other the contents of your $post_object\n */\n get_template_part( 'includes/content', get_post_format() );\n endforeach;\n wp_reset_postdata(); //reset global $post\nendif;\n?&gt;\n</code></pre>\n\n<p>you need to call <code>setup_postdata()</code>on your obect, to use <code>get_post_format()</code>. see the <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow noreferrer\">docs</a> for more info on setup_postdata.</p>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312879", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/93082/" ]
I need help with this one. What I want to do is to display specific posts of the custom post type. Everything working fine, just I can't display more than 1(one) post. doesn't matter how much posts I select it always return to me just one. Here is a full code ``` <?php $post_objects = get_sub_field('choose_blocks'); $string = ""; if( $post_objects ): ?> <?php foreach( $post_objects as $post_object): $post_id = $post_object->ID; $string .= $post_id.','; endforeach; ?> <?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?> <?php endif; ?> <?php $string = rtrim($string, ','); ?> <?php $args = array( 'post_type'=>'presentations', 'post_status'=>'publish', 'post__in' => array( $string ) ); ?> <?php // the query $all_presentations = new WP_Query($args); ?> <?php if ( $all_presentations->have_posts() ) : ?> <?php while ( $all_presentations->have_posts() ) : $all_presentations->the_post(); ?> <?php get_template_part( 'includes/content', get_post_format() ); ?> <?php endwhile; ?> <!-- end of the loop --> <?php wp_reset_postdata(); ?> <?php else : ?> <!-- do nothing --> <?php endif; ?> <?php endif; ?> ```
now we are getting there.. you really need to try to explain, what your problem is, its not very clear in your question. my assumption is, you tried this one, but it didn't work out: ``` foreach( $post_objects as $post_object): get_template_part( 'includes/content', get_post_format( $post_object->ID ) ); endforeach; ``` and here is why: you call the template, but the global `$post` is still set to the previous post/page. you need to set the global `$post` variable as you do it later on in your code (`$all_presentations->the_post();`). it works differently, when you do it in a foreach and not with `WP_Query()`, but you can set the global `$post` variable when you hand and object of that post to [setup\_postdata](https://codex.wordpress.org/Function_Reference/setup_postdata). when you do that, you can call all the other functions, like `the_title()` or `the_content()` and wp will grab it from the object, that you provided. here is how: ``` <?php /** * when you call the_title() here, it will return the title of the current post/page (global $post defined by main query) */ if( $post_objects ): foreach( $post_objects as $post): //!!the variable MUST be called $post setup_postdata($post); //set new $post_object /** * now we switched global $post, so the_title() will return other the contents of your $post_object */ get_template_part( 'includes/content', get_post_format() ); endforeach; wp_reset_postdata(); //reset global $post endif; ?> ``` you need to call `setup_postdata()`on your obect, to use `get_post_format()`. see the [docs](https://codex.wordpress.org/Function_Reference/setup_postdata) for more info on setup\_postdata.
312,905
<p>I have created a HTML website and want to shift to wordpress. I have another theme so I will be copying my content to that theme. But I want to keep my HTML website alive till I am done with the shifting to wordpress. Is there any way I can install the wordpress database and install my theme and start my word in backend whereas the HTML still stays alive.</p> <p>I am a beginner in this so please spare me for any errors.</p> <p>Thank you.</p>
[ { "answer_id": 312889, "author": "Stefan", "author_id": 93082, "author_profile": "https://wordpress.stackexchange.com/users/93082", "pm_score": -1, "selected": false, "text": "<p>Here is a solution, i need to returns an array of string. It's not enough to pass string in array()</p>\n\n<pre><code>&lt;?php $arr = explode(',', $string); ?&gt;\n</code></pre>\n\n<p>Full code</p>\n\n<pre><code>&lt;?php\n\n$post_objects = get_sub_field('choose_blocks');\n$string = \"\";\nif( $post_objects ): ?&gt;\n\n &lt;?php foreach( $post_objects as $post_object):\n\n $post_id = $post_object-&gt;ID;\n\n $string .= $post_id.',';\n\n\n endforeach; ?&gt;\n\n &lt;?php wp_reset_postdata(); // IMPORTANT - reset the $post object so the rest of the page works correctly ?&gt;\n&lt;?php endif; ?&gt;\n\n&lt;?php $string = rtrim($string, ','); ?&gt;\n\n\n// THIS IS THAT I NEED TO GET IT WORK\n&lt;?php $arr = explode(',', $string); ?&gt;\n\n\n &lt;?php\n $args = array(\n 'post_type'=&gt;'presentations',\n 'post_status'=&gt;'publish',\n 'post__in' =&gt; array( $string )\n );\n?&gt;\n &lt;?php // the query\n $all_presentations = new WP_Query($args); ?&gt;\n\n &lt;?php if ( $all_presentations-&gt;have_posts() ) : ?&gt;\n\n &lt;?php while ( $all_presentations-&gt;have_posts() ) : $all_presentations-&gt;the_post(); ?&gt;\n\n &lt;?php get_template_part( 'includes/content', get_post_format() ); ?&gt;\n\n &lt;?php endwhile; ?&gt;\n &lt;!-- end of the loop --&gt;\n\n\n &lt;?php wp_reset_postdata(); ?&gt;\n\n &lt;?php else : ?&gt;\n &lt;!-- do nothing --&gt;\n &lt;?php endif; ?&gt;\n\n&lt;?php endif; ?&gt;\n</code></pre>\n" }, { "answer_id": 312980, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 1, "selected": false, "text": "<p>now we are getting there.. you really need to try to explain, what your problem is, its not very clear in your question.</p>\n\n<p>my assumption is, you tried this one, but it didn't work out:</p>\n\n<pre><code>foreach( $post_objects as $post_object):\n get_template_part( 'includes/content', get_post_format( $post_object-&gt;ID ) );\nendforeach;\n</code></pre>\n\n<p>and here is why: you call the template, but the global <code>$post</code> is still set to the previous post/page. you need to set the global <code>$post</code> variable as you do it later on in your code (<code>$all_presentations-&gt;the_post();</code>). it works differently, when you do it in a foreach and not with <code>WP_Query()</code>, but you can set the global <code>$post</code> variable when you hand and object of that post to <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow noreferrer\">setup_postdata</a>. when you do that, you can call all the other functions, like <code>the_title()</code> or <code>the_content()</code> and wp will grab it from the object, that you provided.</p>\n\n<p>here is how:</p>\n\n<pre><code>&lt;?php\n /**\n * when you call the_title() here, it will return the title of the current post/page (global $post defined by main query)\n */\nif( $post_objects ):\n foreach( $post_objects as $post): //!!the variable MUST be called $post\n setup_postdata($post); //set new $post_object\n /**\n * now we switched global $post, so the_title() will return other the contents of your $post_object\n */\n get_template_part( 'includes/content', get_post_format() );\n endforeach;\n wp_reset_postdata(); //reset global $post\nendif;\n?&gt;\n</code></pre>\n\n<p>you need to call <code>setup_postdata()</code>on your obect, to use <code>get_post_format()</code>. see the <a href=\"https://codex.wordpress.org/Function_Reference/setup_postdata\" rel=\"nofollow noreferrer\">docs</a> for more info on setup_postdata.</p>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312905", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149678/" ]
I have created a HTML website and want to shift to wordpress. I have another theme so I will be copying my content to that theme. But I want to keep my HTML website alive till I am done with the shifting to wordpress. Is there any way I can install the wordpress database and install my theme and start my word in backend whereas the HTML still stays alive. I am a beginner in this so please spare me for any errors. Thank you.
now we are getting there.. you really need to try to explain, what your problem is, its not very clear in your question. my assumption is, you tried this one, but it didn't work out: ``` foreach( $post_objects as $post_object): get_template_part( 'includes/content', get_post_format( $post_object->ID ) ); endforeach; ``` and here is why: you call the template, but the global `$post` is still set to the previous post/page. you need to set the global `$post` variable as you do it later on in your code (`$all_presentations->the_post();`). it works differently, when you do it in a foreach and not with `WP_Query()`, but you can set the global `$post` variable when you hand and object of that post to [setup\_postdata](https://codex.wordpress.org/Function_Reference/setup_postdata). when you do that, you can call all the other functions, like `the_title()` or `the_content()` and wp will grab it from the object, that you provided. here is how: ``` <?php /** * when you call the_title() here, it will return the title of the current post/page (global $post defined by main query) */ if( $post_objects ): foreach( $post_objects as $post): //!!the variable MUST be called $post setup_postdata($post); //set new $post_object /** * now we switched global $post, so the_title() will return other the contents of your $post_object */ get_template_part( 'includes/content', get_post_format() ); endforeach; wp_reset_postdata(); //reset global $post endif; ?> ``` you need to call `setup_postdata()`on your obect, to use `get_post_format()`. see the [docs](https://codex.wordpress.org/Function_Reference/setup_postdata) for more info on setup\_postdata.
312,929
<p>I'm trying to display user info including custom fields determined by an ACF relational user field, and all contained within a flexible content field.</p> <p><em>EDIT</em> Updated code following answers / comments, but still can't get anything to output - all my variables are empty.</p> <p>The flexible content part is fine, and I'm just including it for context.</p> <p>I have hit a brick wall with getting the related user info out though.</p> <p>Within my flexible content layout, I have:</p> <p><strong>Field Type:</strong> User<br> <strong>Select multiple values?:</strong> Yes<br> <strong>Return format:</strong> User Array</p> <p>Then in my template I have (most HTML Stripped out):</p> <p>(<code>role</code> and <code>author_image</code> are ACF fields in the user entry).</p> <pre><code>&lt;?php $posts = get_sub_field('who_to_show'); if( $posts ): foreach( $posts as $post): setup_postdata($post); $user_info = get_userdata($post); $image = get_field('author_image', 'user_' . $user_info-&gt;post_author ); $role = get_field('role', 'user_' . $user_info-&gt;post_author ); ?&gt; &lt;p&gt;&lt;?php echo $role; ?&gt;&lt;/p&gt; &lt;img src="&lt;?php echo $image['url']; ?&gt;" alt="&lt;?php echo $image['alt']; ?&gt;" /&gt; &lt;?php endforeach; endif; wp_reset_postdata(); ?&gt; </code></pre> <p>I also tried:</p> <pre><code>&lt;?php $posts = get_sub_field('who_to_show'); if( $posts ): foreach( $posts as $post): setup_postdata($post); $image = get_field('author_image'); $role = get_field('role'); ?&gt; &lt;p&gt;&lt;?php echo $role; ?&gt;&lt;/p&gt; &lt;img src="&lt;?php echo $image['url']; ?&gt;" alt="&lt;?php echo $image['alt']; ?&gt;" /&gt; &lt;?php endforeach; endif; wp_reset_postdata(); ?&gt; </code></pre> <p>And still my variables are empty.</p> <p>It's worth noting the image field Return Value is set to "Image Array" in ACF.</p> <p>Any pointers in the right direction appreciated.</p>
[ { "answer_id": 312931, "author": "Lewis Donovan", "author_id": 113034, "author_profile": "https://wordpress.stackexchange.com/users/113034", "pm_score": 1, "selected": false, "text": "<p>You don't actually need to call <code>get_userdata()</code>, all the data you need should be in the relational field array:</p>\n\n<p><strong>EDIT</strong>: Add post ID and User ID to calls to <code>get_field()</code>.</p>\n\n\n\n<pre><code>&lt;?php\n$posts = get_sub_field('who_to_show');\n\n if( $posts ): ?&gt;\n\n &lt;?php foreach( $posts as $post):\n\n setup_postdata($post);\n $user_info = get_field( 'relational_user_field', $post-&gt;ID );\n $image = get_the_field('author_image', 'user_'.$user_info-&gt;ID );\n $role = get_the_field('role', 'user_'.$user_info-&gt;ID );\n ?&gt;\n\n &lt;h3&gt;&lt;?php echo $user_info-&gt;user_nicename; ?&gt;&lt;/h3&gt;\n &lt;img src=\"&lt;?php echo $image['url']; ?&gt;\" alt=\"&lt;?php echo $image['alt']; ?&gt;\" /&gt;\n\n &lt;?php endforeach;\n endif;\n wp_reset_postdata();\n\nendif; ?&gt;\n</code></pre>\n\n<p>Obviously swap <code>'relational_user_field'</code> for your actual field name.\nThe data returned in the user array is the same as the return values in <a href=\"https://codex.wordpress.org/Function_Reference/the_author_meta\" rel=\"nofollow noreferrer\"><code>the_author_meta</code></a></p>\n" }, { "answer_id": 312934, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 0, "selected": false, "text": "<p>you wrote <code>get_the_field</code>, whilst the proper function to get acf data is <code>get_field</code> or <code>the_field</code> if you want to echo the stuff immediately.. i guess, this breaks your template.</p>\n\n<p>not sure, if i got you right, but if you added the field <code>author_image</code> to the user, than the following answer will get you there. if not, than my answer is crap :)</p>\n\n<p>the proper way of getting acf data from a user would be like this:</p>\n\n<pre><code>get_field('author_image', 'user_' . $user_info-&gt;post_author );\n</code></pre>\n\n<p>when you simply call <code>get_field('parameter')</code> it will return data from the current post, similar to <code>get_field('parameter', get_the_ID())</code>, so if you change that second parameter to whatever ID you have, you could get it from that specific ID.. in case of <code>user</code> it is <code>user_(USER_ID)</code></p>\n" }, { "answer_id": 314131, "author": "user2265915", "author_id": 111367, "author_profile": "https://wordpress.stackexchange.com/users/111367", "pm_score": 1, "selected": true, "text": "<p>The solution was only slightly different from Lewis' answer:</p>\n\n<pre><code>&lt;?php\n $posts = get_sub_field('who_to_show');\n\n if( $posts ):\n\n foreach( $posts as $post):\n\n $userdata = get_user_by('ID',$post['ID']);\n $image = get_field('author_image', 'user_'. $post['ID'] );\n $role = get_field('role', 'user_'. $post['ID'] );\n\n echo $userdata-&gt;first_name;\n echo $role;\n\n endforeach;\n\n endif;\n\nwp_reset_postdata(); ?&gt;\n</code></pre>\n" } ]
2018/08/30
[ "https://wordpress.stackexchange.com/questions/312929", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/111367/" ]
I'm trying to display user info including custom fields determined by an ACF relational user field, and all contained within a flexible content field. *EDIT* Updated code following answers / comments, but still can't get anything to output - all my variables are empty. The flexible content part is fine, and I'm just including it for context. I have hit a brick wall with getting the related user info out though. Within my flexible content layout, I have: **Field Type:** User **Select multiple values?:** Yes **Return format:** User Array Then in my template I have (most HTML Stripped out): (`role` and `author_image` are ACF fields in the user entry). ``` <?php $posts = get_sub_field('who_to_show'); if( $posts ): foreach( $posts as $post): setup_postdata($post); $user_info = get_userdata($post); $image = get_field('author_image', 'user_' . $user_info->post_author ); $role = get_field('role', 'user_' . $user_info->post_author ); ?> <p><?php echo $role; ?></p> <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /> <?php endforeach; endif; wp_reset_postdata(); ?> ``` I also tried: ``` <?php $posts = get_sub_field('who_to_show'); if( $posts ): foreach( $posts as $post): setup_postdata($post); $image = get_field('author_image'); $role = get_field('role'); ?> <p><?php echo $role; ?></p> <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>" /> <?php endforeach; endif; wp_reset_postdata(); ?> ``` And still my variables are empty. It's worth noting the image field Return Value is set to "Image Array" in ACF. Any pointers in the right direction appreciated.
The solution was only slightly different from Lewis' answer: ``` <?php $posts = get_sub_field('who_to_show'); if( $posts ): foreach( $posts as $post): $userdata = get_user_by('ID',$post['ID']); $image = get_field('author_image', 'user_'. $post['ID'] ); $role = get_field('role', 'user_'. $post['ID'] ); echo $userdata->first_name; echo $role; endforeach; endif; wp_reset_postdata(); ?> ```
312,973
<h2>How Can I Manually Fix &amp; What is The Root Cause?</h2> <p>The <code>Site Language</code> setting in <code>Settings &gt; General</code> for <a href="https://lbryhub.com" rel="nofollow noreferrer">my site</a>, will not update.</p> <p>It is stuck on <code>English (United States)</code>.</p> <p>I have done all the usually debugging procedures, such as disabling all my plugins etc, reinstalling WordPress etc. But the issue remains.</p> <hr> <p><strong>Q:</strong> What is the best way to manually fix this, and what is the root cause of the issue likely to be?</p> <p><a href="https://i.stack.imgur.com/QC4Gl.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QC4Gl.jpg" alt="enter image description here"></a></p> <p><a href="https://i.stack.imgur.com/mLtdN.gif" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mLtdN.gif" alt="enter image description here"></a></p>
[ { "answer_id": 312931, "author": "Lewis Donovan", "author_id": 113034, "author_profile": "https://wordpress.stackexchange.com/users/113034", "pm_score": 1, "selected": false, "text": "<p>You don't actually need to call <code>get_userdata()</code>, all the data you need should be in the relational field array:</p>\n\n<p><strong>EDIT</strong>: Add post ID and User ID to calls to <code>get_field()</code>.</p>\n\n\n\n<pre><code>&lt;?php\n$posts = get_sub_field('who_to_show');\n\n if( $posts ): ?&gt;\n\n &lt;?php foreach( $posts as $post):\n\n setup_postdata($post);\n $user_info = get_field( 'relational_user_field', $post-&gt;ID );\n $image = get_the_field('author_image', 'user_'.$user_info-&gt;ID );\n $role = get_the_field('role', 'user_'.$user_info-&gt;ID );\n ?&gt;\n\n &lt;h3&gt;&lt;?php echo $user_info-&gt;user_nicename; ?&gt;&lt;/h3&gt;\n &lt;img src=\"&lt;?php echo $image['url']; ?&gt;\" alt=\"&lt;?php echo $image['alt']; ?&gt;\" /&gt;\n\n &lt;?php endforeach;\n endif;\n wp_reset_postdata();\n\nendif; ?&gt;\n</code></pre>\n\n<p>Obviously swap <code>'relational_user_field'</code> for your actual field name.\nThe data returned in the user array is the same as the return values in <a href=\"https://codex.wordpress.org/Function_Reference/the_author_meta\" rel=\"nofollow noreferrer\"><code>the_author_meta</code></a></p>\n" }, { "answer_id": 312934, "author": "honk31", "author_id": 10994, "author_profile": "https://wordpress.stackexchange.com/users/10994", "pm_score": 0, "selected": false, "text": "<p>you wrote <code>get_the_field</code>, whilst the proper function to get acf data is <code>get_field</code> or <code>the_field</code> if you want to echo the stuff immediately.. i guess, this breaks your template.</p>\n\n<p>not sure, if i got you right, but if you added the field <code>author_image</code> to the user, than the following answer will get you there. if not, than my answer is crap :)</p>\n\n<p>the proper way of getting acf data from a user would be like this:</p>\n\n<pre><code>get_field('author_image', 'user_' . $user_info-&gt;post_author );\n</code></pre>\n\n<p>when you simply call <code>get_field('parameter')</code> it will return data from the current post, similar to <code>get_field('parameter', get_the_ID())</code>, so if you change that second parameter to whatever ID you have, you could get it from that specific ID.. in case of <code>user</code> it is <code>user_(USER_ID)</code></p>\n" }, { "answer_id": 314131, "author": "user2265915", "author_id": 111367, "author_profile": "https://wordpress.stackexchange.com/users/111367", "pm_score": 1, "selected": true, "text": "<p>The solution was only slightly different from Lewis' answer:</p>\n\n<pre><code>&lt;?php\n $posts = get_sub_field('who_to_show');\n\n if( $posts ):\n\n foreach( $posts as $post):\n\n $userdata = get_user_by('ID',$post['ID']);\n $image = get_field('author_image', 'user_'. $post['ID'] );\n $role = get_field('role', 'user_'. $post['ID'] );\n\n echo $userdata-&gt;first_name;\n echo $role;\n\n endforeach;\n\n endif;\n\nwp_reset_postdata(); ?&gt;\n</code></pre>\n" } ]
2018/08/31
[ "https://wordpress.stackexchange.com/questions/312973", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/148986/" ]
How Can I Manually Fix & What is The Root Cause? ------------------------------------------------ The `Site Language` setting in `Settings > General` for [my site](https://lbryhub.com), will not update. It is stuck on `English (United States)`. I have done all the usually debugging procedures, such as disabling all my plugins etc, reinstalling WordPress etc. But the issue remains. --- **Q:** What is the best way to manually fix this, and what is the root cause of the issue likely to be? [![enter image description here](https://i.stack.imgur.com/QC4Gl.jpg)](https://i.stack.imgur.com/QC4Gl.jpg) [![enter image description here](https://i.stack.imgur.com/mLtdN.gif)](https://i.stack.imgur.com/mLtdN.gif)
The solution was only slightly different from Lewis' answer: ``` <?php $posts = get_sub_field('who_to_show'); if( $posts ): foreach( $posts as $post): $userdata = get_user_by('ID',$post['ID']); $image = get_field('author_image', 'user_'. $post['ID'] ); $role = get_field('role', 'user_'. $post['ID'] ); echo $userdata->first_name; echo $role; endforeach; endif; wp_reset_postdata(); ?> ```
312,975
<p>I have a custom filed called <code>xxxx_url</code>. <code>xxxx_url</code> should be unique.</p> <p>So, before publishing the post, I want to make sure that <code>xxxx_url</code> is unique or not? If it isn't unique, publishing the post should be reject.</p> <p>I tried <code>publish_post</code>. But that isn't the correct one, since it triggers when we publish the post. I want to run my code just before the publish.</p>
[ { "answer_id": 313225, "author": "Petr Cibulka", "author_id": 28718, "author_profile": "https://wordpress.stackexchange.com/users/28718", "pm_score": -1, "selected": false, "text": "<p>The check should go to <code>wp_insert_post</code>. This hook is fired whenever post is published or edited.</p>\n\n<p>There, you can do a custom query to check, if there is any post already has the same <code>xxxx_url</code> value or not.</p>\n\n<pre><code>add_action('wp_insert_post', function($post_id) {\n $meta_key = 'xxxx_url';\n $meta_value = get_post_meta($post_id, $meta_key, true);\n $query = new WP_Query([\n 'post_type' =&gt; get_post_type($post_id), // This might be unnecessary, if you check `post` post type only. Or use `any`.\n 'meta_query' =&gt; [\n [\n 'meta_key' =&gt; $meta_key,\n 'meta_value' =&gt; $meta_value,\n ]\n ]\n ]);\n if ($query-&gt;have_posts()) {\n // invalid key, post with the same value already exists\n } else {\n // valid, key was not found anywhere\n }\n});\n</code></pre>\n" }, { "answer_id": 313237, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 1, "selected": false, "text": "<p>I would hook into <a href=\"https://developer.wordpress.org/reference/hooks/wp_insert_post_data/\" rel=\"nofollow noreferrer\">wp_insert_post_data</a> filter and handle this as less intrusive as possible because as I understand you don't want to block the insertion of a post, you just want to avoid publishing a post with duplicate meta values.</p>\n\n<p>I cannot spare too much in this case because you didn't share any code but here is some pseudo-code of a filter that would work:</p>\n\n<pre><code>function wp8193131_check_if_meta_value_is_unique ( $data, $postarr ) {\n // setup an uniqueness flag.\n $meta_is_unique = true;\n\n // check if the meta is unique and modify the `$meta_is_unique` flag accordingly.\n // {...} &lt;- your code\n\n // if the meta is NOT unique keep the post status in draft.\n if ( ! $meta_is_unique ) {\n // you can force the current post to be draft until the meta value will became unique.\n $data['post_status'] = 'draft';\n // maybe, update the meta value with a hint of the fact that it's not unique.\n // or display a dashboard notice about it.\n }\n\n return $data;\n}\nadd_filter( 'wp_insert_post_data', 'wp8193131_check_if_meta_value_is_unique' );\n</code></pre>\n\n<p>Another great thing about this filter is that it's separated from the attachments one <code>wp_insert_attachment_data</code>.</p>\n\n<p>I hope it helps, and whatever you do, it sounds awesome!</p>\n" }, { "answer_id": 313716, "author": "cjbj", "author_id": 75495, "author_profile": "https://wordpress.stackexchange.com/users/75495", "pm_score": 4, "selected": true, "text": "<p>At the beginning of <a href=\"https://developer.wordpress.org/reference/functions/wp_insert_post/\" rel=\"noreferrer\"><code>wp_insert_post</code></a>, the function that saves/updates a post, there is a filter called <a href=\"https://developer.wordpress.org/reference/hooks/wp_insert_post_empty_content/\" rel=\"noreferrer\"><code>wp_insert_post_empty_content</code></a>. By default this filter checks whether the title, editor, and excerpt fields are all empty, in which case the save process will be halted.</p>\n\n<p>However, since all the fields to be saved are passed to this filter, you can expand this filter to include any other test to determine whether the post should be considered empty. It would be something like this:</p>\n\n<pre><code>add_filter ('wp_insert_post_empty_content','wpse312975_check_unique_url',10,2);\nfunction wpse312975_check_unique_url ($maybe_empty, $postarr) {\n\n // extract custom field from $postarr, check uniqueness\n\n if ($unique) return false else return true;\n }\n</code></pre>\n\n<p>Note: the function must return 'true' to halt the saving process.</p>\n\n<p>If the custom field is not unique you may also want to echo a warning.</p>\n" }, { "answer_id": 313744, "author": "Abhik", "author_id": 26991, "author_profile": "https://wordpress.stackexchange.com/users/26991", "pm_score": 1, "selected": false, "text": "<p>How about using AJAX to check the uniqueness before even submitting the post for publishing? </p>\n\n<pre><code>$( '#post' ).on( 'submit', function( event ) {\n event.preventDefault(); // Prevent publishing\n\n //Now do some AJAX Checks\n $.post( ajaxurl, data, function(response) {\n if ( response === 'success' ) {\n $( this ).off( event ).submit();\n } else {\n alert( 'The custom field must be unique' );\n }\n });\n}); \n</code></pre>\n\n<p>Though the code isn't tested, but it should work. You might need to play with it to get your desired result.</p>\n" } ]
2018/08/31
[ "https://wordpress.stackexchange.com/questions/312975", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/123092/" ]
I have a custom filed called `xxxx_url`. `xxxx_url` should be unique. So, before publishing the post, I want to make sure that `xxxx_url` is unique or not? If it isn't unique, publishing the post should be reject. I tried `publish_post`. But that isn't the correct one, since it triggers when we publish the post. I want to run my code just before the publish.
At the beginning of [`wp_insert_post`](https://developer.wordpress.org/reference/functions/wp_insert_post/), the function that saves/updates a post, there is a filter called [`wp_insert_post_empty_content`](https://developer.wordpress.org/reference/hooks/wp_insert_post_empty_content/). By default this filter checks whether the title, editor, and excerpt fields are all empty, in which case the save process will be halted. However, since all the fields to be saved are passed to this filter, you can expand this filter to include any other test to determine whether the post should be considered empty. It would be something like this: ``` add_filter ('wp_insert_post_empty_content','wpse312975_check_unique_url',10,2); function wpse312975_check_unique_url ($maybe_empty, $postarr) { // extract custom field from $postarr, check uniqueness if ($unique) return false else return true; } ``` Note: the function must return 'true' to halt the saving process. If the custom field is not unique you may also want to echo a warning.
312,988
<p>I am currently using a Hesita Child Theme. I want to edit the copyright text in the footer. </p> <p>I have found the text I need to edit in 'hestia/inc/views/main/class-hestia-footer.php'</p> <p>I think know what code to edit, however, I do not know how to make that change in the child theme. I have changed it before, but it has been reverted back to the original after a parent update. </p> <p>Can anyone help?</p> <p>Cheers</p>
[ { "answer_id": 312990, "author": "Quang Hoang", "author_id": 134874, "author_profile": "https://wordpress.stackexchange.com/users/134874", "pm_score": -1, "selected": false, "text": "<p>In the child-theme, you must duplicate a file class-hestia-footer.php like as parent-theme and edit file in child-theme.</p>\n" }, { "answer_id": 312993, "author": "bueltge", "author_id": 170, "author_profile": "https://wordpress.stackexchange.com/users/170", "pm_score": 1, "selected": false, "text": "<p>The default Footer content of the parent theme Hestia is included via Hook <code>hestia_do_bottom_footer_content</code>. So you can remove them via <a href=\"https://codex.wordpress.org/Function_Reference/remove_action\" rel=\"nofollow noreferrer\"><code>remove_action</code></a>. and add your own content, own function in your child theme.</p>\n\n<p>Source in the parent theme to valid this hook, file <code>hestia\\inc\\views\\main\\class-hestia-footer.php</code>:</p>\n\n<pre><code>/**\n * Initialization of the feature.\n */\npublic function init() {\n add_action( 'hestia_do_footer', array( $this, 'the_footer_content' ) );\n add_filter( 'wp_nav_menu_args', array( $this, 'modify_footer_menu_classes' ) );\n add_action( 'hestia_do_bottom_footer_content', array( $this, 'bottom_footer_content' ) );\n}\n</code></pre>\n\n<p>The content is inside this method:</p>\n\n<pre><code>/**\n * Function to display footer copyright and footer menu.\n * Also used as callback for selective refresh.\n */\npublic function bottom_footer_content() {\n $hestia_general_credits = get_theme_mod(\n 'hestia_general_credits',\n sprintf(\n /* translators: %1$s is Theme Name, %2$s is WordPress */\n esc_html__( '%1$s | Powered by %2$s', 'hestia' ),\n sprintf(\n /* translators: %s is Theme name */\n '&lt;a href=\"https://themeisle.com/themes/hestia/\" target=\"_blank\" rel=\"nofollow\"&gt;%s&lt;/a&gt;',\n esc_html__( 'Hestia', 'hestia' )\n ),\n /* translators: %1$s is URL, %2$s is WordPress */\n sprintf(\n '&lt;a href=\"%1$s\" rel=\"nofollow\"&gt;%2$s&lt;/a&gt;',\n esc_url( __( 'http://wordpress.org', 'hestia' ) ),\n esc_html__( 'WordPress', 'hestia' )\n )\n )\n );\n\n wp_nav_menu(\n array(\n 'theme_location' =&gt; 'footer',\n 'depth' =&gt; 1,\n 'container' =&gt; 'ul',\n 'menu_class' =&gt; 'footer-menu',\n )\n );\n ?&gt;\n &lt;?php if ( ! empty( $hestia_general_credits ) || is_customize_preview() ) : ?&gt;\n &lt;div class=\"copyright &lt;?php echo esc_attr( $this-&gt;add_footer_copyright_alignment_class() ); ?&gt;\"&gt;\n &lt;?php echo wp_kses_post( $hestia_general_credits ); ?&gt;\n &lt;/div&gt;\n &lt;?php\n endif;\n}\n</code></pre>\n" }, { "answer_id": 312996, "author": "Andrei", "author_id": 26395, "author_profile": "https://wordpress.stackexchange.com/users/26395", "pm_score": 0, "selected": false, "text": "<p>If you are interested in editing the copyright and not removing it I would recommend using the <a href=\"https://developer.wordpress.org/reference/hooks/theme_mod_name/\" rel=\"nofollow noreferrer\">theme_mod filter</a>. Just play with the <code>$new_credits</code> variable in the example below which works in the child functions.php file.</p>\n\n<pre><code>function wp739534_change_hestia_copyright( $old_credits ){\n\n $new_credits = sprintf(\n /* translators: %1$s is Theme Name, %2$s is WordPress */\n esc_html__( '%1$s | Powered by %2$s', 'hestia-pro' ),\n sprintf(\n /* translators: %s is Theme name */\n '&lt;a href=\"https://themeisle.com/themes/hestia/\" target=\"_blank\" rel=\"nofollow\"&gt;%s&lt;/a&gt;',\n esc_html__( 'Hestia', 'hestia-pro' )\n ),\n /* translators: %1$s is URL, %2$s is WordPress */\n sprintf(\n '&lt;a href=\"%1$s\" rel=\"nofollow\"&gt;%2$s&lt;/a&gt;',\n esc_url( __( 'http://wordpress.org', 'hestia-pro' ) ),\n esc_html__( 'WordPress', 'hestia-pro' )\n )\n );\n\n return $new_credits;\n}\nadd_filter( 'theme_mod_hestia_general_credits', 'wp739534_change_hestia_copyright' );\n</code></pre>\n" }, { "answer_id": 312999, "author": "Electron", "author_id": 148986, "author_profile": "https://wordpress.stackexchange.com/users/148986", "pm_score": 1, "selected": true, "text": "<h2>You Could Also Try This Cheeky Little Trick :)</h2>\n\n<p>If you just want a quick and easy, no fuss change, you can do this to the <a href=\"https://themeisle.com/demo/?theme=Hestia\" rel=\"nofollow noreferrer\">Hestia</a> theme copyright area.</p>\n\n<p>Just add the following code to your child theme CSS or to the WordPress Customise > CSS area.</p>\n\n<pre><code>.copyright a {\n display: none;\n}\n.copyright:before {\n content: \"My site\";\n}\n.copyright:after {\n content: \" Craig\";\n}\n</code></pre>\n\n<p>Alternatively, you could just hide it all.</p>\n\n<pre><code>.copyright {\n display: none;\n}\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/YB7LQ.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/YB7LQ.jpg\" alt=\"enter image description here\"></a></p>\n" } ]
2018/08/31
[ "https://wordpress.stackexchange.com/questions/312988", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149738/" ]
I am currently using a Hesita Child Theme. I want to edit the copyright text in the footer. I have found the text I need to edit in 'hestia/inc/views/main/class-hestia-footer.php' I think know what code to edit, however, I do not know how to make that change in the child theme. I have changed it before, but it has been reverted back to the original after a parent update. Can anyone help? Cheers
You Could Also Try This Cheeky Little Trick :) ---------------------------------------------- If you just want a quick and easy, no fuss change, you can do this to the [Hestia](https://themeisle.com/demo/?theme=Hestia) theme copyright area. Just add the following code to your child theme CSS or to the WordPress Customise > CSS area. ``` .copyright a { display: none; } .copyright:before { content: "My site"; } .copyright:after { content: " Craig"; } ``` Alternatively, you could just hide it all. ``` .copyright { display: none; } ``` [![enter image description here](https://i.stack.imgur.com/YB7LQ.jpg)](https://i.stack.imgur.com/YB7LQ.jpg)
313,015
<p>I'm developing a system where I have a Deck presentation.<br> I have a field that takes the post by the 'copas' type of card being within the 'meta_value' array specification, and I would like it to be sorted exactly as it is in the array:</p> <pre><code>array('K','Q','J','10','9','8','7','6','5','4','3','2'), </code></pre> <p>But the next order is: </p> <pre><code>'10','9','8','7','6','5','4','3','2','J','Q','K' </code></pre> <p>I do not know how to do it, can you help me?</p> <pre><code>$args = array( 'post_type' =&gt; 'copas', 'posts_per_page' =&gt; '12', 'meta_key' =&gt; 'dbt_carta', 'meta_value' =&gt; array('K','Q','J','10','9','8','7','6','5','4','3','2'), 'compare' =&gt; 'LIKE', 'orderby' =&gt; 'meta_value_num', 'order' =&gt; 'DESC' ); // A Query $cartas = new WP_Query( $args ); </code></pre> <p>Remember that I need it to be in this order, because then another filter will come in $ args, because the cards will have an Active / Inactive status, and they must always remain in the order of the array and not in the order of the post.</p> <hr> <blockquote> <p>It worked perfectly as indicated by @PatJ, I am grateful for everyone's help! <strong>Below the result</strong> </p> </blockquote> <p><strong>This is my meta-box-field:</strong></p> <pre><code>array( //Texto referente ao campo | ponto (N) 'name' =&gt; 'Carta', //Texto de exemplo 'desc' =&gt; 'Selecione a Carta', //SEMPRE MUDE - Nome registrado no Banco de dados 'id' =&gt; $prefix . 'carta', //NÃO MUDE 'type' =&gt; 'select', 'options' =&gt; array('A','K','Q','J','10','9','8','7','6','5','4','3','2') ) </code></pre> <p><strong>This is the part of the code where I look for the post of the letters and I present on the screen:</strong> </p> <pre><code>&lt;ul id="wpbgallery" class="clearfix"&gt; &lt;?php $contador = 1 ; ?&gt; &lt;li class="carta-as" style="justify-content: center;"&gt; &lt;!-- inicio do loop --&gt; &lt;?php // Os argumentos $args_A = array( 'post_type' =&gt; 'copas', 'posts_per_page' =&gt; '1', 'meta_key' =&gt; 'dbt_carta', 'meta_value' =&gt; 'A' ); // A Query $carta_as = new WP_Query( $args_A ); // O Loop while ( $carta_as-&gt;have_posts() ) : $carta_as-&gt;the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'single-post-thumbnail' ); ?&gt; &lt;a href="&lt;?php echo $image[0]; ?&gt;" title="&lt;?php the_title(); ?&gt;" data-gallery=""&gt; &lt;?php the_post_thumbnail("baralho"); ?&gt; &lt;/a&gt; &lt;?php endwhile; ?&gt; &lt;!-- fim do loop --&gt; &lt;/li&gt; &lt;br&gt; &lt;li class="cartas"&gt; &lt;!-- inicio do loop --&gt; &lt;?php $args = array( 'post_type' =&gt; 'copas', 'posts_per_page' =&gt; '12', 'meta_key' =&gt; 'dbt_carta', 'meta_value' =&gt; array('K','Q','J','10','9','8','7','6','5','4','3','2'), 'compare' =&gt; 'LIKE' ); // A Query $cartas = new WP_Query( $args ); usort( $cartas-&gt;posts, 'sort_cartas' ); function sort_cartas( $a, $b ) { $single = true; $a_dbt_carta = get_post_meta( $a-&gt;ID, 'dbt_carta', $single ); $b_dbt_carta = get_post_meta( $b-&gt;ID, 'dbt_carta', $single ); // If they're the same, don't worry about sorting. if ( $a_dbt_carta == $b_dbt_carta ) { return 0; } // Converts 'K', 'Q', and 'J' to numbers, for easier comparisons. $face_card_numbers = array( 'K' =&gt; 13, 'Q' =&gt; 12, 'J' =&gt; 11 ); if ( in_array( $a_dbt_carta, array_keys( $face_card_numbers ) ) ) { $a_dbt_carta = $face_card_numbers[ $a_dbt_carta ]; } if ( in_array( $b_dbt_carta, array_keys( $face_card_numbers ) ) ) { $b_dbt_carta = $face_card_numbers[ $b_dbt_carta ]; } if ( $a_dbt_carta &gt; $b_dbt_carta ) { return -1; } return 1; } if ($cartas-&gt;have_posts()) : while ($cartas-&gt;have_posts()) : $cartas-&gt;the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post-&gt;ID ), 'single-post-thumbnail' ); ?&gt; &lt;a href="&lt;?php echo $image[0]; ?&gt;" title="&lt;?php the_title(); ?&gt;" data-gallery=""&gt; &lt;?php the_post_thumbnail("baralho"); ?&gt; &lt;/a&gt; &lt;?php if($contador == 4): ?&gt; &lt;/li&gt; &lt;li class="cartas"&gt; &lt;?php endif; $contador++; ?&gt; &lt;?php endwhile; ?&gt; &lt;?php else : ?&gt; &lt;p class="text-center"&gt;Não existe conteúdo aqui!&lt;/p&gt; &lt;?php endif; ?&gt; &lt;/ul&gt; </code></pre> <p><strong>This is a representation of the result I'm getting, exactly what I wanted (PS: I can not show the print of the original screen since each card has sensitive and restricted data):</strong><br> <a href="https://i.stack.imgur.com/4BjU2.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4BjU2.png" alt="enter image description here"></a></p>
[ { "answer_id": 313017, "author": "Peter HvD", "author_id": 134918, "author_profile": "https://wordpress.stackexchange.com/users/134918", "pm_score": 0, "selected": false, "text": "<p>You are misunderstanding the use of<code>'meta_value'</code>. It is used to tell the query what you want to search for, not the order it should be in. </p>\n\n<p>I would suggest that you change your internal card values in <code>dbt_carta</code> to 13 for K, 12 for Q and 11 for J. It will then be a simple numeric sort.</p>\n" }, { "answer_id": 313018, "author": "Pat J", "author_id": 16121, "author_profile": "https://wordpress.stackexchange.com/users/16121", "pm_score": 2, "selected": true, "text": "<p>Looking at the <a href=\"https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters\" rel=\"nofollow noreferrer\"><code>orderby</code></a> parameter on <code>WP_Query</code>, I don't see any way to do this. You could (as Peter HvD suggests in his answer) convert your face cards to numbers; but if you want to keep the <code>K|Q|J</code> values, I'd recommend using a <a href=\"https://php.net/usort\" rel=\"nofollow noreferrer\"><code>usort()</code></a> callback:</p>\n\n<pre><code>// Assuming that $cartas-&gt;posts contains your posts\nusort( $carta-&gt;posts, 'wpse313015_sort_cartas' );\n\n// ...\n\nfunction wpse313015_sort_cartas( $a, $b ) {\n $single = true;\n $a_dbt_carta = get_post_meta( $a-&gt;ID, 'dbt_carta', $single );\n $b_dbt_carta = get_post_meta( $b-&gt;ID, 'dbt_carta', $single );\n // If they're the same, don't worry about sorting.\n if ( $a_dbt_carta == $b_dbt_carta ) {\n return 0;\n }\n // Converts 'K', 'Q', and 'J' to numbers, for easier comparisons.\n $face_card_numbers = array( 'K' =&gt; 13, 'Q' =&gt; 12, 'J' = 11 );\n if ( in_array( $a_dbt_carta, array_keys( $face_card_numbers ) ) ) {\n $a_dbt_carta = $face_card_numbers[ $a_dbt_carta ];\n }\n if ( in_array( $b_dbt_carta, array_keys( $face_card_numbers ) ) ) {\n $b_dbt_carta = $face_card_numbers[ $b_dbt_carta ];\n }\n if ( $a_dbt_carta &gt; $b_dbt_carta ) {\n return -1;\n }\n return 1;\n}\n</code></pre>\n\n<p>This code is untested. You'll probably need to make changes to it to fit your particular needs.</p>\n" } ]
2018/08/31
[ "https://wordpress.stackexchange.com/questions/313015", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149751/" ]
I'm developing a system where I have a Deck presentation. I have a field that takes the post by the 'copas' type of card being within the 'meta\_value' array specification, and I would like it to be sorted exactly as it is in the array: ``` array('K','Q','J','10','9','8','7','6','5','4','3','2'), ``` But the next order is: ``` '10','9','8','7','6','5','4','3','2','J','Q','K' ``` I do not know how to do it, can you help me? ``` $args = array( 'post_type' => 'copas', 'posts_per_page' => '12', 'meta_key' => 'dbt_carta', 'meta_value' => array('K','Q','J','10','9','8','7','6','5','4','3','2'), 'compare' => 'LIKE', 'orderby' => 'meta_value_num', 'order' => 'DESC' ); // A Query $cartas = new WP_Query( $args ); ``` Remember that I need it to be in this order, because then another filter will come in $ args, because the cards will have an Active / Inactive status, and they must always remain in the order of the array and not in the order of the post. --- > > It worked perfectly as indicated by @PatJ, I am grateful for > everyone's help! **Below the result** > > > **This is my meta-box-field:** ``` array( //Texto referente ao campo | ponto (N) 'name' => 'Carta', //Texto de exemplo 'desc' => 'Selecione a Carta', //SEMPRE MUDE - Nome registrado no Banco de dados 'id' => $prefix . 'carta', //NÃO MUDE 'type' => 'select', 'options' => array('A','K','Q','J','10','9','8','7','6','5','4','3','2') ) ``` **This is the part of the code where I look for the post of the letters and I present on the screen:** ``` <ul id="wpbgallery" class="clearfix"> <?php $contador = 1 ; ?> <li class="carta-as" style="justify-content: center;"> <!-- inicio do loop --> <?php // Os argumentos $args_A = array( 'post_type' => 'copas', 'posts_per_page' => '1', 'meta_key' => 'dbt_carta', 'meta_value' => 'A' ); // A Query $carta_as = new WP_Query( $args_A ); // O Loop while ( $carta_as->have_posts() ) : $carta_as->the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> <a href="<?php echo $image[0]; ?>" title="<?php the_title(); ?>" data-gallery=""> <?php the_post_thumbnail("baralho"); ?> </a> <?php endwhile; ?> <!-- fim do loop --> </li> <br> <li class="cartas"> <!-- inicio do loop --> <?php $args = array( 'post_type' => 'copas', 'posts_per_page' => '12', 'meta_key' => 'dbt_carta', 'meta_value' => array('K','Q','J','10','9','8','7','6','5','4','3','2'), 'compare' => 'LIKE' ); // A Query $cartas = new WP_Query( $args ); usort( $cartas->posts, 'sort_cartas' ); function sort_cartas( $a, $b ) { $single = true; $a_dbt_carta = get_post_meta( $a->ID, 'dbt_carta', $single ); $b_dbt_carta = get_post_meta( $b->ID, 'dbt_carta', $single ); // If they're the same, don't worry about sorting. if ( $a_dbt_carta == $b_dbt_carta ) { return 0; } // Converts 'K', 'Q', and 'J' to numbers, for easier comparisons. $face_card_numbers = array( 'K' => 13, 'Q' => 12, 'J' => 11 ); if ( in_array( $a_dbt_carta, array_keys( $face_card_numbers ) ) ) { $a_dbt_carta = $face_card_numbers[ $a_dbt_carta ]; } if ( in_array( $b_dbt_carta, array_keys( $face_card_numbers ) ) ) { $b_dbt_carta = $face_card_numbers[ $b_dbt_carta ]; } if ( $a_dbt_carta > $b_dbt_carta ) { return -1; } return 1; } if ($cartas->have_posts()) : while ($cartas->have_posts()) : $cartas->the_post(); $image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'single-post-thumbnail' ); ?> <a href="<?php echo $image[0]; ?>" title="<?php the_title(); ?>" data-gallery=""> <?php the_post_thumbnail("baralho"); ?> </a> <?php if($contador == 4): ?> </li> <li class="cartas"> <?php endif; $contador++; ?> <?php endwhile; ?> <?php else : ?> <p class="text-center">Não existe conteúdo aqui!</p> <?php endif; ?> </ul> ``` **This is a representation of the result I'm getting, exactly what I wanted (PS: I can not show the print of the original screen since each card has sensitive and restricted data):** [![enter image description here](https://i.stack.imgur.com/4BjU2.png)](https://i.stack.imgur.com/4BjU2.png)
Looking at the [`orderby`](https://developer.wordpress.org/reference/classes/wp_query/#order-orderby-parameters) parameter on `WP_Query`, I don't see any way to do this. You could (as Peter HvD suggests in his answer) convert your face cards to numbers; but if you want to keep the `K|Q|J` values, I'd recommend using a [`usort()`](https://php.net/usort) callback: ``` // Assuming that $cartas->posts contains your posts usort( $carta->posts, 'wpse313015_sort_cartas' ); // ... function wpse313015_sort_cartas( $a, $b ) { $single = true; $a_dbt_carta = get_post_meta( $a->ID, 'dbt_carta', $single ); $b_dbt_carta = get_post_meta( $b->ID, 'dbt_carta', $single ); // If they're the same, don't worry about sorting. if ( $a_dbt_carta == $b_dbt_carta ) { return 0; } // Converts 'K', 'Q', and 'J' to numbers, for easier comparisons. $face_card_numbers = array( 'K' => 13, 'Q' => 12, 'J' = 11 ); if ( in_array( $a_dbt_carta, array_keys( $face_card_numbers ) ) ) { $a_dbt_carta = $face_card_numbers[ $a_dbt_carta ]; } if ( in_array( $b_dbt_carta, array_keys( $face_card_numbers ) ) ) { $b_dbt_carta = $face_card_numbers[ $b_dbt_carta ]; } if ( $a_dbt_carta > $b_dbt_carta ) { return -1; } return 1; } ``` This code is untested. You'll probably need to make changes to it to fit your particular needs.
313,090
<p>I'm working on a project where we'll be creating two different custom post types: <em>Machines</em> and <em>Enquiries</em>. The Machines posts will be created by admin, and will simply be a list of items that are for sale (although this isn't an e-commerce site). Enquiries, however, will be created by users via a form displayed on the front-end. When a user submits an enquiry, they must select whether they want to buy or sell - if they are buying they must then also specify a machine.</p> <p>The client has expressed that they would like to be able to see which machine the enquiry relates to in both the Enquiries admin columns, and in the Enquiries edit pages. This would obviously be non-editable, but it could be the Machine post title, SKU, or a link to either the Machine edit page or front-end - or any combination thereof.</p> <hr> <p>So my question is:</p> <p>When creating and saving an Enquiry post type, is there a way to query the Machines post types (i.e. the Machine submitted with the user's enquiry) and, with that Machines's row data, add a field to the Enquiry post that can then be displayed on the enquiry edit page, or admin columns?</p>
[ { "answer_id": 313094, "author": "jdp", "author_id": 115910, "author_profile": "https://wordpress.stackexchange.com/users/115910", "pm_score": 1, "selected": false, "text": "<p>I think your answer lies with adding metadata on the Machine post type that links back to the Enquiry post. Your form on the Enquiries page would have a select field with all the machines available for purchase. The value of each option in the select control would be the ID of the Machine post. </p>\n\n<p>When the user submits the form, save the Enquiery Post ID as meta key/value for the Machine post. I'll use the string <code>machine_enquiry</code> as the meta key. </p>\n\n<pre><code>add_post_meta($machine_post_id, 'machine_enquiry', $enquiry_post_id);\n</code></pre>\n\n<p>This will give you an array of enquiries for each machine in the Machine post as it seems you may have multiple enquiries for each machine.</p>\n\n<p>You might also get some benefit from putting the Machine post ID in the meta for the Enquiry post. This will work as long as you don't allow enquiries for multiple machines.</p>\n\n<pre><code>update_post_meta($enquiry_post_id, 'machine_enquiry', $machine_post_id);\n</code></pre>\n" }, { "answer_id": 313116, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Add a field to your form that allows selection of a <code>machine</code>. You can use <code>get_posts</code> to generate a <code>select</code> element:</p>\n\n<pre><code>$args = [\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'machine'\n];\n$machines = get_posts( $args );\nif( ! empty( $machines ) ){\n echo '&lt;select name=\"_machine_id\"&gt;';\n foreach( $machines as $machine ){\n echo '&lt;option value=\"' . $machine-&gt;ID . '\" &gt;' . get_the_title( $machine ) . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n}\n</code></pre>\n\n<p>Save that value in post meta for the <code>enquiry</code> post under the key <code>_machine_id</code>.</p>\n\n<p>To add a Machine column to the <code>enquiry</code> post type list screen, use the <code>manage_$post_type_posts_columns</code> filter:</p>\n\n<pre><code>function wpd_enquiry_posts_columns( $columns ) {\n $columns['machine'] = 'Machine';\n return $columns;\n}\nadd_filter( 'manage_enquiry_posts_columns', 'wpd_enquiry_posts_columns' );\n</code></pre>\n\n<p>Next, use the <code>manage_$post_type_posts_custom_column</code> action to output a value in that column for each post:</p>\n\n<pre><code>function wpd_enquiry_column( $column, $post_id ) {\n if ( 'machine' === $column ) {\n // get the machine ID saved in meta\n $machine_id = get_post_meta( $post_id, '_machine_id', true );\n if( $machine_id ){\n // get the machine post\n $machine = get_post( $machine_id );\n if( is_object( $machine ) ){\n echo get_the_title( $machine );\n }\n } else {\n echo 'none';\n }\n }\n}\nadd_action( 'manage_enquiry_posts_custom_column', 'wpd_enquiry_column', 10, 2 );\n</code></pre>\n\n<p>For the individual <code>enquiry</code> post edit screens, you can add a meta box to display the machine. Here we add a meta box:</p>\n\n<pre><code>function wpd_machine_meta_box() {\n add_meta_box( 'machine-id', 'Machine', 'wpd_display_machine_meta_box', 'enquiry' );\n}\nadd_action( 'add_meta_boxes', 'wpd_machine_meta_box' );\n</code></pre>\n\n<p>And then the display function for the meta box:</p>\n\n<pre><code>function wpd_display_machine_meta_box( $post ) {\n $machine_id = get_post_meta( $post-&gt;ID, '_machine_id', true );\n if( $machine_id ){\n $machine = get_post( $machine_id );\n if( is_object( $machine ) ){\n echo get_the_title( $machine );\n }\n } else {\n echo 'none';\n }\n}\n</code></pre>\n\n<p>Here we have just a simple display of a static value, you can also generate a form field in your meta box, like the first function above, and hook <code>post_save</code> to allow the admin to update the value.</p>\n" } ]
2018/09/01
[ "https://wordpress.stackexchange.com/questions/313090", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/60225/" ]
I'm working on a project where we'll be creating two different custom post types: *Machines* and *Enquiries*. The Machines posts will be created by admin, and will simply be a list of items that are for sale (although this isn't an e-commerce site). Enquiries, however, will be created by users via a form displayed on the front-end. When a user submits an enquiry, they must select whether they want to buy or sell - if they are buying they must then also specify a machine. The client has expressed that they would like to be able to see which machine the enquiry relates to in both the Enquiries admin columns, and in the Enquiries edit pages. This would obviously be non-editable, but it could be the Machine post title, SKU, or a link to either the Machine edit page or front-end - or any combination thereof. --- So my question is: When creating and saving an Enquiry post type, is there a way to query the Machines post types (i.e. the Machine submitted with the user's enquiry) and, with that Machines's row data, add a field to the Enquiry post that can then be displayed on the enquiry edit page, or admin columns?
Add a field to your form that allows selection of a `machine`. You can use `get_posts` to generate a `select` element: ``` $args = [ 'posts_per_page' => -1, 'post_type' => 'machine' ]; $machines = get_posts( $args ); if( ! empty( $machines ) ){ echo '<select name="_machine_id">'; foreach( $machines as $machine ){ echo '<option value="' . $machine->ID . '" >' . get_the_title( $machine ) . '</option>'; } echo '</select>'; } ``` Save that value in post meta for the `enquiry` post under the key `_machine_id`. To add a Machine column to the `enquiry` post type list screen, use the `manage_$post_type_posts_columns` filter: ``` function wpd_enquiry_posts_columns( $columns ) { $columns['machine'] = 'Machine'; return $columns; } add_filter( 'manage_enquiry_posts_columns', 'wpd_enquiry_posts_columns' ); ``` Next, use the `manage_$post_type_posts_custom_column` action to output a value in that column for each post: ``` function wpd_enquiry_column( $column, $post_id ) { if ( 'machine' === $column ) { // get the machine ID saved in meta $machine_id = get_post_meta( $post_id, '_machine_id', true ); if( $machine_id ){ // get the machine post $machine = get_post( $machine_id ); if( is_object( $machine ) ){ echo get_the_title( $machine ); } } else { echo 'none'; } } } add_action( 'manage_enquiry_posts_custom_column', 'wpd_enquiry_column', 10, 2 ); ``` For the individual `enquiry` post edit screens, you can add a meta box to display the machine. Here we add a meta box: ``` function wpd_machine_meta_box() { add_meta_box( 'machine-id', 'Machine', 'wpd_display_machine_meta_box', 'enquiry' ); } add_action( 'add_meta_boxes', 'wpd_machine_meta_box' ); ``` And then the display function for the meta box: ``` function wpd_display_machine_meta_box( $post ) { $machine_id = get_post_meta( $post->ID, '_machine_id', true ); if( $machine_id ){ $machine = get_post( $machine_id ); if( is_object( $machine ) ){ echo get_the_title( $machine ); } } else { echo 'none'; } } ``` Here we have just a simple display of a static value, you can also generate a form field in your meta box, like the first function above, and hook `post_save` to allow the admin to update the value.
313,118
<p>I am looking for the function to change position the price for the category. (I attached an image). Ok, is not a switch is a remove and add.</p> <p>¿Where i can find a good explanation about the php function and the list of it?,will be awesome if somebody know a good explanation of the structure too.</p> <p>Because Codex from <a href="https://docs.woocommerce.com/documentation/plugins/woocommerce/woocommerce-codex/" rel="nofollow noreferrer">Woocommerce</a> and <a href="https://codex.wordpress.org/" rel="nofollow noreferrer">Wordpress</a> there isn't all of it.</p> <p><a href="https://i.stack.imgur.com/tiMRE.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tiMRE.jpg" alt="enter image description here"></a></p> <p>Thanks in advanced!!</p> <p>Regards!</p>
[ { "answer_id": 313094, "author": "jdp", "author_id": 115910, "author_profile": "https://wordpress.stackexchange.com/users/115910", "pm_score": 1, "selected": false, "text": "<p>I think your answer lies with adding metadata on the Machine post type that links back to the Enquiry post. Your form on the Enquiries page would have a select field with all the machines available for purchase. The value of each option in the select control would be the ID of the Machine post. </p>\n\n<p>When the user submits the form, save the Enquiery Post ID as meta key/value for the Machine post. I'll use the string <code>machine_enquiry</code> as the meta key. </p>\n\n<pre><code>add_post_meta($machine_post_id, 'machine_enquiry', $enquiry_post_id);\n</code></pre>\n\n<p>This will give you an array of enquiries for each machine in the Machine post as it seems you may have multiple enquiries for each machine.</p>\n\n<p>You might also get some benefit from putting the Machine post ID in the meta for the Enquiry post. This will work as long as you don't allow enquiries for multiple machines.</p>\n\n<pre><code>update_post_meta($enquiry_post_id, 'machine_enquiry', $machine_post_id);\n</code></pre>\n" }, { "answer_id": 313116, "author": "Milo", "author_id": 4771, "author_profile": "https://wordpress.stackexchange.com/users/4771", "pm_score": 3, "selected": true, "text": "<p>Add a field to your form that allows selection of a <code>machine</code>. You can use <code>get_posts</code> to generate a <code>select</code> element:</p>\n\n<pre><code>$args = [\n 'posts_per_page' =&gt; -1,\n 'post_type' =&gt; 'machine'\n];\n$machines = get_posts( $args );\nif( ! empty( $machines ) ){\n echo '&lt;select name=\"_machine_id\"&gt;';\n foreach( $machines as $machine ){\n echo '&lt;option value=\"' . $machine-&gt;ID . '\" &gt;' . get_the_title( $machine ) . '&lt;/option&gt;';\n }\n echo '&lt;/select&gt;';\n}\n</code></pre>\n\n<p>Save that value in post meta for the <code>enquiry</code> post under the key <code>_machine_id</code>.</p>\n\n<p>To add a Machine column to the <code>enquiry</code> post type list screen, use the <code>manage_$post_type_posts_columns</code> filter:</p>\n\n<pre><code>function wpd_enquiry_posts_columns( $columns ) {\n $columns['machine'] = 'Machine';\n return $columns;\n}\nadd_filter( 'manage_enquiry_posts_columns', 'wpd_enquiry_posts_columns' );\n</code></pre>\n\n<p>Next, use the <code>manage_$post_type_posts_custom_column</code> action to output a value in that column for each post:</p>\n\n<pre><code>function wpd_enquiry_column( $column, $post_id ) {\n if ( 'machine' === $column ) {\n // get the machine ID saved in meta\n $machine_id = get_post_meta( $post_id, '_machine_id', true );\n if( $machine_id ){\n // get the machine post\n $machine = get_post( $machine_id );\n if( is_object( $machine ) ){\n echo get_the_title( $machine );\n }\n } else {\n echo 'none';\n }\n }\n}\nadd_action( 'manage_enquiry_posts_custom_column', 'wpd_enquiry_column', 10, 2 );\n</code></pre>\n\n<p>For the individual <code>enquiry</code> post edit screens, you can add a meta box to display the machine. Here we add a meta box:</p>\n\n<pre><code>function wpd_machine_meta_box() {\n add_meta_box( 'machine-id', 'Machine', 'wpd_display_machine_meta_box', 'enquiry' );\n}\nadd_action( 'add_meta_boxes', 'wpd_machine_meta_box' );\n</code></pre>\n\n<p>And then the display function for the meta box:</p>\n\n<pre><code>function wpd_display_machine_meta_box( $post ) {\n $machine_id = get_post_meta( $post-&gt;ID, '_machine_id', true );\n if( $machine_id ){\n $machine = get_post( $machine_id );\n if( is_object( $machine ) ){\n echo get_the_title( $machine );\n }\n } else {\n echo 'none';\n }\n}\n</code></pre>\n\n<p>Here we have just a simple display of a static value, you can also generate a form field in your meta box, like the first function above, and hook <code>post_save</code> to allow the admin to update the value.</p>\n" } ]
2018/09/02
[ "https://wordpress.stackexchange.com/questions/313118", "https://wordpress.stackexchange.com", "https://wordpress.stackexchange.com/users/149189/" ]
I am looking for the function to change position the price for the category. (I attached an image). Ok, is not a switch is a remove and add. ¿Where i can find a good explanation about the php function and the list of it?,will be awesome if somebody know a good explanation of the structure too. Because Codex from [Woocommerce](https://docs.woocommerce.com/documentation/plugins/woocommerce/woocommerce-codex/) and [Wordpress](https://codex.wordpress.org/) there isn't all of it. [![enter image description here](https://i.stack.imgur.com/tiMRE.jpg)](https://i.stack.imgur.com/tiMRE.jpg) Thanks in advanced!! Regards!
Add a field to your form that allows selection of a `machine`. You can use `get_posts` to generate a `select` element: ``` $args = [ 'posts_per_page' => -1, 'post_type' => 'machine' ]; $machines = get_posts( $args ); if( ! empty( $machines ) ){ echo '<select name="_machine_id">'; foreach( $machines as $machine ){ echo '<option value="' . $machine->ID . '" >' . get_the_title( $machine ) . '</option>'; } echo '</select>'; } ``` Save that value in post meta for the `enquiry` post under the key `_machine_id`. To add a Machine column to the `enquiry` post type list screen, use the `manage_$post_type_posts_columns` filter: ``` function wpd_enquiry_posts_columns( $columns ) { $columns['machine'] = 'Machine'; return $columns; } add_filter( 'manage_enquiry_posts_columns', 'wpd_enquiry_posts_columns' ); ``` Next, use the `manage_$post_type_posts_custom_column` action to output a value in that column for each post: ``` function wpd_enquiry_column( $column, $post_id ) { if ( 'machine' === $column ) { // get the machine ID saved in meta $machine_id = get_post_meta( $post_id, '_machine_id', true ); if( $machine_id ){ // get the machine post $machine = get_post( $machine_id ); if( is_object( $machine ) ){ echo get_the_title( $machine ); } } else { echo 'none'; } } } add_action( 'manage_enquiry_posts_custom_column', 'wpd_enquiry_column', 10, 2 ); ``` For the individual `enquiry` post edit screens, you can add a meta box to display the machine. Here we add a meta box: ``` function wpd_machine_meta_box() { add_meta_box( 'machine-id', 'Machine', 'wpd_display_machine_meta_box', 'enquiry' ); } add_action( 'add_meta_boxes', 'wpd_machine_meta_box' ); ``` And then the display function for the meta box: ``` function wpd_display_machine_meta_box( $post ) { $machine_id = get_post_meta( $post->ID, '_machine_id', true ); if( $machine_id ){ $machine = get_post( $machine_id ); if( is_object( $machine ) ){ echo get_the_title( $machine ); } } else { echo 'none'; } } ``` Here we have just a simple display of a static value, you can also generate a form field in your meta box, like the first function above, and hook `post_save` to allow the admin to update the value.