qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
sequence | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
324,079 | <p>I want to give a post a classname on the homepage (index) if the post on the single page has no content. So when the post itself exists but there is no content, I want to give a classname to that specific post/article which will be shown on the homepage.</p>
<p>My question: can this be done? If so, how?</p>
| [
{
"answer_id": 324087,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 1,
"selected": false,
"text": "<p>As Tom J Nowell mentioned in his comment, it is not clear what do you want to accomplish. If you want to just show your empty content <code>div</code>, you can use CSS as follows:</p>\n\n<pre><code>div:empty {\n width: 100%;\n height: 20px;\n margin-bottom: 10px;\n background: #ff0000;\n}\n</code></pre>\n\n<p>It will show your empty content <code>div</code> as a nice, red band.</p>\n"
},
{
"answer_id": 324089,
"author": "Kevin Mamaqi",
"author_id": 60103,
"author_profile": "https://wordpress.stackexchange.com/users/60103",
"pm_score": 0,
"selected": false,
"text": "<p>If you want to add a post class programatically to the posts that have no content you should use the following snippet inside the loop:</p>\n\n<pre><code>if ( empty( get_the_content() ) ) {}\n</code></pre>\n\n<p>If you're using it outside the loop to call other posts you can use:</p>\n\n<pre><code><?php if (empty(get_post_field('post_content', $MY_POST_ID))): ?>\n\n<?php endif ?>\n</code></pre>\n"
}
] | 2018/12/28 | [
"https://wordpress.stackexchange.com/questions/324079",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/62192/"
] | I want to give a post a classname on the homepage (index) if the post on the single page has no content. So when the post itself exists but there is no content, I want to give a classname to that specific post/article which will be shown on the homepage.
My question: can this be done? If so, how? | As Tom J Nowell mentioned in his comment, it is not clear what do you want to accomplish. If you want to just show your empty content `div`, you can use CSS as follows:
```
div:empty {
width: 100%;
height: 20px;
margin-bottom: 10px;
background: #ff0000;
}
```
It will show your empty content `div` as a nice, red band. |
324,091 | <p>I'm trying to create custom columns block in Gutenberg.
Is it possible to add class to the wrapper of the element in the editor based on the attributes? I'd like to switch <code>???</code> to class based e.g. <code>columns-4</code>. Otherwise it's not possible to use <code>flex</code>. </p>
<pre><code><div id="..." class="wp-block editor-block-list__block ???" data-type="my-blocks/column" tabindex="0" aria-label="Block: Single Column">
<div>
<div class="this-can-be-set-in-edit-or-attributes">
...
</div>
</div>
</div>
</code></pre>
| [
{
"answer_id": 324095,
"author": "Runnick",
"author_id": 121208,
"author_profile": "https://wordpress.stackexchange.com/users/121208",
"pm_score": 4,
"selected": true,
"text": "<p>Actually it can be done with the <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blocklistblock\" rel=\"nofollow noreferrer\">filter</a>:</p>\n\n<pre><code>const { createHigherOrderComponent } = wp.compose;\nconst withCustomClassName = createHigherOrderComponent( ( BlockListBlock ) => {\n return ( props ) => {\n if(props.attributes.size) {\n return <BlockListBlock { ...props } className={ \"block-\" + props.attributes.size } />;\n } else {\n return <BlockListBlock {...props} />\n }\n\n };\n}, 'withClientIdClassName' );\n\nwp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withCustomClassName );\n</code></pre>\n"
},
{
"answer_id": 388416,
"author": "SteveEmmE",
"author_id": 206596,
"author_profile": "https://wordpress.stackexchange.com/users/206596",
"pm_score": 2,
"selected": false,
"text": "<p>I think is also possible to manage wrapper classes with useBlockProps.\nI found this solution in the official Gutenberg doc, <a href=\"https://developer.wordpress.org/block-editor/reference-guides/block-api/block-edit-save/#block-wrapper-props\" rel=\"nofollow noreferrer\">here</a></p>\n<pre><code>import { useBlockProps } from '@wordpress/block-editor';\n\n// ...\nconst blockSettings = {\napiVersion: 2,\n\n// ...\n\nedit: () => {\n const blockProps = useBlockProps( {\n className: 'my-random-classname',\n } );\n\n return <div { ...blockProps }>Your block.</div>;\n},\n};\n</code></pre>\n"
}
] | 2018/12/28 | [
"https://wordpress.stackexchange.com/questions/324091",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121208/"
] | I'm trying to create custom columns block in Gutenberg.
Is it possible to add class to the wrapper of the element in the editor based on the attributes? I'd like to switch `???` to class based e.g. `columns-4`. Otherwise it's not possible to use `flex`.
```
<div id="..." class="wp-block editor-block-list__block ???" data-type="my-blocks/column" tabindex="0" aria-label="Block: Single Column">
<div>
<div class="this-can-be-set-in-edit-or-attributes">
...
</div>
</div>
</div>
``` | Actually it can be done with the [filter](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#editor-blocklistblock):
```
const { createHigherOrderComponent } = wp.compose;
const withCustomClassName = createHigherOrderComponent( ( BlockListBlock ) => {
return ( props ) => {
if(props.attributes.size) {
return <BlockListBlock { ...props } className={ "block-" + props.attributes.size } />;
} else {
return <BlockListBlock {...props} />
}
};
}, 'withClientIdClassName' );
wp.hooks.addFilter( 'editor.BlockListBlock', 'my-plugin/with-client-id-class-name', withCustomClassName );
``` |
324,127 | <p>I have this PHP code that shows a related posts element created using advanced custom fields plugin. I want to create a shortcode inside functions.php with the code and then use the shortcode in a text element of a page builder. Would someone kindly assist me with the modified code to put inside functions.php? Thanks</p>
<pre><code><?php
$posts = get_field('related_posts', false, false);
$loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3, 'post__in' => $posts, 'post_status' => 'publish', 'orderby' => 'post__in', 'order' => 'ASC' ));
if($loop->have_posts()) { ?>
<div class="rel-posts">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="related-post">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('td_218x150'); ?></a>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
<?php endwhile; ?>
</div>
<?php } wp_reset_query(); ?>
</code></pre>
| [
{
"answer_id": 324108,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 0,
"selected": false,
"text": "<p>Just delete the data from what you're showing the client. If a person doesn't understand what the API is, showing him data on it will simply confuse the human being. Use Whiteout if you have to.</p>\n"
},
{
"answer_id": 324171,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>I'm not entirely sure what will be better explanation, or why this one (the real one) is not enough.</p>\n\n<p>In your stats you see URLs of requests and not paths to files. URL has nothing to do with files on server.</p>\n\n<p>Yes - if the requests targets physical file, then that file exists, but... There are plenty URLs that are not connected to any file - mod_rewrite takes care of them. For example there is no directory like <code>/rss/</code> anywhere in your WP installation directory. There is no directory like <code>/category/uncaregorized/</code>, and yet - both of these URLs work and you can find them in stats...</p>\n\n<p>I don't see anything wrong in explaining, that your client sees HTTP requests and not file paths. And these <code>/wp-json/*</code> requests are requests to WP REST API.</p>\n\n<p>PS. You don't see them in Google Analytics, because there is no tracking code in REST API, so there requests are not logged to GA. But AWStats are more like server logs, so all requests get logged.</p>\n"
}
] | 2018/12/29 | [
"https://wordpress.stackexchange.com/questions/324127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | I have this PHP code that shows a related posts element created using advanced custom fields plugin. I want to create a shortcode inside functions.php with the code and then use the shortcode in a text element of a page builder. Would someone kindly assist me with the modified code to put inside functions.php? Thanks
```
<?php
$posts = get_field('related_posts', false, false);
$loop = new WP_Query(array('post_type' => 'post', 'posts_per_page' => 3, 'post__in' => $posts, 'post_status' => 'publish', 'orderby' => 'post__in', 'order' => 'ASC' ));
if($loop->have_posts()) { ?>
<div class="rel-posts">
<?php while ($loop->have_posts()) : $loop->the_post(); ?>
<div class="related-post">
<a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('td_218x150'); ?></a>
<h3><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
</div>
<?php endwhile; ?>
</div>
<?php } wp_reset_query(); ?>
``` | I'm not entirely sure what will be better explanation, or why this one (the real one) is not enough.
In your stats you see URLs of requests and not paths to files. URL has nothing to do with files on server.
Yes - if the requests targets physical file, then that file exists, but... There are plenty URLs that are not connected to any file - mod\_rewrite takes care of them. For example there is no directory like `/rss/` anywhere in your WP installation directory. There is no directory like `/category/uncaregorized/`, and yet - both of these URLs work and you can find them in stats...
I don't see anything wrong in explaining, that your client sees HTTP requests and not file paths. And these `/wp-json/*` requests are requests to WP REST API.
PS. You don't see them in Google Analytics, because there is no tracking code in REST API, so there requests are not logged to GA. But AWStats are more like server logs, so all requests get logged. |
324,158 | <p>I have a blank theme purely to redirect to my custom front-end. I created a <code>functions.php</code> and put <code>add_theme_support()</code> inside it and to no avail.</p>
<p>index.php:</p>
<pre><code><meta content="0; URL='https://headless-cms.test''" http-equiv"refresh">
<!-- just in case the meta tag is not read properly, here is plan B: a JS redirect -->
<script type="text/javascript">
window.location = 'https://headless-cms.test';
</script>
</code></pre>
<p>functions.php</p>
<pre><code>add_action( 'after_setup_theme', 'headless_theme_setup' );
function headless_theme_setup() {
add_theme_support( 'post-thumbnails');
}
// Also tried these and still didn't show
//add_theme_support('post-thumbnails', array(
// 'post',
// 'page',
//));
//add_theme_support( 'post-thumbnails' );
</code></pre>
<p>I refreshed the admin panel and checked under <code>screen options</code> and did not see it. I'm using WP 5.0.2.</p>
| [
{
"answer_id": 324131,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 1,
"selected": true,
"text": "<p>You can try using <a href=\"https://wordpress.org/plugins/bulkpress/\" rel=\"nofollow noreferrer\">BulkPress</a>. It allows you to create hundreds of categories very easily. Follow these steps:</p>\n\n<ol>\n<li>Install and activate the plugin.</li>\n<li>In the left side bar, hover your cursor on <strong>Bulkpress</strong>. Then click\non <strong>Terms</strong>.</li>\n<li>A new page will appear. In <strong>Taxonomy</strong> field, choose <strong>Category</strong>.</li>\n<li>Insert your <strong>Categories</strong> in the <strong>Terms</strong> field.</li>\n<li>Choose your desired <strong>Parent</strong>, if required.</li>\n<li>Finally, click on the <strong>Add Terms</strong> button.</li>\n</ol>\n"
},
{
"answer_id": 324157,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Wouldn't it be handy if we could write our category hierarchy that we wish to import as:</p>\n\n<pre><code>apple|Apple|Apple products\n iphone-6s|Iphone 6s|Apple Iphone 6s\n iphone-6s-battery|Iphone 6s battery|Apple Iphone 6s battery\n iphone-8-battery|Iphone 8 battery|Apple Iphone 8 battery\n</code></pre>\n\n<p>with each row as:</p>\n\n<pre><code>term slug|term name|term description\n</code></pre>\n\n<p>and the hierarchy defined by the indentation.</p>\n\n<h2>Example #1</h2>\n\n<p>An example using a space for indentation and <code>|</code> as a column delimiter:</p>\n\n<pre><code>$import = '\na1|A1|Term description\n a11|A11|Term description\n a111|A111|Term description\n a112|A112|Term description\n a12|A12|Term description\n';\n\nwpse324129_bulk_terms_importer( $import, 'category', '|', PHP_EOL );\n</code></pre>\n\n<p>that would import the terms as:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kwoHV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kwoHV.png\" alt=\"Import example #1\"></a></p>\n\n<h2>Example #2</h2>\n\n<p>Another example using a tab for indentation and comma as a column delimiter:</p>\n\n<pre><code>$import = '\na1,A1,\"Term description, including column delimiter\"\n a11,A11, \"Term description, including column delimiter\"\n a111,A111,\"Term description, including column delimiter\"\n a112,A112,\"Term description, including column delimiter\"\n a12,A12,\"Term description, including column delimiter\"\n';\n\nwpse324129_bulk_terms_importer( $import, 'category', ',', PHP_EOL );\n</code></pre>\n\n<p>importing terms as:</p>\n\n<p><a href=\"https://i.stack.imgur.com/XP9oH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XP9oH.png\" alt=\"Import examle #2\"></a></p>\n\n<h2>Implementation</h2>\n\n<p>Here's a first draft for such a function to bulk import terms from a string:</p>\n\n<pre><code> /**\n * Bulk Term Importer\n *\n * Bulk import terms with a given hierarchy, defined by indentation (tab or space).\n *\n * @version 0.1.3\n *\n * @see https://wordpress.stackexchange.com/a/324157/26350\n *\n * @param string $import Terms to import\n * @param string $tax Taxonomy. Default 'category'.\n * @param string $col_delimiter Column delimiter. Default '|'.\n * @param string $row_delimiter Row delimiter. Default PHP_EOL.\n */\nfunction wpse324129_bulk_term_importer( $import, $tax = 'category', $col_delimiter = '|', $row_delimiter = PHP_EOL ) {\n $rows = explode( $row_delimiter, trim( $import ) );\n $level = 0;\n $prev_term_id = 0;\n $ancestors = new \\SplStack(); // Last-In First-Out.\n\n foreach( $rows as $row ) {\n $cols = str_getcsv( $row, $col_delimiter );\n if ( 3 !== count( $cols ) ) {\n throw new Exception( __( 'Incorrect number of columns', 'wpse' ) );\n }\n $term_slug = $cols[0];\n $term_name = $cols[1];\n $term_desc = $cols[2];\n\n // Hierarchy traversal level (non negative).\n $level = strlen( $term_slug ) - strlen( ltrim( $term_slug ) );\n\n // Push the previous term to the ancestors stack if we go inner (right).\n if ( $level > $ancestors->count() ) {\n $ancestors->push( $prev_term_id );\n } // After: level === ancestors count\n\n // Reduce the ancestors' stack when we go outer (left).\n while ( $level < $ancestors->count() ) {\n $ancestors->pop();\n } // After: level === ancestors count\n\n // Arguments for term creation.\n $args = [\n 'description' => $term_desc,\n 'slug' => $term_slug,\n ];\n\n // Check parent term and add to the term creation arguments if needed.\n if ( $prev_term_id > 0 && $ancestors->count() > 0 ) {\n $parent_id = $ancestors->top(); // The parent is the one on the top.\n $parent_term = get_term_by( 'term_id', $parent_id, $tax, ARRAY_A );\n if ( isset( $parent_term['term_id'] ) ) {\n $args['parent'] = $parent_term['term_id'];\n }\n }\n\n // Check if current term slug exists and insert if needed.\n $term = get_term_by( 'slug', $term_slug, $tax, ARRAY_A ); \n if ( ! isset( $term['term_id'] ) ) { \n $result = wp_insert_term( $term_name, $tax, $args );\n if ( is_wp_error( $result ) ) {\n throw new Exception( __( 'Could not insert term!', 'wpse' ) );\n }\n $prev_term_id = $result['term_id'];\n } else {\n $prev_term_id = $term['term_id'];\n }\n }\n}\n</code></pre>\n\n<p>When we insert a term, we need to know about it's parent. So we need to collect the direct term ancestors when we traverse the hierarchy. The <strong>stack</strong> is a suitable data structure, where the <em>last item in</em> is the <em>first item out</em> (LIFO). In PHP 5.3+ we can use <a href=\"https://secure.php.net/manual/en/class.splstack.php\" rel=\"nofollow noreferrer\"><code>SplStack</code></a> that already implements methods like <code>pop()</code>, <code>push()</code>, <code>top()</code> and <code>count()</code>.</p>\n\n<p>By comparing the current <em>level</em> to the number of current ancestors, we can determine if we are going inner (right) or outer (left) and adjust the stack accordingly. Reducing the stack when we go left and push to the stack when we go right.</p>\n\n<p>For large import, one could run it through the <code>wp-cli</code> to avoid timeout.</p>\n\n<p>Hope you can extend this further to your needs, e.g. with a format validator and what to do with existing terms (we currently leave them unaffected here).</p>\n\n<p>Please backup before testing!</p>\n"
}
] | 2018/12/29 | [
"https://wordpress.stackexchange.com/questions/324158",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145214/"
] | I have a blank theme purely to redirect to my custom front-end. I created a `functions.php` and put `add_theme_support()` inside it and to no avail.
index.php:
```
<meta content="0; URL='https://headless-cms.test''" http-equiv"refresh">
<!-- just in case the meta tag is not read properly, here is plan B: a JS redirect -->
<script type="text/javascript">
window.location = 'https://headless-cms.test';
</script>
```
functions.php
```
add_action( 'after_setup_theme', 'headless_theme_setup' );
function headless_theme_setup() {
add_theme_support( 'post-thumbnails');
}
// Also tried these and still didn't show
//add_theme_support('post-thumbnails', array(
// 'post',
// 'page',
//));
//add_theme_support( 'post-thumbnails' );
```
I refreshed the admin panel and checked under `screen options` and did not see it. I'm using WP 5.0.2. | You can try using [BulkPress](https://wordpress.org/plugins/bulkpress/). It allows you to create hundreds of categories very easily. Follow these steps:
1. Install and activate the plugin.
2. In the left side bar, hover your cursor on **Bulkpress**. Then click
on **Terms**.
3. A new page will appear. In **Taxonomy** field, choose **Category**.
4. Insert your **Categories** in the **Terms** field.
5. Choose your desired **Parent**, if required.
6. Finally, click on the **Add Terms** button. |
324,174 | <p>can anyone help me i am trying to create a plugin for gallery but at the initiating
a problem occurred,when i activate the plugin it activating but problem is that it does not appearing at left menu ,</p>
<p><code>this is my code of plugin startup:|</code></p>
<pre><code><?php
/*
Plugin Name:JaissGallery
Plugin URI:WWW.GOOGLE.COM
description: >-Jaiss gallery plugin
Version: 0.1
Author: Mr. Tahrid abbas
Author URI: http://mrtotallyawesome.com
*/
function doctors_gallery(){
add_menu_page(
"doctorsGallery",
"Doctors Gallery",
"Manage_options",
"DoctorsGallery",
"Doc_gallery_view"
);
}
add_action('admin_menu','doctors_gallery');
function Doc_gallery_view(){
echo "ghfhgfgh";
}
</code></pre>
<p>can somebody tell me please what i am missing there ?</p>
| [
{
"answer_id": 324131,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 1,
"selected": true,
"text": "<p>You can try using <a href=\"https://wordpress.org/plugins/bulkpress/\" rel=\"nofollow noreferrer\">BulkPress</a>. It allows you to create hundreds of categories very easily. Follow these steps:</p>\n\n<ol>\n<li>Install and activate the plugin.</li>\n<li>In the left side bar, hover your cursor on <strong>Bulkpress</strong>. Then click\non <strong>Terms</strong>.</li>\n<li>A new page will appear. In <strong>Taxonomy</strong> field, choose <strong>Category</strong>.</li>\n<li>Insert your <strong>Categories</strong> in the <strong>Terms</strong> field.</li>\n<li>Choose your desired <strong>Parent</strong>, if required.</li>\n<li>Finally, click on the <strong>Add Terms</strong> button.</li>\n</ol>\n"
},
{
"answer_id": 324157,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>Wouldn't it be handy if we could write our category hierarchy that we wish to import as:</p>\n\n<pre><code>apple|Apple|Apple products\n iphone-6s|Iphone 6s|Apple Iphone 6s\n iphone-6s-battery|Iphone 6s battery|Apple Iphone 6s battery\n iphone-8-battery|Iphone 8 battery|Apple Iphone 8 battery\n</code></pre>\n\n<p>with each row as:</p>\n\n<pre><code>term slug|term name|term description\n</code></pre>\n\n<p>and the hierarchy defined by the indentation.</p>\n\n<h2>Example #1</h2>\n\n<p>An example using a space for indentation and <code>|</code> as a column delimiter:</p>\n\n<pre><code>$import = '\na1|A1|Term description\n a11|A11|Term description\n a111|A111|Term description\n a112|A112|Term description\n a12|A12|Term description\n';\n\nwpse324129_bulk_terms_importer( $import, 'category', '|', PHP_EOL );\n</code></pre>\n\n<p>that would import the terms as:</p>\n\n<p><a href=\"https://i.stack.imgur.com/kwoHV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/kwoHV.png\" alt=\"Import example #1\"></a></p>\n\n<h2>Example #2</h2>\n\n<p>Another example using a tab for indentation and comma as a column delimiter:</p>\n\n<pre><code>$import = '\na1,A1,\"Term description, including column delimiter\"\n a11,A11, \"Term description, including column delimiter\"\n a111,A111,\"Term description, including column delimiter\"\n a112,A112,\"Term description, including column delimiter\"\n a12,A12,\"Term description, including column delimiter\"\n';\n\nwpse324129_bulk_terms_importer( $import, 'category', ',', PHP_EOL );\n</code></pre>\n\n<p>importing terms as:</p>\n\n<p><a href=\"https://i.stack.imgur.com/XP9oH.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/XP9oH.png\" alt=\"Import examle #2\"></a></p>\n\n<h2>Implementation</h2>\n\n<p>Here's a first draft for such a function to bulk import terms from a string:</p>\n\n<pre><code> /**\n * Bulk Term Importer\n *\n * Bulk import terms with a given hierarchy, defined by indentation (tab or space).\n *\n * @version 0.1.3\n *\n * @see https://wordpress.stackexchange.com/a/324157/26350\n *\n * @param string $import Terms to import\n * @param string $tax Taxonomy. Default 'category'.\n * @param string $col_delimiter Column delimiter. Default '|'.\n * @param string $row_delimiter Row delimiter. Default PHP_EOL.\n */\nfunction wpse324129_bulk_term_importer( $import, $tax = 'category', $col_delimiter = '|', $row_delimiter = PHP_EOL ) {\n $rows = explode( $row_delimiter, trim( $import ) );\n $level = 0;\n $prev_term_id = 0;\n $ancestors = new \\SplStack(); // Last-In First-Out.\n\n foreach( $rows as $row ) {\n $cols = str_getcsv( $row, $col_delimiter );\n if ( 3 !== count( $cols ) ) {\n throw new Exception( __( 'Incorrect number of columns', 'wpse' ) );\n }\n $term_slug = $cols[0];\n $term_name = $cols[1];\n $term_desc = $cols[2];\n\n // Hierarchy traversal level (non negative).\n $level = strlen( $term_slug ) - strlen( ltrim( $term_slug ) );\n\n // Push the previous term to the ancestors stack if we go inner (right).\n if ( $level > $ancestors->count() ) {\n $ancestors->push( $prev_term_id );\n } // After: level === ancestors count\n\n // Reduce the ancestors' stack when we go outer (left).\n while ( $level < $ancestors->count() ) {\n $ancestors->pop();\n } // After: level === ancestors count\n\n // Arguments for term creation.\n $args = [\n 'description' => $term_desc,\n 'slug' => $term_slug,\n ];\n\n // Check parent term and add to the term creation arguments if needed.\n if ( $prev_term_id > 0 && $ancestors->count() > 0 ) {\n $parent_id = $ancestors->top(); // The parent is the one on the top.\n $parent_term = get_term_by( 'term_id', $parent_id, $tax, ARRAY_A );\n if ( isset( $parent_term['term_id'] ) ) {\n $args['parent'] = $parent_term['term_id'];\n }\n }\n\n // Check if current term slug exists and insert if needed.\n $term = get_term_by( 'slug', $term_slug, $tax, ARRAY_A ); \n if ( ! isset( $term['term_id'] ) ) { \n $result = wp_insert_term( $term_name, $tax, $args );\n if ( is_wp_error( $result ) ) {\n throw new Exception( __( 'Could not insert term!', 'wpse' ) );\n }\n $prev_term_id = $result['term_id'];\n } else {\n $prev_term_id = $term['term_id'];\n }\n }\n}\n</code></pre>\n\n<p>When we insert a term, we need to know about it's parent. So we need to collect the direct term ancestors when we traverse the hierarchy. The <strong>stack</strong> is a suitable data structure, where the <em>last item in</em> is the <em>first item out</em> (LIFO). In PHP 5.3+ we can use <a href=\"https://secure.php.net/manual/en/class.splstack.php\" rel=\"nofollow noreferrer\"><code>SplStack</code></a> that already implements methods like <code>pop()</code>, <code>push()</code>, <code>top()</code> and <code>count()</code>.</p>\n\n<p>By comparing the current <em>level</em> to the number of current ancestors, we can determine if we are going inner (right) or outer (left) and adjust the stack accordingly. Reducing the stack when we go left and push to the stack when we go right.</p>\n\n<p>For large import, one could run it through the <code>wp-cli</code> to avoid timeout.</p>\n\n<p>Hope you can extend this further to your needs, e.g. with a format validator and what to do with existing terms (we currently leave them unaffected here).</p>\n\n<p>Please backup before testing!</p>\n"
}
] | 2018/12/29 | [
"https://wordpress.stackexchange.com/questions/324174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/144155/"
] | can anyone help me i am trying to create a plugin for gallery but at the initiating
a problem occurred,when i activate the plugin it activating but problem is that it does not appearing at left menu ,
`this is my code of plugin startup:|`
```
<?php
/*
Plugin Name:JaissGallery
Plugin URI:WWW.GOOGLE.COM
description: >-Jaiss gallery plugin
Version: 0.1
Author: Mr. Tahrid abbas
Author URI: http://mrtotallyawesome.com
*/
function doctors_gallery(){
add_menu_page(
"doctorsGallery",
"Doctors Gallery",
"Manage_options",
"DoctorsGallery",
"Doc_gallery_view"
);
}
add_action('admin_menu','doctors_gallery');
function Doc_gallery_view(){
echo "ghfhgfgh";
}
```
can somebody tell me please what i am missing there ? | You can try using [BulkPress](https://wordpress.org/plugins/bulkpress/). It allows you to create hundreds of categories very easily. Follow these steps:
1. Install and activate the plugin.
2. In the left side bar, hover your cursor on **Bulkpress**. Then click
on **Terms**.
3. A new page will appear. In **Taxonomy** field, choose **Category**.
4. Insert your **Categories** in the **Terms** field.
5. Choose your desired **Parent**, if required.
6. Finally, click on the **Add Terms** button. |
324,209 | <p>I'm still learning PHP and MySQL and need to create a unique number in Wordpress site (as a order number ID) every time, when user fill and submit "order" form from frontend and save it to database. Next submit will create a number+1. Website is not running on Woocommerce. No cart, checkout, products...</p>
<p>Thanks for help! :)</p>
| [
{
"answer_id": 324212,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": -1,
"selected": false,
"text": "<p>You can get the unique ID number by using the merge tag {submission:sequence}. It allows you to get the submission number of the current user’s submission.It only populates after the submission data has been saved to the database.</p>\n"
},
{
"answer_id": 324215,
"author": "Arash Rabiee",
"author_id": 129717,
"author_profile": "https://wordpress.stackexchange.com/users/129717",
"pm_score": 0,
"selected": false,
"text": "<p>in order to do this use </p>\n\n<pre><code> AUTO_INCREMENT PRIMARY KEY \n</code></pre>\n\n<p>while you define your table. Your table should be something like this:</p>\n\n<pre><code>CREATE TABLE `order` (\n `order_id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,\n `user_group_id` INT(11) UNSIGNED NOT NULL,\n `status` BIT,\n `meta` VARCHAR ( 255 ),\n `value` TEXT,\n `update_time` TIMESTAMP\n )DEFAULT CHARSET = utf8;\n</code></pre>\n\n<p>remember that you could change other columns, the important one is <code>order_id</code> which is auto increment</p>\n"
}
] | 2018/12/30 | [
"https://wordpress.stackexchange.com/questions/324209",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157966/"
] | I'm still learning PHP and MySQL and need to create a unique number in Wordpress site (as a order number ID) every time, when user fill and submit "order" form from frontend and save it to database. Next submit will create a number+1. Website is not running on Woocommerce. No cart, checkout, products...
Thanks for help! :) | in order to do this use
```
AUTO_INCREMENT PRIMARY KEY
```
while you define your table. Your table should be something like this:
```
CREATE TABLE `order` (
`order_id` INT(11) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
`user_group_id` INT(11) UNSIGNED NOT NULL,
`status` BIT,
`meta` VARCHAR ( 255 ),
`value` TEXT,
`update_time` TIMESTAMP
)DEFAULT CHARSET = utf8;
```
remember that you could change other columns, the important one is `order_id` which is auto increment |
324,221 | <p>I have this custom post type:</p>
<pre><code>function create_posttype() {
register_post_type( 'companies',
array(
'labels' => array(
'name' => __( 'شرکتهای عضو' ),
'singular_name' => __( 'شرکت' )
),
'supports' => array('title', 'editor', 'custom-fields', 'excerpt', 'thumbnail'),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'companies'),
)
);
}
add_action( 'init', 'create_posttype' );
</code></pre>
<p>Which shows classic editor in WordPress admin area. I tried to replace 'editor' with 'gutenberg' in the supports array which doesn't work.
I also added this code to my function as suggested <a href="https://stackoverflow.com/questions/52199629/how-to-disable-gutenberg-editor-for-certain-post-types/52199630">here</a>:</p>
<pre><code>add_filter('gutenberg_can_edit_post_type', 'prefix_disable_gutenberg');
function prefix_disable_gutenberg($current_status, $post_type)
{
if ($post_type === 'companies') return true;
return $current_status;
}
</code></pre>
<p>How can I have a Gutenberg editor on my custom post type?</p>
| [
{
"answer_id": 324222,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 7,
"selected": true,
"text": "<p>For Gutenberg to work in a Custom Post Type you need to enable both the <code>editor</code> in <code>supports</code> (which you already have) and <code>show_in_rest</code>. So add <code>'show_in_rest' => true,</code> to your post registration arguments array.</p>\n"
},
{
"answer_id": 331516,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 3,
"selected": false,
"text": "<p>Start by registering a Gutenberg WordPress custom type. The process is fairly easy and involves adding the following the code snippet.</p>\n\n<pre><code>/*Register WordPress Gutenberg CPT */\nfunction cw_post_type() {\n\n register_post_type( 'portfolio',\n // WordPress CPT Options Start\n array(\n 'labels' => array(\n 'name' => __( 'Portfolio' ),\n 'singular_name' => __( 'Portfolio' )\n ),\n 'has_archive' => true,\n 'public' => true,\n 'rewrite' => array('slug' => 'portfolio'),\n 'show_in_rest' => true,\n 'supports' => array('editor')\n )\n );\n}\n\nadd_action( 'init', 'cw_post_type' );\n</code></pre>\n\n<p>add the show_in_rest key and set it to true via your custom post type.</p>\n\n<pre><code>'show_in_rest' => true,\n 'supports' => array('editor')\n</code></pre>\n\n<p>As you can see, the above code snippet just set the ‘show_in_rest’ parameter to ‘TRUE’. After this step, when you create or edit a custom post type, you will see the Gutenberg editor visible and enabled.</p>\n\n<p>All the steps and query discuss in detailed at \n<a href=\"https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/\" rel=\"noreferrer\">https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/</a></p>\n"
}
] | 2018/12/30 | [
"https://wordpress.stackexchange.com/questions/324221",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109403/"
] | I have this custom post type:
```
function create_posttype() {
register_post_type( 'companies',
array(
'labels' => array(
'name' => __( 'شرکتهای عضو' ),
'singular_name' => __( 'شرکت' )
),
'supports' => array('title', 'editor', 'custom-fields', 'excerpt', 'thumbnail'),
'public' => true,
'has_archive' => true,
'rewrite' => array('slug' => 'companies'),
)
);
}
add_action( 'init', 'create_posttype' );
```
Which shows classic editor in WordPress admin area. I tried to replace 'editor' with 'gutenberg' in the supports array which doesn't work.
I also added this code to my function as suggested [here](https://stackoverflow.com/questions/52199629/how-to-disable-gutenberg-editor-for-certain-post-types/52199630):
```
add_filter('gutenberg_can_edit_post_type', 'prefix_disable_gutenberg');
function prefix_disable_gutenberg($current_status, $post_type)
{
if ($post_type === 'companies') return true;
return $current_status;
}
```
How can I have a Gutenberg editor on my custom post type? | For Gutenberg to work in a Custom Post Type you need to enable both the `editor` in `supports` (which you already have) and `show_in_rest`. So add `'show_in_rest' => true,` to your post registration arguments array. |
324,229 | <p>I'm currently using this code within my plugin on a custom widgets textarea to enable codemirror.</p>
<pre><code>(function ($) {
$(document).ready( function(){
var coinmedi_es_<?php echo $wid_id; ?> = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
coinmedi_es_<?php echo $wid_id; ?>.codemirror = _.extend(
{},
coinmedi_es_<?php echo $wid_id; ?>.codemirror,
{
mode: 'htmlmixed',
lineNumbers: true,
indentUnit: 2,
tabSize: 2,
autoRefresh:true
}
);
var cm_editor_<?php echo $wid_id; ?> = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , coinmedi_es_<?php echo $wid_id; ?> );
$(document).on('keyup', '.CodeMirror-code', function(){
$('#<?php echo $textarea_id; ?>').html(cm_editor_<?php echo $wid_id; ?>.codemirror.getValue());
$('#<?php echo $textarea_id; ?>').trigger('change');
});
});
})(jQuery);
</code></pre>
<p>Everything is working fine for HTML but when I try to add javascript eg.</p>
<pre><code><script> alert('1') </script>
</code></pre>
<p>It accepts the javascript and highlights as it should but when I click the save button nothing is posted for this textarea. When I remove the javascript it saves as it should. Where am I going wrong, I can't seem to pinpoint why it's not saving. Any help would be appreciated. </p>
<p>Edit: Update method</p>
<pre><code>$instance['ad-code'] = ( ! empty( $new_instance['ad-code'] ) ) ? $new_instance['ad-code'] : '';
</code></pre>
| [
{
"answer_id": 324222,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 7,
"selected": true,
"text": "<p>For Gutenberg to work in a Custom Post Type you need to enable both the <code>editor</code> in <code>supports</code> (which you already have) and <code>show_in_rest</code>. So add <code>'show_in_rest' => true,</code> to your post registration arguments array.</p>\n"
},
{
"answer_id": 331516,
"author": "Owais Alam",
"author_id": 91939,
"author_profile": "https://wordpress.stackexchange.com/users/91939",
"pm_score": 3,
"selected": false,
"text": "<p>Start by registering a Gutenberg WordPress custom type. The process is fairly easy and involves adding the following the code snippet.</p>\n\n<pre><code>/*Register WordPress Gutenberg CPT */\nfunction cw_post_type() {\n\n register_post_type( 'portfolio',\n // WordPress CPT Options Start\n array(\n 'labels' => array(\n 'name' => __( 'Portfolio' ),\n 'singular_name' => __( 'Portfolio' )\n ),\n 'has_archive' => true,\n 'public' => true,\n 'rewrite' => array('slug' => 'portfolio'),\n 'show_in_rest' => true,\n 'supports' => array('editor')\n )\n );\n}\n\nadd_action( 'init', 'cw_post_type' );\n</code></pre>\n\n<p>add the show_in_rest key and set it to true via your custom post type.</p>\n\n<pre><code>'show_in_rest' => true,\n 'supports' => array('editor')\n</code></pre>\n\n<p>As you can see, the above code snippet just set the ‘show_in_rest’ parameter to ‘TRUE’. After this step, when you create or edit a custom post type, you will see the Gutenberg editor visible and enabled.</p>\n\n<p>All the steps and query discuss in detailed at \n<a href=\"https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/\" rel=\"noreferrer\">https://www.cloudways.com/blog/gutenberg-wordpress-custom-post-type/</a></p>\n"
}
] | 2018/12/30 | [
"https://wordpress.stackexchange.com/questions/324229",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155953/"
] | I'm currently using this code within my plugin on a custom widgets textarea to enable codemirror.
```
(function ($) {
$(document).ready( function(){
var coinmedi_es_<?php echo $wid_id; ?> = wp.codeEditor.defaultSettings ? _.clone( wp.codeEditor.defaultSettings ) : {};
coinmedi_es_<?php echo $wid_id; ?>.codemirror = _.extend(
{},
coinmedi_es_<?php echo $wid_id; ?>.codemirror,
{
mode: 'htmlmixed',
lineNumbers: true,
indentUnit: 2,
tabSize: 2,
autoRefresh:true
}
);
var cm_editor_<?php echo $wid_id; ?> = wp.codeEditor.initialize($('#<?php echo $textarea_id; ?>') , coinmedi_es_<?php echo $wid_id; ?> );
$(document).on('keyup', '.CodeMirror-code', function(){
$('#<?php echo $textarea_id; ?>').html(cm_editor_<?php echo $wid_id; ?>.codemirror.getValue());
$('#<?php echo $textarea_id; ?>').trigger('change');
});
});
})(jQuery);
```
Everything is working fine for HTML but when I try to add javascript eg.
```
<script> alert('1') </script>
```
It accepts the javascript and highlights as it should but when I click the save button nothing is posted for this textarea. When I remove the javascript it saves as it should. Where am I going wrong, I can't seem to pinpoint why it's not saving. Any help would be appreciated.
Edit: Update method
```
$instance['ad-code'] = ( ! empty( $new_instance['ad-code'] ) ) ? $new_instance['ad-code'] : '';
``` | For Gutenberg to work in a Custom Post Type you need to enable both the `editor` in `supports` (which you already have) and `show_in_rest`. So add `'show_in_rest' => true,` to your post registration arguments array. |
324,230 | <p>I have a freelancer working on a program for me. </p>
<p>I gave him access to the theme folder via FTP. He uploaded <a href="http://phpminiadmin.sourceforge.net/" rel="nofollow noreferrer">phpMiniAdmin</a> to that folder and, somehow, obtained the database credentials, which he then used to sign in. </p>
<p>How did he manage to obtain those credentials? Is there a vulnerability that can be used once you can upload files to the server?</p>
| [
{
"answer_id": 324231,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>If they can upload files then they can upload a php file that can read the database credentials from wp-config.php. Having upload access to the server can let you do almost anything. Don't give that access to people you don't trust. There's no vulnerability here, you just gave them the keys.</p>\n"
},
{
"answer_id": 324232,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": true,
"text": "<p>All he needed to do is to put this PHP code in any template file and run it:</p>\n\n<pre><code>var_dump(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST);\n</code></pre>\n\n<p>One line and it will print all the DB credentials. </p>\n\n<p>As you can see - no vulnerabilities are needed.</p>\n\n<p>All PHP code has access to these credentials. And it has to - otherwise it wouldn’t be able to access DB...</p>\n"
}
] | 2018/12/30 | [
"https://wordpress.stackexchange.com/questions/324230",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/136273/"
] | I have a freelancer working on a program for me.
I gave him access to the theme folder via FTP. He uploaded [phpMiniAdmin](http://phpminiadmin.sourceforge.net/) to that folder and, somehow, obtained the database credentials, which he then used to sign in.
How did he manage to obtain those credentials? Is there a vulnerability that can be used once you can upload files to the server? | All he needed to do is to put this PHP code in any template file and run it:
```
var_dump(DB_NAME, DB_USER, DB_PASSWORD, DB_HOST);
```
One line and it will print all the DB credentials.
As you can see - no vulnerabilities are needed.
All PHP code has access to these credentials. And it has to - otherwise it wouldn’t be able to access DB... |
324,243 | <p>I'm working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I've been fine right up to image "conversion". I think I can pull the old image and add it to the library using <a href="https://wordpress.stackexchange.com/questions/238294/programmatically-adding-images-to-the-media-library-with-wp-generate-attachment">this answer</a>. After that, I'm sort of lost.</p>
<p>What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from.</p>
<h3>Step 1. I need to get a pointer or id or something for the freshly added media.</h3>
<p>I don't 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added.</p>
<h3>Step 2. I need to make that image be part of a post.</h3>
<p>As for how I add it to the post (in the right size) in whatever format WordPress uses natively...</p>
<p><em>I need help with both steps.</em></p>
| [
{
"answer_id": 340400,
"author": "Antti Koskinen",
"author_id": 144392,
"author_profile": "https://wordpress.stackexchange.com/users/144392",
"pm_score": 1,
"selected": false,
"text": "<p>Building upon the accepted answer on the linked question, I think something like this might work.</p>\n\n<p>So basically,</p>\n\n<ol>\n<li>get the existing post content with <code>get_post_field</code></li>\n<li>upload the image with <code>wp_insert_attachment</code> which gives you the image ID</li>\n<li>grab the image size and alt from the post content somehow</li>\n<li>let WP generate the markup for the image with <code>wp_get_attachment_image</code></li>\n<li>replace the old image placeholder with the new image html</li>\n<li>when all of the image placeholders have been replaced with img tags, save the modified post content to DB with <code>wp_update_post</code></li>\n</ol>\n\n<p>Optionally set any of the images as the post thumbnail / featured image with <code>set_post_thumbnail</code>.</p>\n\n<pre><code>$post_id = 1234;\n$images = array('filename1.png', 'filename2.png', ... 'filename10.png');\n\n// Get post content\n$post_content = get_post_field( 'post_content', $post_id );\n\n// Get the path to the upload directory.\n$wp_upload_dir = wp_upload_dir();\n\nforeach($images as $name) {\n $attachment = array(\n 'guid'=> $wp_upload_dir['url'] . '/' . basename( $name ), \n 'post_mime_type' => 'image/png',\n 'post_title' => 'my description',\n 'post_content' => 'my description',\n 'post_status' => 'inherit'\n );\n\n /**\n * STEP 1\n * add images as attachments to WordPress\n */\n $image_id = wp_insert_attachment($attachment, $name, $post_id);\n // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\n require_once( ABSPATH . 'wp-admin/includes/image.php' );\n // Generate the metadata for the attachment, and update the database record.\n $attach_data = wp_generate_attachment_metadata( $image_id, $name );\n wp_update_attachment_metadata( $image_id, $attach_data );\n\n /**\n * STEP 2\n * Grab image data from $post_content\n */\n // strpos() + substr() maybe?\n $width = 123;\n $height = 123;\n $alt = 'Hello';\n\n /**\n * STEP 3\n * get html markup for image\n */ \n // Let WP generate the html markup for the image, adjust size as needed (thumbnail,medium,large,full,array(width,height))\n $image_html = wp_get_attachment_image( $image_id, array( $width, $height ), false, array( 'alt' => $alt ) );\n\n /**\n * STEP 4\n * Replace placeholders in content with img markup\n */\n preg_replace( $pattern, $image_html, $post_content ) // I don't understand regex well enough to give an example, so you need to figure it out yourself\n\n /**\n * OPTIONAL\n * set image as featured\n */\n if ( $name === 'example' ) {\n set_post_thumbnail( $post_id, $image_id );\n }\n\n}\n\n/**\n * STEP 5\n * Update post content\n */\n$post_with_imported_images = array(\n 'ID' => $post_id,\n 'post_content' => $post_content,\n);\nwp_update_post( $post_with_imported_images );\n</code></pre>\n\n<p><strong>EDIT</strong> This should work, maybe with little tweaking, at least with the Classic Editor. I'm not sure about Gutenberg as I haven't worked with it much.</p>\n"
},
{
"answer_id": 340404,
"author": "Faham Shaikh",
"author_id": 147414,
"author_profile": "https://wordpress.stackexchange.com/users/147414",
"pm_score": 2,
"selected": false,
"text": "<p>Hey I used this code for something similar(I was also downloading remote image and uploading to WordPress site). Please have a look:</p>\n\n<pre><code>$image_url = $value;//This is the sanitized image url.\n$image = pathinfo($image_url);//Extracting information into array.\n$image_name = $image['basename'];\n$upload_dir = wp_upload_dir();\n$image_data = file_get_contents($image_url);\n$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);\n$filename = basename($unique_file_name);\n$postarr = array(\n 'post_title' => $post_title,\n 'post_content' => $post_content,\n 'post_type' => 'post',//or whatever is your post type slug.\n 'post_status' => 'publish',\n 'meta_input' => array(\n //If you have any meta data, that will go here.\n ),\n);\n$insert_id = wp_insert_post($postarr, true);\nif (!is_wp_error($insert_id)) {\n if ($image != '') {\n // Check folder permission and define file location\n if (wp_mkdir_p($upload_dir['path'])) {\n $file = $upload_dir['path'] . '/' . $filename;\n } else {\n $file = $upload_dir['basedir'] . '/' . $filename;\n }\n // Create the image file on the server\n file_put_contents($file, $image_data);\n // Check image file type\n $wp_filetype = wp_check_filetype($filename, null);\n // Set attachment data\n $attachment = array(\n 'post_mime_type' => $wp_filetype['type'],\n 'post_title' => sanitize_file_name($filename),\n 'post_content' => '',\n 'post_status' => 'inherit',\n );\n // Create the attachment\n $attach_id = wp_insert_attachment($attachment, $file, $insert_id);\n // Include image.php\n require_once ABSPATH . 'wp-admin/includes/image.php';\n // Define attachment metadata\n $attach_data = wp_generate_attachment_metadata($attach_id, $file);\n // Assign metadata to attachment\n wp_update_attachment_metadata($attach_id, $attach_data);\n // And finally assign featured image to post\n $thumbnail = set_post_thumbnail($insert_id, $attach_id);\n }\n}\n</code></pre>\n"
}
] | 2018/12/30 | [
"https://wordpress.stackexchange.com/questions/324243",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109240/"
] | I'm working on converting my old NucleusCMS blogs to WordPress. I have created a set of tables locally and began the conversion process. I've been fine right up to image "conversion". I think I can pull the old image and add it to the library using [this answer](https://wordpress.stackexchange.com/questions/238294/programmatically-adding-images-to-the-media-library-with-wp-generate-attachment). After that, I'm sort of lost.
What I want to do is, having just programmatically added a media item (picture), then use that image by programmatically adding it to a specific post with the dimensions and alt text I just pulled (via regex) from the source I was working from.
### Step 1. I need to get a pointer or id or something for the freshly added media.
I don't 100% know what I am doing with WordPress itself so I do not know how to get a handle on the media I just added.
### Step 2. I need to make that image be part of a post.
As for how I add it to the post (in the right size) in whatever format WordPress uses natively...
*I need help with both steps.* | Hey I used this code for something similar(I was also downloading remote image and uploading to WordPress site). Please have a look:
```
$image_url = $value;//This is the sanitized image url.
$image = pathinfo($image_url);//Extracting information into array.
$image_name = $image['basename'];
$upload_dir = wp_upload_dir();
$image_data = file_get_contents($image_url);
$unique_file_name = wp_unique_filename($upload_dir['path'], $image_name);
$filename = basename($unique_file_name);
$postarr = array(
'post_title' => $post_title,
'post_content' => $post_content,
'post_type' => 'post',//or whatever is your post type slug.
'post_status' => 'publish',
'meta_input' => array(
//If you have any meta data, that will go here.
),
);
$insert_id = wp_insert_post($postarr, true);
if (!is_wp_error($insert_id)) {
if ($image != '') {
// Check folder permission and define file location
if (wp_mkdir_p($upload_dir['path'])) {
$file = $upload_dir['path'] . '/' . $filename;
} else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
// Create the image file on the server
file_put_contents($file, $image_data);
// Check image file type
$wp_filetype = wp_check_filetype($filename, null);
// Set attachment data
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name($filename),
'post_content' => '',
'post_status' => 'inherit',
);
// Create the attachment
$attach_id = wp_insert_attachment($attachment, $file, $insert_id);
// Include image.php
require_once ABSPATH . 'wp-admin/includes/image.php';
// Define attachment metadata
$attach_data = wp_generate_attachment_metadata($attach_id, $file);
// Assign metadata to attachment
wp_update_attachment_metadata($attach_id, $attach_data);
// And finally assign featured image to post
$thumbnail = set_post_thumbnail($insert_id, $attach_id);
}
}
``` |
324,244 | <p>So I am trying to add a button at the end of my blog posts, here is the code I have in the plugin so far: </p>
<pre><code><?php
/*
Plugin Name: etc....
*/
function shares_content() { ?>
<div class='social-shares-container'>
<a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>
</div> <?php
}
function shares_add_buttons($content) {
global $post;
if (!is_page() && is_object($post)) {
return $content . shares_content();
}
return $content;
}
add_filter('the_content', 'shares_add_buttons');
?>
</code></pre>
<p>This adds the link just before my content, but if I do something like this, it adds the new content in the desired place (after <code>the_content</code>):</p>
<pre><code>function shares_add_buttons($content) {
global $post;
if (!is_page() && is_object($post)) {
return $content . 'some random content';
}
return $content;
}
</code></pre>
<p>Could anyone tell me why this is please?</p>
| [
{
"answer_id": 324246,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>In this line:</p>\n\n<pre><code>return $content . shares_content();\n</code></pre>\n\n<p>You concatenate original content with result of <code>shares_content</code> function. So it looks correct, but then...</p>\n\n<p>In that function:</p>\n\n<pre><code>function shares_content() { ?>\n <div class='social-shares-container'>\n <a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>\n </div> <?php\n}\n</code></pre>\n\n<p>you don’t return anything, so this function has no result, so nothing is appended to the content in your filter.</p>\n\n<p>But also... This function echoes div with link, so that content is printed, when the function is ran, so it gets printed before the content...</p>\n"
},
{
"answer_id": 324247,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>Your <code>shares_content</code> function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a <code>return</code> statement within another function.</p>\n\n<p>You can change it to <code>return</code> the string:</p>\n\n<pre><code>function shares_content() {\n $content = \"<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>\";\n return sprintf( $content, get_permalink() );\n}\n</code></pre>\n\n<p>It's also worth pointing out here the use of <code>get_permalink()</code>. If you look at the source code, that function also <code>return</code>s its value. There is another API function, <code>the_permalink()</code>, which contains an <code>echo</code> instead of a <code>return</code>. That would also break your filter output. Most WordPress functions have two versions like this.</p>\n"
}
] | 2018/12/30 | [
"https://wordpress.stackexchange.com/questions/324244",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/155705/"
] | So I am trying to add a button at the end of my blog posts, here is the code I have in the plugin so far:
```
<?php
/*
Plugin Name: etc....
*/
function shares_content() { ?>
<div class='social-shares-container'>
<a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>
</div> <?php
}
function shares_add_buttons($content) {
global $post;
if (!is_page() && is_object($post)) {
return $content . shares_content();
}
return $content;
}
add_filter('the_content', 'shares_add_buttons');
?>
```
This adds the link just before my content, but if I do something like this, it adds the new content in the desired place (after `the_content`):
```
function shares_add_buttons($content) {
global $post;
if (!is_page() && is_object($post)) {
return $content . 'some random content';
}
return $content;
}
```
Could anyone tell me why this is please? | Your `shares_content` function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a `return` statement within another function.
You can change it to `return` the string:
```
function shares_content() {
$content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>";
return sprintf( $content, get_permalink() );
}
```
It's also worth pointing out here the use of `get_permalink()`. If you look at the source code, that function also `return`s its value. There is another API function, `the_permalink()`, which contains an `echo` instead of a `return`. That would also break your filter output. Most WordPress functions have two versions like this. |
324,306 | <p>When I visit website using Wordpress Dashboard, browser is showing 'cPanel, Inc. Certification Authority';</p>
<p><a href="https://i.stack.imgur.com/u0wYQ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/u0wYQ.png" alt="enter image description here"></a></p>
<p>But, when I access it directly typing the domain in the URL Bar, no Certification icon is being displayed.</p>
<p><a href="https://i.stack.imgur.com/yOTBU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yOTBU.png" alt="enter image description here"></a></p>
<p>What it means? And how can I fix it?</p>
| [
{
"answer_id": 324246,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>In this line:</p>\n\n<pre><code>return $content . shares_content();\n</code></pre>\n\n<p>You concatenate original content with result of <code>shares_content</code> function. So it looks correct, but then...</p>\n\n<p>In that function:</p>\n\n<pre><code>function shares_content() { ?>\n <div class='social-shares-container'>\n <a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>\n </div> <?php\n}\n</code></pre>\n\n<p>you don’t return anything, so this function has no result, so nothing is appended to the content in your filter.</p>\n\n<p>But also... This function echoes div with link, so that content is printed, when the function is ran, so it gets printed before the content...</p>\n"
},
{
"answer_id": 324247,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>Your <code>shares_content</code> function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a <code>return</code> statement within another function.</p>\n\n<p>You can change it to <code>return</code> the string:</p>\n\n<pre><code>function shares_content() {\n $content = \"<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>\";\n return sprintf( $content, get_permalink() );\n}\n</code></pre>\n\n<p>It's also worth pointing out here the use of <code>get_permalink()</code>. If you look at the source code, that function also <code>return</code>s its value. There is another API function, <code>the_permalink()</code>, which contains an <code>echo</code> instead of a <code>return</code>. That would also break your filter output. Most WordPress functions have two versions like this.</p>\n"
}
] | 2018/12/31 | [
"https://wordpress.stackexchange.com/questions/324306",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158048/"
] | When I visit website using Wordpress Dashboard, browser is showing 'cPanel, Inc. Certification Authority';
[](https://i.stack.imgur.com/u0wYQ.png)
But, when I access it directly typing the domain in the URL Bar, no Certification icon is being displayed.
[](https://i.stack.imgur.com/yOTBU.png)
What it means? And how can I fix it? | Your `shares_content` function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a `return` statement within another function.
You can change it to `return` the string:
```
function shares_content() {
$content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>";
return sprintf( $content, get_permalink() );
}
```
It's also worth pointing out here the use of `get_permalink()`. If you look at the source code, that function also `return`s its value. There is another API function, `the_permalink()`, which contains an `echo` instead of a `return`. That would also break your filter output. Most WordPress functions have two versions like this. |
324,320 | <p>I'm using a plugin (Comet Cache) to save static versions of a particular page I have on my site. </p>
<p>Inside the plugin, I have the cache set to clear every 2 hours (that way this page can show the latest, non-cached) version of data its pulling from. </p>
<p>The only issue is, for this page to get cached again, someone has to manually browser to it. </p>
<p>I'm trying to automate this with WP Cron where it triggers a page load of the content. I've also been thinking of doing this with Python outside of WordPress. </p>
<p>Would there be a best practices way of doing this?
Thanks</p>
| [
{
"answer_id": 324246,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>In this line:</p>\n\n<pre><code>return $content . shares_content();\n</code></pre>\n\n<p>You concatenate original content with result of <code>shares_content</code> function. So it looks correct, but then...</p>\n\n<p>In that function:</p>\n\n<pre><code>function shares_content() { ?>\n <div class='social-shares-container'>\n <a href='https://www.facebook.com/sharer/sharer.php?u=<?php echo the_permalink(); ?>'>Share on Facebook</a>\n </div> <?php\n}\n</code></pre>\n\n<p>you don’t return anything, so this function has no result, so nothing is appended to the content in your filter.</p>\n\n<p>But also... This function echoes div with link, so that content is printed, when the function is ran, so it gets printed before the content...</p>\n"
},
{
"answer_id": 324247,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>Your <code>shares_content</code> function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a <code>return</code> statement within another function.</p>\n\n<p>You can change it to <code>return</code> the string:</p>\n\n<pre><code>function shares_content() {\n $content = \"<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>\";\n return sprintf( $content, get_permalink() );\n}\n</code></pre>\n\n<p>It's also worth pointing out here the use of <code>get_permalink()</code>. If you look at the source code, that function also <code>return</code>s its value. There is another API function, <code>the_permalink()</code>, which contains an <code>echo</code> instead of a <code>return</code>. That would also break your filter output. Most WordPress functions have two versions like this.</p>\n"
}
] | 2018/12/31 | [
"https://wordpress.stackexchange.com/questions/324320",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/145165/"
] | I'm using a plugin (Comet Cache) to save static versions of a particular page I have on my site.
Inside the plugin, I have the cache set to clear every 2 hours (that way this page can show the latest, non-cached) version of data its pulling from.
The only issue is, for this page to get cached again, someone has to manually browser to it.
I'm trying to automate this with WP Cron where it triggers a page load of the content. I've also been thinking of doing this with Python outside of WordPress.
Would there be a best practices way of doing this?
Thanks | Your `shares_content` function directly outputs content, which won't work if you're trying to assign the results to a variable or use it in a `return` statement within another function.
You can change it to `return` the string:
```
function shares_content() {
$content = "<div class='social-shares-container'><a href='https://www.facebook.com/sharer/sharer.php?u=%s'>Share on Facebook</a></div>";
return sprintf( $content, get_permalink() );
}
```
It's also worth pointing out here the use of `get_permalink()`. If you look at the source code, that function also `return`s its value. There is another API function, `the_permalink()`, which contains an `echo` instead of a `return`. That would also break your filter output. Most WordPress functions have two versions like this. |
324,327 | <p><strong>Scenario</strong></p>
<p>I'm considering writing a custom wp-json endpoint to list ALL permalinks for everyone post in my wordpress.</p>
<p><strong>Question</strong></p>
<p>Is it possible to do this with a rest query + filters? eg. <a href="http://wpsite.com/wp-json/wp/v2/posts?filter%5Bonly-permalinks%5D" rel="nofollow noreferrer">http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]</a></p>
<h1>Current Solution</h1>
<p>I ended up writing a custom endpoint, code below:</p>
<p><em>added to the bottom of functions.php</em></p>
<pre><code>function get_all_slugs() {
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => "screen",
) );
if ( empty( $posts ) ) {
return null;
}
$posts_data = array();
foreach( $posts as $post ) {
$id = $post->ID;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
//'title' => $post->post_title,
);
}
return $posts_data;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'row/v1', '/all-slugs', array( // /(?P<post_type>\d+)', array(
'methods' => 'GET',
'callback' => 'get_all_slugs',
) );
} );
</code></pre>
| [
{
"answer_id": 324332,
"author": "Justin Waulters",
"author_id": 137235,
"author_profile": "https://wordpress.stackexchange.com/users/137235",
"pm_score": 2,
"selected": false,
"text": "<p>I don't believe there is a default endpoint to let you get <em>all</em> the posts and return <em>only</em> the permalinks.</p>\n\n<p>You could use the <code>posts</code> endpoint to get large chunks of permalinks (I don't believe it will let you return all of them in a single request) and paginate the request. To get it to return only the permalinks you could use the <code>json_prepare_post</code> filter all of which is outlined as part of <a href=\"https://css-tricks.com/using-the-wp-api-to-fetch-posts/\" rel=\"nofollow noreferrer\">this</a> tutorial.</p>\n\n<p>However, if you must have <em>all</em> the permalinks in a single return, the most efficient way of doing it would be to add a new endpoint as outlined <a href=\"https://developer.wordpress.org/rest-api/extending-the-rest-api/adding-custom-endpoints/\" rel=\"nofollow noreferrer\">here</a>. In the callback function you could do something like <a href=\"https://stackoverflow.com/a/28274853/7656220\">this</a> but instead of <code>echo</code>ing the permalinks put them in an array, <code>json_encode()</code> the array, and then return it.</p>\n\n<p>Since this could become a monster of a process with a lot of posts, I'd recommend using the <a href=\"https://codex.wordpress.org/Transients_API\" rel=\"nofollow noreferrer\">Transient API</a> to store the request(s) - whether you choose to paginate and use the <code>posts</code> endpoint or return everything with a custom endpoint.</p>\n"
},
{
"answer_id": 324397,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<blockquote>\n <p>Is it possible to do this with a rest query + filters? eg.\n <a href=\"http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]\" rel=\"nofollow noreferrer\">http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]</a></p>\n</blockquote>\n\n<p>Yes, since 4.9.8 (see <a href=\"https://core.trac.wordpress.org/ticket/43874\" rel=\"nofollow noreferrer\">#43874</a>) it's possible to render only fields needed with the <code>_fields</code> parameter.</p>\n\n<h2>Examples</h2>\n\n<p>Render only the <em>permalinks</em>:</p>\n\n<p><a href=\"https://example.com/wp-json/wp/v2/posts?_fields=link\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wp/v2/posts?_fields=link</a></p>\n\n<pre><code>[ \n {\n link: \"https://example.com/foo/\"\n },\n {\n link: \"https://example.com/bar/\"\n },\n]\n</code></pre>\n\n<p>Render only the <em>post IDs</em> and <em>permalinks</em>:</p>\n\n<p><a href=\"https://example.com/wp-json/wp/v2/posts?_fields=id,link\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wp/v2/posts?_fields=id,link</a></p>\n\n<pre><code>[ \n {\n id: 123,\n link: \"https://example.com/foo/\"\n },\n {\n id: 234,\n link: \"https://example.com/bar/\"\n },\n]\n</code></pre>\n\n<p>Render only the <em>post IDs</em> and the <em>slugs</em>:</p>\n\n<p><a href=\"https://example.com/wp-json/wp/v2/posts?_fields=id,slug\" rel=\"nofollow noreferrer\">https://example.com/wp-json/wp/v2/posts?_fields=id,slug</a></p>\n\n<pre><code>[ \n {\n id: 123,\n slug: \"foo\"\n },\n {\n id: 234,\n slug: \"bar\"\n },\n]\n</code></pre>\n\n<h2>Fetching All Available Items</h2>\n\n<p>Currently we have to fetch all available items with paging, like:</p>\n\n<pre><code>https://example.comwp-json/wp/v2/posts?_fields=slug&per_page=100&page=1\nhttps://example.comwp-json/wp/v2/posts?_fields=slug&per_page=100&page=2\n...\n</code></pre>\n\n<p>where <code>per_page</code> is 10 by default and with maximum value of 100.</p>\n\n<p>Fetching all items in a single request can result in fatal errors if the number of items exceeds the available resources. </p>\n\n<p>The ticket <a href=\"https://core.trac.wordpress.org/ticket/43998\" rel=\"nofollow noreferrer\">#43998</a> to allow unbound requests (something like <code>per_page=-1</code>) for logged in users, was closed as <em>wontfix</em> because it doesn't scale and has performance issues.</p>\n\n<p>There's a ticket <a href=\"https://core.trac.wordpress.org/ticket/45140\" rel=\"nofollow noreferrer\">#45140</a> to increase the upper bound for <code>per_page</code> to few hundreds. </p>\n\n<p>Usually there's no need to display so many items in a user interface and there exists javascript techniques to handle the pagination. </p>\n\n<p>If more is really needed then one could filter the rest query via <code>rest_{$post_type}_query</code> to override the maximum default value of <code>posts_per_page</code>, at the risk of fatal errors if available resources are exceeded.</p>\n"
}
] | 2018/12/31 | [
"https://wordpress.stackexchange.com/questions/324327",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13170/"
] | **Scenario**
I'm considering writing a custom wp-json endpoint to list ALL permalinks for everyone post in my wordpress.
**Question**
Is it possible to do this with a rest query + filters? eg. [http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]](http://wpsite.com/wp-json/wp/v2/posts?filter%5Bonly-permalinks%5D)
Current Solution
================
I ended up writing a custom endpoint, code below:
*added to the bottom of functions.php*
```
function get_all_slugs() {
$posts = get_posts( array(
'numberposts' => -1,
'post_type' => "screen",
) );
if ( empty( $posts ) ) {
return null;
}
$posts_data = array();
foreach( $posts as $post ) {
$id = $post->ID;
$posts_data[] = (object) array(
'id' => $id,
'slug' => $post->post_name,
//'title' => $post->post_title,
);
}
return $posts_data;
}
add_action( 'rest_api_init', function () {
register_rest_route( 'row/v1', '/all-slugs', array( // /(?P<post_type>\d+)', array(
'methods' => 'GET',
'callback' => 'get_all_slugs',
) );
} );
``` | >
> Is it possible to do this with a rest query + filters? eg.
> <http://wpsite.com/wp-json/wp/v2/posts?filter[only-permalinks]>
>
>
>
Yes, since 4.9.8 (see [#43874](https://core.trac.wordpress.org/ticket/43874)) it's possible to render only fields needed with the `_fields` parameter.
Examples
--------
Render only the *permalinks*:
<https://example.com/wp-json/wp/v2/posts?_fields=link>
```
[
{
link: "https://example.com/foo/"
},
{
link: "https://example.com/bar/"
},
]
```
Render only the *post IDs* and *permalinks*:
<https://example.com/wp-json/wp/v2/posts?_fields=id,link>
```
[
{
id: 123,
link: "https://example.com/foo/"
},
{
id: 234,
link: "https://example.com/bar/"
},
]
```
Render only the *post IDs* and the *slugs*:
<https://example.com/wp-json/wp/v2/posts?_fields=id,slug>
```
[
{
id: 123,
slug: "foo"
},
{
id: 234,
slug: "bar"
},
]
```
Fetching All Available Items
----------------------------
Currently we have to fetch all available items with paging, like:
```
https://example.comwp-json/wp/v2/posts?_fields=slug&per_page=100&page=1
https://example.comwp-json/wp/v2/posts?_fields=slug&per_page=100&page=2
...
```
where `per_page` is 10 by default and with maximum value of 100.
Fetching all items in a single request can result in fatal errors if the number of items exceeds the available resources.
The ticket [#43998](https://core.trac.wordpress.org/ticket/43998) to allow unbound requests (something like `per_page=-1`) for logged in users, was closed as *wontfix* because it doesn't scale and has performance issues.
There's a ticket [#45140](https://core.trac.wordpress.org/ticket/45140) to increase the upper bound for `per_page` to few hundreds.
Usually there's no need to display so many items in a user interface and there exists javascript techniques to handle the pagination.
If more is really needed then one could filter the rest query via `rest_{$post_type}_query` to override the maximum default value of `posts_per_page`, at the risk of fatal errors if available resources are exceeded. |
324,345 | <p>i moved my site from http to https
now i want to redirect the user into the new url but evry time i'm trying to edit .htaccess file i'm getting an error </p>
<p>this is the working file content where xxxz is site name</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR]
RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L]
</code></pre>
<p>what i'm trying to edit is to add the following code in the top of the file as i read </p>
<pre><code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR]
RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC]
RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC]
</code></pre>
<p>but its not working so what do u think </p>
| [
{
"answer_id": 324355,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>The best way for setting up Permanent 301 Redirects is by editing .htaccess with the required redirection code. Follow these steps:</p>\n\n<ol>\n<li>Open your cPanel account.</li>\n<li>Click on <strong>File Manager</strong> under <strong>Files</strong> section.</li>\n<li>Click on <strong>public_html</strong> directory in the left sidebar.</li>\n<li>Search for the <strong>.htaccess</strong> file. Right-click on it. Click on <strong>Edit</strong>.</li>\n<li>A pop up box will appear. Click on <strong>Edit</strong>.</li>\n<li><p>A new tab will be opened. Here, you have to add the\nredirect code. For example, your old page is\n<a href=\"https://yoursite.com/old-page.htm\" rel=\"nofollow noreferrer\">https://yoursite.com/old-page.htm</a>, and the new page is\n<a href=\"https://yoursite.com/new-page.htm\" rel=\"nofollow noreferrer\">https://yoursite.com/new-page.htm</a>. In this case, the redirect code\nwill be:</p>\n\n<pre><code>Redirect 301 /old-page.htm/ /new-page.htm\n</code></pre></li>\n</ol>\n\n<p>You can find more information about these steps <a href=\"https://hostadvice.com/how-to/how-to-setup-a-permanent-301-redirect-from-one-file-to-another-using-htaccess/\" rel=\"nofollow noreferrer\">right here</a>. </p>\n"
},
{
"answer_id": 324358,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<pre><code>RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR]\nRewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC]\nRewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC]\n</code></pre>\n</blockquote>\n\n<p>This will result in a redirect loop as it will repeatedly redirect <code>https://www.xxxz.com.qa/<url></code> to <code>https://www.xxxz.com.qa/<url></code> again and again...</p>\n\n<p>If you want to redirect from HTTP then you need to check that the request was for HTTP before redirecting to HTTPS. For example:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n\n<p>No need for the <code>NC</code> flag, as you are simply matching everything anyway.</p>\n\n<hr>\n\n<p>However, this conflicts with the existing directives at the end of your file:</p>\n\n<blockquote>\n<pre><code>RewriteCond %{HTTP_HOST} ^xxxz\\.qa$ [OR]\nRewriteCond %{HTTP_HOST} ^www\\.xxxz\\.qa$\nRewriteCond %{REQUEST_URI} !^/\\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$\nRewriteCond %{REQUEST_URI} !^/\\.well-known/pki-validation/[A-F0-9] {32}\\.txt(?:\\ Comodo\\ DCV)?$\nRewriteRule ^/?$ \"http\\:\\/\\/xxxz\\.com\\.qa\" [R=301,L]\n</code></pre>\n</blockquote>\n\n<p>These directives should probably be deleted. (Fortunately, they probably aren't doing anything anyway - because they are <em>after</em> the WordPress front-controller.)</p>\n"
}
] | 2019/01/01 | [
"https://wordpress.stackexchange.com/questions/324345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82887/"
] | i moved my site from http to https
now i want to redirect the user into the new url but evry time i'm trying to edit .htaccess file i'm getting an error
this is the working file content where xxxz is site name
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR]
RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$
RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$
RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L]
```
what i'm trying to edit is to add the following code in the top of the file as i read
```
RewriteEngine on
RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR]
RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC]
RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC]
```
but its not working so what do u think | >
>
> ```
> RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR]
> RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC]
> RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC]
>
> ```
>
>
This will result in a redirect loop as it will repeatedly redirect `https://www.xxxz.com.qa/<url>` to `https://www.xxxz.com.qa/<url>` again and again...
If you want to redirect from HTTP then you need to check that the request was for HTTP before redirecting to HTTPS. For example:
```
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
```
No need for the `NC` flag, as you are simply matching everything anyway.
---
However, this conflicts with the existing directives at the end of your file:
>
>
> ```
> RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR]
> RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$
> RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
> RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$
> RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L]
>
> ```
>
>
These directives should probably be deleted. (Fortunately, they probably aren't doing anything anyway - because they are *after* the WordPress front-controller.) |
324,441 | <p>How do I get all terms matching:</p>
<ol>
<li>custom taxonomy "<code>company</code>"</li>
<li>only where term meta (ACF field) "<code>tags</code>" value matches a given string, "<code>Publishing</code>"</li>
<li>only if the term has any posts of custom type "<code>article</code>"</li>
<li>but those posts must only have a taxonomy "<code>format</code>" value of term "<code>viewpoint</code>" or one of its children</li>
</ol>
<p>... ?</p>
<p>My current code fulfils 1) and 2) above - but I do not how how to add the additional constraints of 3) "<code>article</code>" and 4) "<code>format</code>"...</p>
<pre><code> $args = array(
'meta_query' => array(
array(
'key' => 'tags',
'value' => 'Publishing',
'compare' => 'LIKE'
)
),
'taxonomy' => 'company',
'hide_empty' => false,
'number' => 10,
);
$orgs_matched = get_terms($args);
echo '<ul class="list-group list-unstyled">';
foreach ($orgs_matched as $matching_org) {
echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
echo '<span><img src="https://www.google.com/s2/favicons?domain='.get_field( 'domain', $matching_org ).'" class="mr-2"><a href="' . esc_url( get_term_link( $matching_org ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $matching_org->name ) ) . '">' . $matching_org->name . '</a></span>';
echo '<span class="badge badge-primary badge-pill">'.$matching_org->count.'</span>';
echo '</li>';
}
echo '</ul>';
</code></pre>
<p>In my setup, "<code>article</code>" posts can have associations with:</p>
<ul>
<li>"<code>format</code>" taxonomy term, with name values including "<code>viewpoint</code>".</li>
<li>"<code>company</code>" taxonomy terms, which themselves have an ACF Checkbox field, "<code>tags</code>", one of whose values is "<code>Publishing</code>". </li>
</ul>
<p>I want to get only the "<code>company</code>" terms which have a "<code>tags</code>" value of "<code>Publishing</code>" - but I am only interested in getting those companies which have associated "<code>article</code>" posts that also have taxonomy "<code>format</code>" values of "<code>viewpoint</code>" or beneath.</p>
<p>For each resulting "<code>company</code>' term, I would want to count the number of "<code>article</code>" posts of taxonomy format "<code>viewpoint</code>" and beneath.</p>
<h1>Update:</h1>
<p>I'm contemplating the method below. Basically, the standard <code>get_terms</code> below, which works, and then <strong>stepping through the resulting array to filter out any terms which don't have the term</strong> in question...</p>
<pre><code> $args_for_short = array(
'taxonomy' => 'company',
// ACF "tag" checkbox field
'meta_query' => array(
array(
'key' => 'tags',
'value' => 'Publishing',
'compare' => 'LIKE'
)
),
'orderby' => 'count',
'order' => 'desc',
'hide_empty' => false,
'number' => 10,
);
// array: actual term objects
$orgs_list_short = get_terms($args_for_short);
// Strip non-Viewpoints out of the terms array
$orgs_list_short_filtered = array();
foreach ($orgs_list_short as $org_short_single) {
// Get all posts of type 'article'
// For each 'article'
// Examine associated "format" terms
// If 'format' term "viewpoint" or child is not present
// Remove this term from the term object array
}
</code></pre>
| [
{
"answer_id": 324355,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>The best way for setting up Permanent 301 Redirects is by editing .htaccess with the required redirection code. Follow these steps:</p>\n\n<ol>\n<li>Open your cPanel account.</li>\n<li>Click on <strong>File Manager</strong> under <strong>Files</strong> section.</li>\n<li>Click on <strong>public_html</strong> directory in the left sidebar.</li>\n<li>Search for the <strong>.htaccess</strong> file. Right-click on it. Click on <strong>Edit</strong>.</li>\n<li>A pop up box will appear. Click on <strong>Edit</strong>.</li>\n<li><p>A new tab will be opened. Here, you have to add the\nredirect code. For example, your old page is\n<a href=\"https://yoursite.com/old-page.htm\" rel=\"nofollow noreferrer\">https://yoursite.com/old-page.htm</a>, and the new page is\n<a href=\"https://yoursite.com/new-page.htm\" rel=\"nofollow noreferrer\">https://yoursite.com/new-page.htm</a>. In this case, the redirect code\nwill be:</p>\n\n<pre><code>Redirect 301 /old-page.htm/ /new-page.htm\n</code></pre></li>\n</ol>\n\n<p>You can find more information about these steps <a href=\"https://hostadvice.com/how-to/how-to-setup-a-permanent-301-redirect-from-one-file-to-another-using-htaccess/\" rel=\"nofollow noreferrer\">right here</a>. </p>\n"
},
{
"answer_id": 324358,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 1,
"selected": false,
"text": "<blockquote>\n<pre><code>RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR]\nRewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC]\nRewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC]\n</code></pre>\n</blockquote>\n\n<p>This will result in a redirect loop as it will repeatedly redirect <code>https://www.xxxz.com.qa/<url></code> to <code>https://www.xxxz.com.qa/<url></code> again and again...</p>\n\n<p>If you want to redirect from HTTP then you need to check that the request was for HTTP before redirecting to HTTPS. For example:</p>\n\n<pre><code>RewriteCond %{HTTPS} off\nRewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]\n</code></pre>\n\n<p>No need for the <code>NC</code> flag, as you are simply matching everything anyway.</p>\n\n<hr>\n\n<p>However, this conflicts with the existing directives at the end of your file:</p>\n\n<blockquote>\n<pre><code>RewriteCond %{HTTP_HOST} ^xxxz\\.qa$ [OR]\nRewriteCond %{HTTP_HOST} ^www\\.xxxz\\.qa$\nRewriteCond %{REQUEST_URI} !^/\\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$\nRewriteCond %{REQUEST_URI} !^/\\.well-known/pki-validation/[A-F0-9] {32}\\.txt(?:\\ Comodo\\ DCV)?$\nRewriteRule ^/?$ \"http\\:\\/\\/xxxz\\.com\\.qa\" [R=301,L]\n</code></pre>\n</blockquote>\n\n<p>These directives should probably be deleted. (Fortunately, they probably aren't doing anything anyway - because they are <em>after</em> the WordPress front-controller.)</p>\n"
}
] | 2019/01/02 | [
"https://wordpress.stackexchange.com/questions/324441",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39300/"
] | How do I get all terms matching:
1. custom taxonomy "`company`"
2. only where term meta (ACF field) "`tags`" value matches a given string, "`Publishing`"
3. only if the term has any posts of custom type "`article`"
4. but those posts must only have a taxonomy "`format`" value of term "`viewpoint`" or one of its children
... ?
My current code fulfils 1) and 2) above - but I do not how how to add the additional constraints of 3) "`article`" and 4) "`format`"...
```
$args = array(
'meta_query' => array(
array(
'key' => 'tags',
'value' => 'Publishing',
'compare' => 'LIKE'
)
),
'taxonomy' => 'company',
'hide_empty' => false,
'number' => 10,
);
$orgs_matched = get_terms($args);
echo '<ul class="list-group list-unstyled">';
foreach ($orgs_matched as $matching_org) {
echo '<li class="list-group-item d-flex justify-content-between align-items-center">';
echo '<span><img src="https://www.google.com/s2/favicons?domain='.get_field( 'domain', $matching_org ).'" class="mr-2"><a href="' . esc_url( get_term_link( $matching_org ) ) . '" alt="' . esc_attr( sprintf( __( 'View all post filed under %s', 'my_localization_domain' ), $matching_org->name ) ) . '">' . $matching_org->name . '</a></span>';
echo '<span class="badge badge-primary badge-pill">'.$matching_org->count.'</span>';
echo '</li>';
}
echo '</ul>';
```
In my setup, "`article`" posts can have associations with:
* "`format`" taxonomy term, with name values including "`viewpoint`".
* "`company`" taxonomy terms, which themselves have an ACF Checkbox field, "`tags`", one of whose values is "`Publishing`".
I want to get only the "`company`" terms which have a "`tags`" value of "`Publishing`" - but I am only interested in getting those companies which have associated "`article`" posts that also have taxonomy "`format`" values of "`viewpoint`" or beneath.
For each resulting "`company`' term, I would want to count the number of "`article`" posts of taxonomy format "`viewpoint`" and beneath.
Update:
=======
I'm contemplating the method below. Basically, the standard `get_terms` below, which works, and then **stepping through the resulting array to filter out any terms which don't have the term** in question...
```
$args_for_short = array(
'taxonomy' => 'company',
// ACF "tag" checkbox field
'meta_query' => array(
array(
'key' => 'tags',
'value' => 'Publishing',
'compare' => 'LIKE'
)
),
'orderby' => 'count',
'order' => 'desc',
'hide_empty' => false,
'number' => 10,
);
// array: actual term objects
$orgs_list_short = get_terms($args_for_short);
// Strip non-Viewpoints out of the terms array
$orgs_list_short_filtered = array();
foreach ($orgs_list_short as $org_short_single) {
// Get all posts of type 'article'
// For each 'article'
// Examine associated "format" terms
// If 'format' term "viewpoint" or child is not present
// Remove this term from the term object array
}
``` | >
>
> ```
> RewriteCond %{HTTP_HOST} ^xxxz.com.qa [NC,OR]
> RewriteCond %{HTTP_HOST} ^www.xxxz.com.qa [NC]
> RewriteRule ^(.*)$ https://www.xxxz.com.qa/$1 [L,R=301,NC]
>
> ```
>
>
This will result in a redirect loop as it will repeatedly redirect `https://www.xxxz.com.qa/<url>` to `https://www.xxxz.com.qa/<url>` again and again...
If you want to redirect from HTTP then you need to check that the request was for HTTP before redirecting to HTTPS. For example:
```
RewriteCond %{HTTPS} off
RewriteRule (.*) https://%{HTTP_HOST}/$1 [R=301,L]
```
No need for the `NC` flag, as you are simply matching everything anyway.
---
However, this conflicts with the existing directives at the end of your file:
>
>
> ```
> RewriteCond %{HTTP_HOST} ^xxxz\.qa$ [OR]
> RewriteCond %{HTTP_HOST} ^www\.xxxz\.qa$
> RewriteCond %{REQUEST_URI} !^/\.well-known/cpanel-dcv/[0-9a-zA-Z_-]+$
> RewriteCond %{REQUEST_URI} !^/\.well-known/pki-validation/[A-F0-9] {32}\.txt(?:\ Comodo\ DCV)?$
> RewriteRule ^/?$ "http\:\/\/xxxz\.com\.qa" [R=301,L]
>
> ```
>
>
These directives should probably be deleted. (Fortunately, they probably aren't doing anything anyway - because they are *after* the WordPress front-controller.) |
324,447 | <p>www.beautifulcreationsphotography.co.uk</p>
<p>I have a client who used to have a Wordpress blog, however for some reason its carrying over to her new site and causing havok with Yoast.</p>
<p>Ive added in this filter below but it doesnt seem to have worked.</p>
<pre><code>add_filter( 'jetpack_enable_open_graph', '__return_false' );
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 324448,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>Make sure you are not seeing a cached version of the site.</p>\n\n<p>Also, try adding priority to the filter like this.</p>\n\n<pre><code>add_filter( 'jetpack_enable_open_graph', '__return_false', 99 );\n</code></pre>\n\n<p>Try this version as well...</p>\n\n<pre><code>add_filter( 'jetpack_enable_opengraph', '__return_false', 99 );\n</code></pre>\n\n<p>Try switching temporarily switching themes and checking the source code. </p>\n"
},
{
"answer_id": 326436,
"author": "jeherve",
"author_id": 27574,
"author_profile": "https://wordpress.stackexchange.com/users/27574",
"pm_score": 1,
"selected": false,
"text": "<p>The site above does not use Jetpack's Open Graph Meta Tags. It uses Yoast SEO's own tags. In fact, on any site, if you use the Yoast SEO plugin and have activated the Open Graph meta tags under SEO > Social > Facebook, Jetpack's own Open Graph Meta Tags will never be added. Only the tags from Yoast will appear on your site. The 2 plugins are built to work well together, so you have no risk of having a duplicate set of tags if you use the 2 plugins together, and you do not need to add any code snippets.</p>\n\n<p>That said, Facebook does cache information about each page on your site, so it is possible that even after you update Open Graph Meta Tags on a site, the old title / description / image is still used when sharing links on Facebook because you are seeing cached data. You can refresh that cache manually by using Facebook's Debug tool:\n<a href=\"https://developers.facebook.com/tools/debug/\" rel=\"nofollow noreferrer\">https://developers.facebook.com/tools/debug/</a>\nYou can click on \"Scape again\" there to refresh the data.</p>\n"
}
] | 2019/01/02 | [
"https://wordpress.stackexchange.com/questions/324447",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23874/"
] | www.beautifulcreationsphotography.co.uk
I have a client who used to have a Wordpress blog, however for some reason its carrying over to her new site and causing havok with Yoast.
Ive added in this filter below but it doesnt seem to have worked.
```
add_filter( 'jetpack_enable_open_graph', '__return_false' );
```
Any ideas? | The site above does not use Jetpack's Open Graph Meta Tags. It uses Yoast SEO's own tags. In fact, on any site, if you use the Yoast SEO plugin and have activated the Open Graph meta tags under SEO > Social > Facebook, Jetpack's own Open Graph Meta Tags will never be added. Only the tags from Yoast will appear on your site. The 2 plugins are built to work well together, so you have no risk of having a duplicate set of tags if you use the 2 plugins together, and you do not need to add any code snippets.
That said, Facebook does cache information about each page on your site, so it is possible that even after you update Open Graph Meta Tags on a site, the old title / description / image is still used when sharing links on Facebook because you are seeing cached data. You can refresh that cache manually by using Facebook's Debug tool:
<https://developers.facebook.com/tools/debug/>
You can click on "Scape again" there to refresh the data. |
324,509 | <p>I tried it all and since i am not so good in this coding,
I want to hide a category and his posts from the homepage
I tried all plugins especially wp hide post but it needs pro version and seems Support is not answering on my emails so i rather do not buy that
i tried the code that i found everywhere see below,</p>
<p>however my theme has his own categories for products <code>(taxonomy=download_category&post_type=download)</code>
the code i found and tried in many ways to change</p>
<pre><code>function exclude_category($query) {
if ( $query->is_home() ) {
$query->set( 'cat', '-156, -58,-154,-155' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category' );
so 1 of the things i tried was
function exclude_category_download($query) {
if ( $query->is_home() ) {
$query->set('cat', '-156, -58,-154,-155');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category_download');
</code></pre>
<p>I am completely lost could really use some help</p>
| [
{
"answer_id": 324473,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 0,
"selected": false,
"text": "<p>Function names have to be unique in PHP, so if some function is assigned to given hook, then there is nothing to look for... There can be only one function with such name - or you’ll get fatal error...</p>\n"
},
{
"answer_id": 324474,
"author": "butlerblog",
"author_id": 38603,
"author_profile": "https://wordpress.stackexchange.com/users/38603",
"pm_score": 1,
"selected": false,
"text": "<p>I think you may be looking at this the wrong way. It doesn't need to look for the <code>$tag</code> function anywhere in core (or anywhere else for that matter). That function needs to already be loaded in the current sequence. As long as whatever file that contains your custom function is loaded at the time the action/filter is triggered, then your function can run (because it is in memory at that time) - otherwise, you'll get an error since that function will be undefined.</p>\n\n<p>Here's a practical discussion of what I'm talking about. If you apply something in your theme's functions.php file that is hooked to <code>plugins_loaded</code>, your function will never fire (even though it's right there in functions.php) because the action has already passed by the time the functions.php file is loaded. You need a later action.</p>\n\n<p>Or another example would that you need to make sure the file containing your function is actually loaded so that when your action or filter call is triggered that the file containing the function is loaded into memory. For example, if you have developed a plugin that consists of multiple files and in the main plugin file that gets loaded has a filter that triggers \"<code>my_cool_filter_function()</code>\" but you never bothered to <code>include()</code> or <code>require()</code> that file in your sequence, then the function will throw an undefined error because the function does not exist when the filter is triggered. However, as long as you've run <code>include()</code> (or <code>require()</code>) to load that file, then you'll be fine because <code>my_cool_filter_function()</code> will be available to be run.</p>\n"
},
{
"answer_id": 324712,
"author": "Mahdi",
"author_id": 158194,
"author_profile": "https://wordpress.stackexchange.com/users/158194",
"pm_score": 1,
"selected": true,
"text": "<p>I read the whole core files in wordpress.\nAnd it is split multiple file across the core folders actually it is very smart of them to do such a thing</p>\n"
}
] | 2019/01/03 | [
"https://wordpress.stackexchange.com/questions/324509",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158239/"
] | I tried it all and since i am not so good in this coding,
I want to hide a category and his posts from the homepage
I tried all plugins especially wp hide post but it needs pro version and seems Support is not answering on my emails so i rather do not buy that
i tried the code that i found everywhere see below,
however my theme has his own categories for products `(taxonomy=download_category&post_type=download)`
the code i found and tried in many ways to change
```
function exclude_category($query) {
if ( $query->is_home() ) {
$query->set( 'cat', '-156, -58,-154,-155' );
}
return $query;
}
add_filter( 'pre_get_posts', 'exclude_category' );
so 1 of the things i tried was
function exclude_category_download($query) {
if ( $query->is_home() ) {
$query->set('cat', '-156, -58,-154,-155');
}
return $query;
}
add_filter('pre_get_posts', 'exclude_category_download');
```
I am completely lost could really use some help | I read the whole core files in wordpress.
And it is split multiple file across the core folders actually it is very smart of them to do such a thing |
324,601 | <p><a href="https://i.stack.imgur.com/GMWYk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/GMWYk.png" alt="enter image description here"></a></p>
<p>Hi, my website im doing now is nurulsazlinprubsntakaful.com</p>
<p>i want to delete home ---> Home as per pic i attach.</p>
<p>i read its about breadcrumbs. i also use inspect function in web browser.i get code like this from some discussion in other forum.
.title-box {
display: none;
}</p>
<p>i put in additional css. still not solve.</p>
<p>im very new in wordpress. hope someone can help me...tq2.</p>
<p>other than that, i also awant to delete icon share. </p>
| [
{
"answer_id": 324602,
"author": "Frank P. Walentynowicz",
"author_id": 32851,
"author_profile": "https://wordpress.stackexchange.com/users/32851",
"pm_score": 2,
"selected": true,
"text": "<p>First, check your theme's settings, if breadcrumbs can be turned on/off. If not, the following CSS will hide breadcrumbs:</p>\n\n<pre><code>nav.breadcrumbs {\n display: none;\n}\n</code></pre>\n\n<p>Put the above lines, into Customize -> Additional CSS, or into your theme's <code>style.css</code>.</p>\n\n<p>To remove sharing buttons, use the following CSS:</p>\n\n<pre><code>div.share.js-share {\n display: none;\n}\n</code></pre>\n"
},
{
"answer_id": 324603,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>I helped you hide the header in another question. Just curious how did you come up with .title-box? What you want to do is hit F12 and get the class or ID of the outer most element you want to hide.</p>\n\n<p>So if we inspect your page, the breadcrumb has a div around it with the class breadcrumbs.</p>\n\n<p>So we can add the following to your stylesheet, just like before, with the customizer, Appearance > Customize > Additional CSS.</p>\n\n<pre><code>.breadcrumbs {\n display: none; \n}\n</code></pre>\n\n<p>Also, if you are going to make a lot of edits, its better to make a <a href=\"https://codex.wordpress.org/Child_Themes\" rel=\"nofollow noreferrer\">child theme</a>, then you can override the stylesheet without having to use the admin customizer.</p>\n"
}
] | 2019/01/04 | [
"https://wordpress.stackexchange.com/questions/324601",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158296/"
] | [](https://i.stack.imgur.com/GMWYk.png)
Hi, my website im doing now is nurulsazlinprubsntakaful.com
i want to delete home ---> Home as per pic i attach.
i read its about breadcrumbs. i also use inspect function in web browser.i get code like this from some discussion in other forum.
.title-box {
display: none;
}
i put in additional css. still not solve.
im very new in wordpress. hope someone can help me...tq2.
other than that, i also awant to delete icon share. | First, check your theme's settings, if breadcrumbs can be turned on/off. If not, the following CSS will hide breadcrumbs:
```
nav.breadcrumbs {
display: none;
}
```
Put the above lines, into Customize -> Additional CSS, or into your theme's `style.css`.
To remove sharing buttons, use the following CSS:
```
div.share.js-share {
display: none;
}
``` |
324,643 | <p>The WordPress block API for Gutenberg has a <code>withInstanceId</code> <a href="https://github.com/WordPress/gutenberg/tree/master/packages/compose/src/with-instance-id" rel="nofollow noreferrer">package</a>. </p>
<p>They say, </p>
<blockquote>
<p>Some components need to generate a unique id for each instance. This
could serve as suffixes to element ID's for example. Wrapping a
component with withInstanceId provides a unique instanceId to serve
this purpose.</p>
</blockquote>
<p>and show an example:</p>
<pre><code>/**
* WordPress dependencies
*/
import { withInstanceId } from '@wordpress/compose';
function MyCustomElement( { instanceId } ) {
return (
<div id={ `my-custom-element-${ instanceId }` }>
content
</div>
);
}
export default withInstanceId( MyCustomElement );
</code></pre>
<p>It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using <code>export default withInstanceId( MyCustomElement )</code> will the entire component have a unique id?</p>
| [
{
"answer_id": 324647,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 2,
"selected": true,
"text": "<p>The generated <code>id</code> is added to the component's props. So it can be accessed through <code>this.props.instanceId</code> inside the component.</p>\n\n<p>In the example you posted it is being used to assign a unique <a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id\" rel=\"nofollow noreferrer\">id attribute</a> to the html element. However it can be used for custom logic inside react. Just as an example, you can assign each component an <code>id</code> and then save its data to the redux store, that way when you need to access the data from an element inside the store you can use its <code>id</code> to find it.</p>\n"
},
{
"answer_id": 371736,
"author": "Meera",
"author_id": 192202,
"author_profile": "https://wordpress.stackexchange.com/users/192202",
"pm_score": 2,
"selected": false,
"text": "<p>You could use clientId to uniquely identify the block. clientId is available in props.</p>\n<p>Something like this..</p>\n<pre><code>export function EditBlock({clientId, setAttributes} ) {\n \n // save clientId in attributes to make it available in Save\n return (\n <div id={ `my-custom-element-${ clientId }` }>\n content\n </div>\n ); \n}\n</code></pre>\n<p>No need for HOC.</p>\n"
}
] | 2019/01/04 | [
"https://wordpress.stackexchange.com/questions/324643",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1613/"
] | The WordPress block API for Gutenberg has a `withInstanceId` [package](https://github.com/WordPress/gutenberg/tree/master/packages/compose/src/with-instance-id).
They say,
>
> Some components need to generate a unique id for each instance. This
> could serve as suffixes to element ID's for example. Wrapping a
> component with withInstanceId provides a unique instanceId to serve
> this purpose.
>
>
>
and show an example:
```
/**
* WordPress dependencies
*/
import { withInstanceId } from '@wordpress/compose';
function MyCustomElement( { instanceId } ) {
return (
<div id={ `my-custom-element-${ instanceId }` }>
content
</div>
);
}
export default withInstanceId( MyCustomElement );
```
It seems like it is just being used for html ids? As to not have duplicate id names? Is there any other usage for it? If i just export my component using `export default withInstanceId( MyCustomElement )` will the entire component have a unique id? | The generated `id` is added to the component's props. So it can be accessed through `this.props.instanceId` inside the component.
In the example you posted it is being used to assign a unique [id attribute](https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/id) to the html element. However it can be used for custom logic inside react. Just as an example, you can assign each component an `id` and then save its data to the redux store, that way when you need to access the data from an element inside the store you can use its `id` to find it. |
324,649 | <p>I have following scenario:</p>
<pre><code>my-domain-name.com/google.com
my-domain-name.com/twitter.com
</code></pre>
<p>I need a custom permalink structure to pass <code>google.com</code> or <code>twitter.com</code> to <code>domain_name</code> query variable.</p>
<p>I have tried following code:</p>
<pre><code>add_rewrite_tag('%domain_name%', '([^&]+)');
add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top');
</code></pre>
<p>But not working</p>
<p>For better example Check this site: <code>http://currentlydown.com/facebook.com</code> I am trying to do the similar</p>
| [
{
"answer_id": 324713,
"author": "rifi2k",
"author_id": 158385,
"author_profile": "https://wordpress.stackexchange.com/users/158385",
"pm_score": 2,
"selected": false,
"text": "<p>I'm not sure if I should assume that you were issuing your examples inside of the init hook, but if not that is the reason they weren't working for you.</p>\n\n<p>So inside functions.php</p>\n\n<pre><code>function sd_rewrite_rules() {\n add_rewrite_tag('%domain_name%', '([^&]+)');\n add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top');\n}\nadd_action('init', 'sd_rewrite_rules', 10, 0);\n</code></pre>\n\n<p>Then if you wanted to retrieve the query variable to do something with it, you would do something like this in a page template file using the $wp_query global.</p>\n\n<pre><code>$domain_value = $wp_query->query_vars['domain_name'];\n</code></pre>\n\n<p>Everything you would want to know plus more can also be located by reading all about the Rewrite_API and it has tons of examples of doing other things you might find interesting or relevent.</p>\n\n<p><a href=\"https://codex.wordpress.org/Rewrite_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Rewrite_API</a></p>\n"
},
{
"answer_id": 324723,
"author": "Saurin Dashadia",
"author_id": 68993,
"author_profile": "https://wordpress.stackexchange.com/users/68993",
"pm_score": 2,
"selected": true,
"text": "<p>The problem was solved by just one line of code. I am thankful to @rifi2k for long discussion and proposing different solutions.</p>\n\n<p>Here is the solutions:</p>\n\n<p>Add following code to functions.php</p>\n\n<pre><code>function custom_rewrite_basic() {\n add_rewrite_tag('%domain_name%', '([a-z]{1,60}\\.[a-z]{2,})');\n}\nadd_action('init', 'custom_rewrite_basic');\n</code></pre>\n\n<p>Then from permalink settings, select <code>Custom Structure</code> and add newly created tag by only in our case its <code>/%domain_name%/</code> save settings.</p>\n"
}
] | 2019/01/04 | [
"https://wordpress.stackexchange.com/questions/324649",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68993/"
] | I have following scenario:
```
my-domain-name.com/google.com
my-domain-name.com/twitter.com
```
I need a custom permalink structure to pass `google.com` or `twitter.com` to `domain_name` query variable.
I have tried following code:
```
add_rewrite_tag('%domain_name%', '([^&]+)');
add_rewrite_rule('^/([^/]*)/?','index.php?domain_name=$matches[1]','top');
```
But not working
For better example Check this site: `http://currentlydown.com/facebook.com` I am trying to do the similar | The problem was solved by just one line of code. I am thankful to @rifi2k for long discussion and proposing different solutions.
Here is the solutions:
Add following code to functions.php
```
function custom_rewrite_basic() {
add_rewrite_tag('%domain_name%', '([a-z]{1,60}\.[a-z]{2,})');
}
add_action('init', 'custom_rewrite_basic');
```
Then from permalink settings, select `Custom Structure` and add newly created tag by only in our case its `/%domain_name%/` save settings. |
324,660 | <p>When trying to edit a wordpress post (page) the editor loads indefinitely, console shows JS error with post.php / polyfill, see code below. To me it seems to be a typo and I have no idea where the line is injected so I could change it manually. </p>
<p>Disabling all plugins did not change anything, neither did disabling Gutenberg. I am not much of a coder, nevertheless it seems to me there should not be a double quotation mark after the last 'defer"... in the line of code.</p>
<p>I am running WP 5.0.2 on Apache (Domainfactory) in a managed server environment, Theme is Enfold by Kriesi. Re-installing Wordpress and the theme (copied from working installations) changed nothing so far.</p>
<p>The reported error in the console is
"Uncaught SyntaxError: missing ) after argument list"
in
<a href="https://.../wp-admin/post.php?post=23&action=edit&lang=de&classic-editor=1:238" rel="nofollow noreferrer">https://.../wp-admin/post.php?post=23&action=edit&lang=de&classic-editor=1:238</a></p>
<p>There it says</p>
<pre><code>( 'fetch' in window ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-fetch.min.js?ver=3.0.0' defer='defer"></scr' + 'ipt>' );( document.contains ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-node-contains.min.js?ver=3.26.0-0' defer='defer"></scr' + 'ipt>' );( window.FormData && window.FormData.prototype.keys ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-formdata.min.js?ver=3.0.12' defer='defer"></scr' + 'ipt>' );( Element.prototype.matches && Element.prototype.closest ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-element-closest.min.js?ver=2.0.2' defer='defer"></scr' + 'ipt>' );
</code></pre>
<p>Any idea would be much appreciated.</p>
| [
{
"answer_id": 325650,
"author": "Kostiantyn Petlia",
"author_id": 104932,
"author_profile": "https://wordpress.stackexchange.com/users/104932",
"pm_score": 2,
"selected": true,
"text": "<p>Here is an answer: <a href=\"https://wordpress.stackexchange.com/questions/325570/wordpress-v5-0-3-gutenberg-js-error-uncaught-syntaxerror-missing-after-arg\">WordPress v5.0.3 Gutenberg & JS error "Uncaught SyntaxError: missing ) after argument list"</a></p>\n\n<p>The simplest way: Find & delete PHP Hook which added 'defer' to script (in the function.php file). Or if you have skills you can edit the code of the hook. Reason: Confusion/conflict with quotes (' & \") witch break down JS.</p>\n\n<p>About 'defer' you can read here: <a href=\"https://www.w3schools.com/tags/att_script_defer.asp\" rel=\"nofollow noreferrer\">https://www.w3schools.com/tags/att_script_defer.asp</a> This is probably due to speed optimization on your website.</p>\n"
},
{
"answer_id": 332934,
"author": "Jonnyauk",
"author_id": 45120,
"author_profile": "https://wordpress.stackexchange.com/users/45120",
"pm_score": 0,
"selected": false,
"text": "<p>OK, so I struggled to find an answer myself to this - but this worked for me. I was stripping out the type='text/javascript' on script tags because it's not required for valid HTML5 - but WordPress insists on including it when you enqueue_script. I had a function in my theme like below to deal with this - so I just stopped it running in admin and it removed the error - your mileage may vary but maybe check your theme or plugins for something similar ;)</p>\n\n<pre><code>/**\n *\n * WordPress insists on inserting invalid javascript script tag definitions when enqueuing\n * This removes this cruft - to check in the future - will WordPress get patched to support this?\n *\n */\nadd_filter( 'script_loader_tag', 'mywfx_html5_clean_js_tags' );\nfunction mywfx_html5_clean_js_tags( $input ) {\n\n if ( !is_admin() ) {\n\n $input = str_replace( \"type='text/javascript' \", '', $input );\n return str_replace( \"'\", '\"', $input );\n\n } else {\n\n return $input;\n\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 333018,
"author": "Amanahumpa",
"author_id": 110944,
"author_profile": "https://wordpress.stackexchange.com/users/110944",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe the lesson to be learnt from injected code is: <strong>Check all potencial sources of code injection.</strong> </p>\n\n<p>It turned out there was code put in the child themes' functions.php. At the time the question was asked it was as \"unnessessary\" to look for the problem there as it was dumb not to do that. </p>\n\n<p>I am sorry and grateful for the help provided. \nThank you.</p>\n"
}
] | 2019/01/04 | [
"https://wordpress.stackexchange.com/questions/324660",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110944/"
] | When trying to edit a wordpress post (page) the editor loads indefinitely, console shows JS error with post.php / polyfill, see code below. To me it seems to be a typo and I have no idea where the line is injected so I could change it manually.
Disabling all plugins did not change anything, neither did disabling Gutenberg. I am not much of a coder, nevertheless it seems to me there should not be a double quotation mark after the last 'defer"... in the line of code.
I am running WP 5.0.2 on Apache (Domainfactory) in a managed server environment, Theme is Enfold by Kriesi. Re-installing Wordpress and the theme (copied from working installations) changed nothing so far.
The reported error in the console is
"Uncaught SyntaxError: missing ) after argument list"
in
<https://.../wp-admin/post.php?post=23&action=edit&lang=de&classic-editor=1:238>
There it says
```
( 'fetch' in window ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-fetch.min.js?ver=3.0.0' defer='defer"></scr' + 'ipt>' );( document.contains ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-node-contains.min.js?ver=3.26.0-0' defer='defer"></scr' + 'ipt>' );( window.FormData && window.FormData.prototype.keys ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-formdata.min.js?ver=3.0.12' defer='defer"></scr' + 'ipt>' );( Element.prototype.matches && Element.prototype.closest ) || document.write( '<script src="https://12345678-123.ch/wp-includes/js/dist/vendor/wp-polyfill-element-closest.min.js?ver=2.0.2' defer='defer"></scr' + 'ipt>' );
```
Any idea would be much appreciated. | Here is an answer: [WordPress v5.0.3 Gutenberg & JS error "Uncaught SyntaxError: missing ) after argument list"](https://wordpress.stackexchange.com/questions/325570/wordpress-v5-0-3-gutenberg-js-error-uncaught-syntaxerror-missing-after-arg)
The simplest way: Find & delete PHP Hook which added 'defer' to script (in the function.php file). Or if you have skills you can edit the code of the hook. Reason: Confusion/conflict with quotes (' & ") witch break down JS.
About 'defer' you can read here: <https://www.w3schools.com/tags/att_script_defer.asp> This is probably due to speed optimization on your website. |
324,751 | <p>I want to obtain a path of all parents for current page. Something similar to breadcrub but used only for pages listed in menu.</p>
<p>For example if i have following structure:</p>
<pre><code>L Menu
L Sub menu
L Current page
L Sub menu 2
L Menu 2
</code></pre>
<p>I want to obtain:</p>
<pre><code>Menu >> Sub Menu >> Current page
</code></pre>
<p>I am using WordPress 5.0.2. I tried various plugins but they show only current page instead of whole path.</p>
<p>How do i solve this issue?</p>
| [
{
"answer_id": 324767,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>The <a href=\"https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/\" rel=\"nofollow noreferrer\"><code>wp_get_nav_menu_items</code></a> function will give you an array of menu item objects for a given menu. These objects contain a mixture of data specific to that unique menu item, as well as the post/page/link data the menu item refers to. You can use this array of menu items to find the current page, and then check the parent field of the item to get each parent in a loop.</p>\n\n<p>Here's an example that should get you most of the way there. Use it by calling <code>wpd_nav_menu_breadcrumbs( 'your menu' )</code> in your template. Read the comments to see what's happening in each section.</p>\n\n<pre><code>// helper function to find a menu item in an array of items\nfunction wpd_get_menu_item( $field, $object_id, $items ){\n foreach( $items as $item ){\n if( $item->$field == $object_id ) return $item;\n }\n return false;\n}\n\nfunction wpd_nav_menu_breadcrumbs( $menu ){\n // get menu items by menu id, slug, name, or object\n $items = wp_get_nav_menu_items( $menu );\n if( false === $items ){\n echo 'Menu not found';\n return;\n }\n // get the menu item for the current page\n $item = wpd_get_menu_item( 'object_id', get_queried_object_id(), $items );\n if( false === $item ){\n return;\n }\n // start an array of objects for the crumbs\n $menu_item_objects = array( $item );\n // loop over menu items to get the menu item parents\n while( 0 != $item->menu_item_parent ){\n $item = wpd_get_menu_item( 'ID', $item->menu_item_parent, $items );\n array_unshift( $menu_item_objects, $item );\n }\n // output crumbs\n $crumbs = array(); \n foreach( $menu_item_objects as $menu_item ){\n $link = '<a href=\"%s\">%s</a>';\n $crumbs[] = sprintf( $link, $menu_item->url, $menu_item->title );\n }\n echo join( ' > ', $crumbs );\n}\n</code></pre>\n\n<p>*disclaimer: not rigorously tested, use at your own risk</p>\n"
},
{
"answer_id": 400413,
"author": "JacobTheDev",
"author_id": 24566,
"author_profile": "https://wordpress.stackexchange.com/users/24566",
"pm_score": 0,
"selected": false,
"text": "<p>@Milo's code is a good baseline, but I ran in to two issues:</p>\n<ul>\n<li>It relies on the menu name as specified under Appearance → Menus. If this name ever gets changed, it would also need updated in the theme files.</li>\n<li>If no matching menu is found, you probably don't actually want a message "Menu not found" output for your users.</li>\n</ul>\n<p>I've updated the code with the following improvements:</p>\n<ul>\n<li>Added another helper function that retrieves a menu name based on a provided location. This will prevent the first issue I listed.</li>\n<li>Changed the "Menu not found" message to be a PHP warning with a more detailed description</li>\n<li>Reformatted code to be a bit easier to read, with more detailed comments</li>\n<li>Modernized a few aspects of code (also changed some stuff to my own preference)</li>\n<li>Added typecasting where possible</li>\n<li>Added ability to specific separator and classes</li>\n<li>Returned the value instead of echoed it (easier for conditional checks)</li>\n</ul>\n<pre class=\"lang-php prettyprint-override\"><code>/**\n * Retrieve a menu title from the database given the location the menu is assigned to\n *\n * @param string $location Menu location\n *\n * @return string The name of the menu\n */\nfunction wpse324751_get_menu_title(string $location): string {\n $menu_name = "";\n\n $locations = get_nav_menu_locations();\n\n if (isset($locations[$location]) && $menu = get_term($locations[$location], "nav_menu")) {\n $menu_name = $menu->name;\n }\n\n return $menu_name;\n}\n\n/**\n * Filter through an array of menu items to locate one specific item\n *\n * @param string $field\n * @param integer $object_id\n * @param array $items\n * @return WP_Post|bool\n */\nfunction wpse324751_get_menu_item(string $field, int $object_id, array $items) {\n foreach ($items as $item) {\n if (intval($item->$field) === $object_id) return $item;\n }\n\n return false;\n}\n\n/**\n * Display breadcrumbs based on a given menu\n *\n * @param string $menu_location\n * @param string $separator\n * @param string $class\n * @return string\n */\nfunction wpse324751_nav_menu_breadcrumbs(string $menu_location, string $separator = "&#8250;", string $class = ""): string {\n /**\n * Locate all menu items of the provided menu\n */\n $items = wp_get_nav_menu_items(wpse324751_get_menu_title($menu_location));\n\n /**\n * If no items exist, return empty\n */\n if ($items === false) {\n trigger_error("A menu at location '" . sanitize_text_field($menu_location) . "' could not be located.", E_USER_WARNING);\n return "";\n }\n\n /**\n * Locate the menu item for the viewed page\n */\n $item = wpse324751_get_menu_item("object_id", get_queried_object_id(), $items);\n\n /**\n * If no viewed item could be located, return empty\n */\n if ($item === false){\n return "";\n }\n\n /**\n * Store an array of items to construct the breadcrumb\n */\n $menu_item_objects = [$item];\n\n /**\n * Locate all parents of the viewed item\n */\n while (intval($item->menu_item_parent) !== 0) {\n $item = wpse324751_get_menu_item("ID", $item->menu_item_parent, $items);\n $menu_item_objects[] = $item;\n }\n\n /**\n * Initialize array to store breadcrumbs\n */\n $breadcrumbs = [];\n\n /**\n * Convert menu items to links and store them in the array\n */\n foreach($menu_item_objects as $menu_item) {\n $breadcrumbs[] = sprintf("<a class='text__link link' href='%s'>%s</a>", $menu_item->url, $menu_item->title);\n }\n\n /**\n * Return the breadcrumbs\n */\n return "<p class='" . esc_attr(trim("text {$class}")) . "'>" . join(" {$separator} ", array_reverse($breadcrumbs)) . "</p>";\n}\n</code></pre>\n"
}
] | 2019/01/05 | [
"https://wordpress.stackexchange.com/questions/324751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158330/"
] | I want to obtain a path of all parents for current page. Something similar to breadcrub but used only for pages listed in menu.
For example if i have following structure:
```
L Menu
L Sub menu
L Current page
L Sub menu 2
L Menu 2
```
I want to obtain:
```
Menu >> Sub Menu >> Current page
```
I am using WordPress 5.0.2. I tried various plugins but they show only current page instead of whole path.
How do i solve this issue? | The [`wp_get_nav_menu_items`](https://developer.wordpress.org/reference/functions/wp_get_nav_menu_items/) function will give you an array of menu item objects for a given menu. These objects contain a mixture of data specific to that unique menu item, as well as the post/page/link data the menu item refers to. You can use this array of menu items to find the current page, and then check the parent field of the item to get each parent in a loop.
Here's an example that should get you most of the way there. Use it by calling `wpd_nav_menu_breadcrumbs( 'your menu' )` in your template. Read the comments to see what's happening in each section.
```
// helper function to find a menu item in an array of items
function wpd_get_menu_item( $field, $object_id, $items ){
foreach( $items as $item ){
if( $item->$field == $object_id ) return $item;
}
return false;
}
function wpd_nav_menu_breadcrumbs( $menu ){
// get menu items by menu id, slug, name, or object
$items = wp_get_nav_menu_items( $menu );
if( false === $items ){
echo 'Menu not found';
return;
}
// get the menu item for the current page
$item = wpd_get_menu_item( 'object_id', get_queried_object_id(), $items );
if( false === $item ){
return;
}
// start an array of objects for the crumbs
$menu_item_objects = array( $item );
// loop over menu items to get the menu item parents
while( 0 != $item->menu_item_parent ){
$item = wpd_get_menu_item( 'ID', $item->menu_item_parent, $items );
array_unshift( $menu_item_objects, $item );
}
// output crumbs
$crumbs = array();
foreach( $menu_item_objects as $menu_item ){
$link = '<a href="%s">%s</a>';
$crumbs[] = sprintf( $link, $menu_item->url, $menu_item->title );
}
echo join( ' > ', $crumbs );
}
```
\*disclaimer: not rigorously tested, use at your own risk |
324,762 | <p>Based on research here and elsewhere, I have the following code that sets a cookie on a site:</p>
<pre><code>add_action( 'init', 'my_set_cookie',1 );
function my_set_cookie() {
if (! $_COOKIE['mycookie']) {
$guid = 'xxxx'; // normally a real guid value so it will be unique
setcookie('mycookie', $guid, time()+(3600*24*30),'/');
}
return;
}
</code></pre>
<p>But even though the <code>init</code> hook is used, and with a priority of '1', I still get 'headers already sent' error for the 'setcookie' statement. Using another priority (say '99') also gives the error.</p>
<p>Is there a different hook to use to set the cookie?</p>
| [
{
"answer_id": 324786,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": false,
"text": "<p>It’s a problem as old as WP, or even older...</p>\n\n<p>You can’t set cookies, or send any other headers, if any of the content of the site is already sent.</p>\n\n<p>You try to set cookies using <code>init</code> hook. And it is OK in most cases, since no output should be printed yet. But... Not all code is written correctly.</p>\n\n<p>There are many other thing done before <code>init</code>. Take a look at <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference#Actions_Run_During_a_Typical_Request\" rel=\"nofollow noreferrer\">actions run during a typical request</a>.</p>\n\n<p>As you can see... Themes get loaded before <code>init</code> hook. And so do plugins.</p>\n\n<p>So if their code cause any warning/notice (and the debug is on) or they generate any other output, then you’ll get error while setting cookie.</p>\n\n<p>Another popular cause for this problem is using closing PHP tags (<code>?></code>) at the end of files. If there is any white characters after that closing tag, then it’s treated as output also.</p>\n"
},
{
"answer_id": 325188,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>After trying various hooks to try to set the cookie before the theme loaded it's header.php file (none of the hooks worked, even those very early in the 'load cycle'), I figure that I might temporarily disable the error so that the cookie can be set. I based my answer on <a href=\"https://stackoverflow.com/a/26154061/1466973\">this question</a>.</p>\n\n<p>Now, I realize that this is not a standard way of doing it, and probably not recommended, but my justification is that if a theme is not doing things 'normally' or 'correct', and therefore causing the 'headers already sent' error message to display on the screen, then quickly bypassing that error display (and then restoring whatever error trapping settings are in place) is a solution that will work in my situation.</p>\n\n<p>It appears from my testing that even if 'headers already sent' happens, the cookie is set properly. That doesn't really sound like it should work, but it appeared to work in my testing.</p>\n\n<p>So, the technique I used is</p>\n\n<ul>\n<li><p>get the current error settings to be used later</p></li>\n<li><p>turn off display of errors</p></li>\n<li><p>do things that cause the error (in my case, set the cookie)</p></li>\n<li><p>restore the error settings to original valuess</p></li>\n</ul>\n\n<p>Here is the code that I used. Again, probably not 'kosher', but it worked in my case. </p>\n\n<pre><code>// some themes cause a 'headers already sent' message, so we bypass it here\n// by turning off that error message while we set the cookie.\n// see https://stackoverflow.com/a/26154061/1466973\n// $random_guid is a guid set previously\n$previousErrorLevel = error_reporting();\nerror_reporting(\\E_ERROR);\nsetcookie('cookie_name', $random_guid,time()+(3600*24*30),'/');\nerror_reporting($previousErrorLevel);\n</code></pre>\n\n<p>Since it worked for my case, I am marking my answer as correct, although the other answer is valid. And I expect a couple of downvotes, as this is not kosher. But it worked for my problem and circumstances.</p>\n"
},
{
"answer_id": 360525,
"author": "nikelone",
"author_id": 184177,
"author_profile": "https://wordpress.stackexchange.com/users/184177",
"pm_score": 1,
"selected": false,
"text": "<p>Here is another post to this topic with some suggestions on solving this: <a href=\"https://stackoverflow.com/questions/50205548/setcookie-not-working-wordpress-because-of-header\">https://stackoverflow.com/questions/50205548/setcookie-not-working-wordpress-because-of-header</a></p>\n\n<p>I used send_headers hook. But it would be great if someone can elaborate more, if this is really the correct hook to use for setting cookies.</p>\n"
},
{
"answer_id": 380711,
"author": "Lars Flieger",
"author_id": 198961,
"author_profile": "https://wordpress.stackexchange.com/users/198961",
"pm_score": 1,
"selected": false,
"text": "<p>You can solve this issue by <strong>checking if the header is already sent</strong>:</p>\n<p><a href=\"https://www.php.net/manual/de/function.headers-sent.php\" rel=\"nofollow noreferrer\"><code>headers_sent()</code></a></p>\n<pre class=\"lang-php prettyprint-override\"><code>function cc_set_cookie() {\n if(!headers_sent())\n setcookie('COOKIE_NAME', 'COOKIE_VALUE', time()+31556926, '/');\n}\nadd_action('init', 'cc_set_cookie');\n</code></pre>\n"
}
] | 2019/01/06 | [
"https://wordpress.stackexchange.com/questions/324762",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
] | Based on research here and elsewhere, I have the following code that sets a cookie on a site:
```
add_action( 'init', 'my_set_cookie',1 );
function my_set_cookie() {
if (! $_COOKIE['mycookie']) {
$guid = 'xxxx'; // normally a real guid value so it will be unique
setcookie('mycookie', $guid, time()+(3600*24*30),'/');
}
return;
}
```
But even though the `init` hook is used, and with a priority of '1', I still get 'headers already sent' error for the 'setcookie' statement. Using another priority (say '99') also gives the error.
Is there a different hook to use to set the cookie? | After trying various hooks to try to set the cookie before the theme loaded it's header.php file (none of the hooks worked, even those very early in the 'load cycle'), I figure that I might temporarily disable the error so that the cookie can be set. I based my answer on [this question](https://stackoverflow.com/a/26154061/1466973).
Now, I realize that this is not a standard way of doing it, and probably not recommended, but my justification is that if a theme is not doing things 'normally' or 'correct', and therefore causing the 'headers already sent' error message to display on the screen, then quickly bypassing that error display (and then restoring whatever error trapping settings are in place) is a solution that will work in my situation.
It appears from my testing that even if 'headers already sent' happens, the cookie is set properly. That doesn't really sound like it should work, but it appeared to work in my testing.
So, the technique I used is
* get the current error settings to be used later
* turn off display of errors
* do things that cause the error (in my case, set the cookie)
* restore the error settings to original valuess
Here is the code that I used. Again, probably not 'kosher', but it worked in my case.
```
// some themes cause a 'headers already sent' message, so we bypass it here
// by turning off that error message while we set the cookie.
// see https://stackoverflow.com/a/26154061/1466973
// $random_guid is a guid set previously
$previousErrorLevel = error_reporting();
error_reporting(\E_ERROR);
setcookie('cookie_name', $random_guid,time()+(3600*24*30),'/');
error_reporting($previousErrorLevel);
```
Since it worked for my case, I am marking my answer as correct, although the other answer is valid. And I expect a couple of downvotes, as this is not kosher. But it worked for my problem and circumstances. |
324,795 | <pre><code>add_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' );
function woo_custom_order_button_text() {
return __( 'Your new button text here', 'woocommerce' );
}
</code></pre>
<p>Above is the example how we can change the woocommerce "Place order" Text, but what if we want to change the CSS also how can we have the whole button customized along with our own button classes and CSS.</p>
| [
{
"answer_id": 324796,
"author": "Md. Ehsanul Haque Kanan",
"author_id": 75705,
"author_profile": "https://wordpress.stackexchange.com/users/75705",
"pm_score": 0,
"selected": false,
"text": "<p>You have to put your PHP codes at the bottom of <strong>functions.php</strong> file of your child theme. You have to place them before \"<strong>?></strong>\". On the other hand, insert your CSS codes in <strong>style.css</strong> file of your child theme. </p>\n"
},
{
"answer_id": 324814,
"author": "The WP Intermediate",
"author_id": 105791,
"author_profile": "https://wordpress.stackexchange.com/users/105791",
"pm_score": 2,
"selected": true,
"text": "<p>I will try to answer your question. since you know how the text can be changed - let me take it for CSS. </p>\n\n<p>View in the browser - The browser is rendering the button like this → </p>\n\n<pre><code><button type=\"submit\" class=\"button alt\" name=\"woocommerce_checkout_place_order\" id=\"place_order\" value=\"Confirm order\" data-value=\"Confirm order\">Confirm order</button>\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/Tmt8C.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Tmt8C.png\" alt=\"enter image description here\"></a></p>\n\n<p>Now create a folder by the name of \"woocommerce\" in your child theme/theme and create a folder by the name of checkout, and in that folder put payment.php from <a href=\"https://github.com/woocommerce/woocommerce/blob/master/templates/checkout/payment.php\" rel=\"nofollow noreferrer\">woo commerce template.</a> (Look for the latest template)</p>\n\n<p>and change the button class there with class that you want. You are all done.</p>\n"
}
] | 2019/01/06 | [
"https://wordpress.stackexchange.com/questions/324795",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152578/"
] | ```
add_filter( 'woocommerce_order_button_text', 'woo_custom_order_button_text' );
function woo_custom_order_button_text() {
return __( 'Your new button text here', 'woocommerce' );
}
```
Above is the example how we can change the woocommerce "Place order" Text, but what if we want to change the CSS also how can we have the whole button customized along with our own button classes and CSS. | I will try to answer your question. since you know how the text can be changed - let me take it for CSS.
View in the browser - The browser is rendering the button like this →
```
<button type="submit" class="button alt" name="woocommerce_checkout_place_order" id="place_order" value="Confirm order" data-value="Confirm order">Confirm order</button>
```
[](https://i.stack.imgur.com/Tmt8C.png)
Now create a folder by the name of "woocommerce" in your child theme/theme and create a folder by the name of checkout, and in that folder put payment.php from [woo commerce template.](https://github.com/woocommerce/woocommerce/blob/master/templates/checkout/payment.php) (Look for the latest template)
and change the button class there with class that you want. You are all done. |
324,908 | <p>I have been follow a tutorial here: <a href="https://rudrastyh.com/gutenberg/remove-default-blocks.html" rel="noreferrer">https://rudrastyh.com/gutenberg/remove-default-blocks.html</a> Where it discusses how to remove default Gutenberg blocks like so:</p>
<pre><code>add_filter( 'allowed_block_types', 'misha_allowed_block_types', 10, 2 );
function misha_allowed_block_types( $allowed_blocks, $post ) {
$allowed_blocks = array(
'core/image',
'core/paragraph',
'core/heading',
'core/list'
);
if( $post->post_type === 'page' ) {
$allowed_blocks[] = 'core/shortcode';
}
return $allowed_blocks;
}
</code></pre>
<p>So what this is doing is limiting the default Gutenberg blocks to image, paragraph, heading, and list. I then set the page post type to also allow for the shortcode block. So this works fine, but I am now having an issue where it removes the functionality of reusable blocks and I can't figure out what needs to be added to add that functionality back.</p>
<p>I tried commenting on that article, but the author wasn't able to think of a solution currently. I was wondering if anyone had any ideas on adding the reusable block functionality back after adding the above code snippet?</p>
| [
{
"answer_id": 324929,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>The <em>reusable block</em> is registered with the <code>core/block</code> name.</p>\n\n<p>I tried to add it to the <em>allowed blocks</em> in the <code>allowed_block_types</code> filter, here's an example:</p>\n\n<pre><code>add_filter( 'allowed_block_types', 'wpse324908_allowed_block_types', 10, 2 );\n\nfunction wpse324908_allowed_block_types( $allowed_blocks, $post ) { \n $allowed_blocks = array(\n 'core/block', // <-- Include to show reusable blocks in the block inserter.\n 'core/image',\n 'core/paragraph',\n ); \n return $allowed_blocks; \n}\n</code></pre>\n\n<p>and it showed the <em>reusable blocks</em> within the <em>block inserter</em>, if at least two other blocks were included as well:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4hbq7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4hbq7.png\" alt=\"Reusable\"></a></p>\n\n<p>Looking at the <code>/wp-includes/js/dist/editor.js</code> we can e.g. see this check for <code>core/block</code> regarding including reusable blocks in the block inserter:</p>\n\n<pre><code>var selectors_canIncludeReusableBlockInInserter = function canIncludeReusableBlockInInserter(state, reusableBlock, rootClientId) {\n\n if (!selectors_canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId)) {\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 403633,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 0,
"selected": false,
"text": "<p>As of WP 5.8, <code>allowed_block_types</code> is deprecated. So instead, we use <code>allowed_block_types_all</code>.</p>\n<p>Example usage:</p>\n<pre><code>function cc_gutenberg_allowed_blocks($block_editor_context, $editor_context) {\n if ( !empty( $editor_context->post ) ) {\n\n // allow these blocks\n $allowed_blocks = array(\n 'core/image',\n 'core/paragraph',\n 'core/heading',\n );\n\n // target specific post type\n if ( $editor_context->post->post_type === 'page' ) {\n $allowed_blocks[] = 'core/shortcode';\n }\n\n return $allowed_blocks;\n\n }\n\n return $block_editor_context;\n}\nadd_filter( 'allowed_block_types_all', 'cc_gutenberg_allowed_blocks', 10, 2 );\n</code></pre>\n"
}
] | 2019/01/07 | [
"https://wordpress.stackexchange.com/questions/324908",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/153404/"
] | I have been follow a tutorial here: <https://rudrastyh.com/gutenberg/remove-default-blocks.html> Where it discusses how to remove default Gutenberg blocks like so:
```
add_filter( 'allowed_block_types', 'misha_allowed_block_types', 10, 2 );
function misha_allowed_block_types( $allowed_blocks, $post ) {
$allowed_blocks = array(
'core/image',
'core/paragraph',
'core/heading',
'core/list'
);
if( $post->post_type === 'page' ) {
$allowed_blocks[] = 'core/shortcode';
}
return $allowed_blocks;
}
```
So what this is doing is limiting the default Gutenberg blocks to image, paragraph, heading, and list. I then set the page post type to also allow for the shortcode block. So this works fine, but I am now having an issue where it removes the functionality of reusable blocks and I can't figure out what needs to be added to add that functionality back.
I tried commenting on that article, but the author wasn't able to think of a solution currently. I was wondering if anyone had any ideas on adding the reusable block functionality back after adding the above code snippet? | The *reusable block* is registered with the `core/block` name.
I tried to add it to the *allowed blocks* in the `allowed_block_types` filter, here's an example:
```
add_filter( 'allowed_block_types', 'wpse324908_allowed_block_types', 10, 2 );
function wpse324908_allowed_block_types( $allowed_blocks, $post ) {
$allowed_blocks = array(
'core/block', // <-- Include to show reusable blocks in the block inserter.
'core/image',
'core/paragraph',
);
return $allowed_blocks;
}
```
and it showed the *reusable blocks* within the *block inserter*, if at least two other blocks were included as well:
[](https://i.stack.imgur.com/4hbq7.png)
Looking at the `/wp-includes/js/dist/editor.js` we can e.g. see this check for `core/block` regarding including reusable blocks in the block inserter:
```
var selectors_canIncludeReusableBlockInInserter = function canIncludeReusableBlockInInserter(state, reusableBlock, rootClientId) {
if (!selectors_canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId)) {
return false;
}
``` |
324,923 | <p>I'm a newbie at even trying to work with PHP, but thinking there may be a simple solution to this. EXIF exposure data is only displaying an "s", so there must be an error. </p>
<p>I'd also like to display FNumber as "Aperture" with common f-stop, such as "f2.8", but it shows a fraction 28/10. Is there PHP code that can be inserted directly to the template file to convert this? In Wordpress image.php, there is code for simplifying fractions, but these values are not being passed through the file - they are being modified directly in the template file. There's definitely something wrong with this...</p>
<pre><code><dt>EXIF data:</dt>
<dd><ul>
<?php foreach ($exif as $key => $value):
if (($key != "Width") && ($key != "Height") && ($key !="DateTime")): ?><li><strong><?php
if ($key == "model") {
echo "Camera";
} elseif ($key == "ExposureTime") {
echo "Exposure";
$newvalue = explode("(", $value);
$newvalue = substr($newvalue[2], 0, -1)."s";
} elseif ($key == "FNumber") {
echo "Aperture";
} else {
echo $key;
} ?></strong>: <?php if (!$newvalue) { echo $value; } else { echo $newvalue; $newvalue = ''; } ?></li>
<?php endif;
endforeach; ?>
</ul></dd></dl>
</code></pre>
<p>Here is the var_export($exif) info:</p>
<pre><code>array (
'Model' => 'Canon EOS 30D',
'DateTime' => '2006:12:23 08:35:02',
'ExposureTime' => '1/100',
'FNumber' => '28/10',
'ExposureProgram' => 3,
'ISOSpeedRatings' => 200,
'ExifVersion' => '0221',
'ApertureValue' => '194698/65536',
'ExposureBiasValue' => '-1/3',
'MeteringMode' => 5,
'FocalLength' => '70/1',
)
</code></pre>
| [
{
"answer_id": 324929,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>The <em>reusable block</em> is registered with the <code>core/block</code> name.</p>\n\n<p>I tried to add it to the <em>allowed blocks</em> in the <code>allowed_block_types</code> filter, here's an example:</p>\n\n<pre><code>add_filter( 'allowed_block_types', 'wpse324908_allowed_block_types', 10, 2 );\n\nfunction wpse324908_allowed_block_types( $allowed_blocks, $post ) { \n $allowed_blocks = array(\n 'core/block', // <-- Include to show reusable blocks in the block inserter.\n 'core/image',\n 'core/paragraph',\n ); \n return $allowed_blocks; \n}\n</code></pre>\n\n<p>and it showed the <em>reusable blocks</em> within the <em>block inserter</em>, if at least two other blocks were included as well:</p>\n\n<p><a href=\"https://i.stack.imgur.com/4hbq7.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/4hbq7.png\" alt=\"Reusable\"></a></p>\n\n<p>Looking at the <code>/wp-includes/js/dist/editor.js</code> we can e.g. see this check for <code>core/block</code> regarding including reusable blocks in the block inserter:</p>\n\n<pre><code>var selectors_canIncludeReusableBlockInInserter = function canIncludeReusableBlockInInserter(state, reusableBlock, rootClientId) {\n\n if (!selectors_canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId)) {\n return false;\n }\n</code></pre>\n"
},
{
"answer_id": 403633,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 0,
"selected": false,
"text": "<p>As of WP 5.8, <code>allowed_block_types</code> is deprecated. So instead, we use <code>allowed_block_types_all</code>.</p>\n<p>Example usage:</p>\n<pre><code>function cc_gutenberg_allowed_blocks($block_editor_context, $editor_context) {\n if ( !empty( $editor_context->post ) ) {\n\n // allow these blocks\n $allowed_blocks = array(\n 'core/image',\n 'core/paragraph',\n 'core/heading',\n );\n\n // target specific post type\n if ( $editor_context->post->post_type === 'page' ) {\n $allowed_blocks[] = 'core/shortcode';\n }\n\n return $allowed_blocks;\n\n }\n\n return $block_editor_context;\n}\nadd_filter( 'allowed_block_types_all', 'cc_gutenberg_allowed_blocks', 10, 2 );\n</code></pre>\n"
}
] | 2019/01/07 | [
"https://wordpress.stackexchange.com/questions/324923",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158549/"
] | I'm a newbie at even trying to work with PHP, but thinking there may be a simple solution to this. EXIF exposure data is only displaying an "s", so there must be an error.
I'd also like to display FNumber as "Aperture" with common f-stop, such as "f2.8", but it shows a fraction 28/10. Is there PHP code that can be inserted directly to the template file to convert this? In Wordpress image.php, there is code for simplifying fractions, but these values are not being passed through the file - they are being modified directly in the template file. There's definitely something wrong with this...
```
<dt>EXIF data:</dt>
<dd><ul>
<?php foreach ($exif as $key => $value):
if (($key != "Width") && ($key != "Height") && ($key !="DateTime")): ?><li><strong><?php
if ($key == "model") {
echo "Camera";
} elseif ($key == "ExposureTime") {
echo "Exposure";
$newvalue = explode("(", $value);
$newvalue = substr($newvalue[2], 0, -1)."s";
} elseif ($key == "FNumber") {
echo "Aperture";
} else {
echo $key;
} ?></strong>: <?php if (!$newvalue) { echo $value; } else { echo $newvalue; $newvalue = ''; } ?></li>
<?php endif;
endforeach; ?>
</ul></dd></dl>
```
Here is the var\_export($exif) info:
```
array (
'Model' => 'Canon EOS 30D',
'DateTime' => '2006:12:23 08:35:02',
'ExposureTime' => '1/100',
'FNumber' => '28/10',
'ExposureProgram' => 3,
'ISOSpeedRatings' => 200,
'ExifVersion' => '0221',
'ApertureValue' => '194698/65536',
'ExposureBiasValue' => '-1/3',
'MeteringMode' => 5,
'FocalLength' => '70/1',
)
``` | The *reusable block* is registered with the `core/block` name.
I tried to add it to the *allowed blocks* in the `allowed_block_types` filter, here's an example:
```
add_filter( 'allowed_block_types', 'wpse324908_allowed_block_types', 10, 2 );
function wpse324908_allowed_block_types( $allowed_blocks, $post ) {
$allowed_blocks = array(
'core/block', // <-- Include to show reusable blocks in the block inserter.
'core/image',
'core/paragraph',
);
return $allowed_blocks;
}
```
and it showed the *reusable blocks* within the *block inserter*, if at least two other blocks were included as well:
[](https://i.stack.imgur.com/4hbq7.png)
Looking at the `/wp-includes/js/dist/editor.js` we can e.g. see this check for `core/block` regarding including reusable blocks in the block inserter:
```
var selectors_canIncludeReusableBlockInInserter = function canIncludeReusableBlockInInserter(state, reusableBlock, rootClientId) {
if (!selectors_canInsertBlockTypeUnmemoized(state, 'core/block', rootClientId)) {
return false;
}
``` |
324,927 | <p>I want to use the WYWISWYG on my blog page for an introduction text, but can't seem to bring back the WYSIWYG Editor on the page the page I defined as my blog posts page.</p>
<p>Is there any way to force WP to still show the WYSIWYG on the Blog posts page?</p>
<p><a href="https://i.stack.imgur.com/sjDej.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sjDej.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 324928,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 3,
"selected": true,
"text": "<p><strong>Pre WP 4.9</strong></p>\n\n<pre><code>if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {\n\n /**\n * Add the wp-editor back into WordPress after it was removed in 4.2.2.\n *\n * @param Object $post\n * @return void\n */\n function fix_no_editor_on_posts_page( $post ) {\n if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {\n return;\n }\n\n remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );\n add_post_type_support( 'page', 'editor' );\n }\n add_action( 'edit_form_after_title', 'fix_no_editor_on_posts_page', 0 );\n}\n</code></pre>\n\n<p><strong>WP 4.9</strong></p>\n\n<pre><code>if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {\n\n function fix_no_editor_on_posts_page( $post_type, $post ) {\n if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {\n return;\n }\n\n remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );\n add_post_type_support( 'page', 'editor' );\n }\n\n add_action( 'add_meta_boxes', 'fix_no_editor_on_posts_page', 0, 2 );\n\n}\n</code></pre>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/193756/86845\">Full Details Here</a></p>\n"
},
{
"answer_id": 324930,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>If you want a quick manual fix-</p>\n\n<p>The problem is that the page's content is currently empty.</p>\n\n<ol>\n<li>Switch the page for posts to a temporary page,</li>\n<li>edit the original page and add some content,</li>\n<li>save,</li>\n<li>set the page for posts page back to the original page.</li>\n</ol>\n\n<p>You'll now be able to edit it whenever you want, as long as you don't empty it again.</p>\n"
}
] | 2019/01/07 | [
"https://wordpress.stackexchange.com/questions/324927",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/8895/"
] | I want to use the WYWISWYG on my blog page for an introduction text, but can't seem to bring back the WYSIWYG Editor on the page the page I defined as my blog posts page.
Is there any way to force WP to still show the WYSIWYG on the Blog posts page?
[](https://i.stack.imgur.com/sjDej.png) | **Pre WP 4.9**
```
if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {
/**
* Add the wp-editor back into WordPress after it was removed in 4.2.2.
*
* @param Object $post
* @return void
*/
function fix_no_editor_on_posts_page( $post ) {
if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {
return;
}
remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );
add_post_type_support( 'page', 'editor' );
}
add_action( 'edit_form_after_title', 'fix_no_editor_on_posts_page', 0 );
}
```
**WP 4.9**
```
if( ! function_exists( 'fix_no_editor_on_posts_page' ) ) {
function fix_no_editor_on_posts_page( $post_type, $post ) {
if( isset( $post ) && $post->ID != get_option('page_for_posts') ) {
return;
}
remove_action( 'edit_form_after_title', '_wp_posts_page_notice' );
add_post_type_support( 'page', 'editor' );
}
add_action( 'add_meta_boxes', 'fix_no_editor_on_posts_page', 0, 2 );
}
```
[Full Details Here](https://wordpress.stackexchange.com/a/193756/86845) |
324,935 | <p>I have a WP site which I have not looked at for a while. I have just logged in to update aspects of it, including WP itself, now on 5.0.2. </p>
<p>Now if I click on any of the Dashboard links - Posts, Appearance etc - I get Page Not Found. If I delete the HTAccess then it works again ... until WP reinstates it. There is nothing special about the site.</p>
<p>The HTAccess is the standard WP one:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>How can I track down what is going wrong?</p>
| [
{
"answer_id": 324936,
"author": "Highly Irregular",
"author_id": 76260,
"author_profile": "https://wordpress.stackexchange.com/users/76260",
"pm_score": 1,
"selected": false,
"text": "<p>I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wondering if the issue is caused by caching (by a plugin or theme). </p>\n\n<p>If you have a caching plugin, or a theme that does caching, there should be a tool in the Dashboard for emptying/clearing/deleting the cache. Click this, and see if it fixes the issue. I've only tried this once, but it did work. </p>\n\n<p>I believe it is generally recommended to clear the cache whenever a software update is installed (plugin, theme, or WordPress), so that might be something you could try to add to your process in future to prevent the issue.</p>\n"
},
{
"answer_id": 324938,
"author": "Junnel Gallemaso",
"author_id": 104638,
"author_profile": "https://wordpress.stackexchange.com/users/104638",
"pm_score": 0,
"selected": false,
"text": "<p>Try to change the theme first by activating default theme e.g. Twenty Nineteen and check your back-end to make sure that the issue is not your theme. If that did not work, do a plugin audit by de-activating all and re-activating them one by one.</p>\n\n<p>Alternatively, you can go to settings > Permalinks and re-flush by just clicking the Save button (without any changes in the settings).</p>\n\n<p>However, I suspect that it is a theme issue as you said, you have not checked your website for a while and the theme might not be already not compatible with latest WordPress version.</p>\n\n<p>Hope that helps!</p>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/324935",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38223/"
] | I have a WP site which I have not looked at for a while. I have just logged in to update aspects of it, including WP itself, now on 5.0.2.
Now if I click on any of the Dashboard links - Posts, Appearance etc - I get Page Not Found. If I delete the HTAccess then it works again ... until WP reinstates it. There is nothing special about the site.
The HTAccess is the standard WP one:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
How can I track down what is going wrong? | I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wondering if the issue is caused by caching (by a plugin or theme).
If you have a caching plugin, or a theme that does caching, there should be a tool in the Dashboard for emptying/clearing/deleting the cache. Click this, and see if it fixes the issue. I've only tried this once, but it did work.
I believe it is generally recommended to clear the cache whenever a software update is installed (plugin, theme, or WordPress), so that might be something you could try to add to your process in future to prevent the issue. |
324,958 | <pre><code><?php function consultation_user_profile_fields($user){
if ( user_can( $user->ID, "subscriber" ) ) {
?>
<h3>Consultation</h3>
<?php $query = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'consultation',
'post_status' => 'publish'
)
);
if ($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
$hasAccess = '';
if ( is_object( $user ) && isset( $user->ID ) ) {
$hasAccess = get_user_meta(
$user>ID,'consultation'.get_the_ID(), true );
} ?>
<div class="consultation">
<span>Has access&nbsp;</span>
<div class="title"><?php the_title(); ?></div>
<input type="checkbox" id="consultation[<?= get_the_ID(); ?>]"
class="regular-text" name="consultation[<?= get_the_ID(); ?>]"
value="1" <?= ($hasAccess == 1 ? 'checked' : ''); ?>/>
</div>
<?php endwhile; endif;
} else {
return;
}
}
add_action( 'show_user_profile', 'consultation_user_profile_fields' );
add_action( 'edit_user_profile', 'consultation_user_profile_fields' );
add_action( "user_new_form", "consultation_user_profile_fields" );
function save_consultation_user_profile_fields($user_id){
if(!current_user_can('manage_options'))
return false;
foreach ($_POST['consultation'] as $key => $val) {
update_user_meta($user_id,'consultation'.$key,$_POST['consultation'][$key]);
}
# save my custom field
}
add_action( 'user_register', 'save_consultation_user_profile_fields');
add_action('personal_options_update','save_consultation_user_profile_fields' );
add_action( 'edit_user_profile_update','save_consultation_user_profile_fields' );
</code></pre>
| [
{
"answer_id": 324936,
"author": "Highly Irregular",
"author_id": 76260,
"author_profile": "https://wordpress.stackexchange.com/users/76260",
"pm_score": 1,
"selected": false,
"text": "<p>I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wondering if the issue is caused by caching (by a plugin or theme). </p>\n\n<p>If you have a caching plugin, or a theme that does caching, there should be a tool in the Dashboard for emptying/clearing/deleting the cache. Click this, and see if it fixes the issue. I've only tried this once, but it did work. </p>\n\n<p>I believe it is generally recommended to clear the cache whenever a software update is installed (plugin, theme, or WordPress), so that might be something you could try to add to your process in future to prevent the issue.</p>\n"
},
{
"answer_id": 324938,
"author": "Junnel Gallemaso",
"author_id": 104638,
"author_profile": "https://wordpress.stackexchange.com/users/104638",
"pm_score": 0,
"selected": false,
"text": "<p>Try to change the theme first by activating default theme e.g. Twenty Nineteen and check your back-end to make sure that the issue is not your theme. If that did not work, do a plugin audit by de-activating all and re-activating them one by one.</p>\n\n<p>Alternatively, you can go to settings > Permalinks and re-flush by just clicking the Save button (without any changes in the settings).</p>\n\n<p>However, I suspect that it is a theme issue as you said, you have not checked your website for a while and the theme might not be already not compatible with latest WordPress version.</p>\n\n<p>Hope that helps!</p>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/324958",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158575/"
] | ```
<?php function consultation_user_profile_fields($user){
if ( user_can( $user->ID, "subscriber" ) ) {
?>
<h3>Consultation</h3>
<?php $query = new WP_Query(
array(
'posts_per_page' => -1,
'post_type' => 'consultation',
'post_status' => 'publish'
)
);
if ($query->have_posts()) :
while($query->have_posts()) : $query->the_post();
$hasAccess = '';
if ( is_object( $user ) && isset( $user->ID ) ) {
$hasAccess = get_user_meta(
$user>ID,'consultation'.get_the_ID(), true );
} ?>
<div class="consultation">
<span>Has access </span>
<div class="title"><?php the_title(); ?></div>
<input type="checkbox" id="consultation[<?= get_the_ID(); ?>]"
class="regular-text" name="consultation[<?= get_the_ID(); ?>]"
value="1" <?= ($hasAccess == 1 ? 'checked' : ''); ?>/>
</div>
<?php endwhile; endif;
} else {
return;
}
}
add_action( 'show_user_profile', 'consultation_user_profile_fields' );
add_action( 'edit_user_profile', 'consultation_user_profile_fields' );
add_action( "user_new_form", "consultation_user_profile_fields" );
function save_consultation_user_profile_fields($user_id){
if(!current_user_can('manage_options'))
return false;
foreach ($_POST['consultation'] as $key => $val) {
update_user_meta($user_id,'consultation'.$key,$_POST['consultation'][$key]);
}
# save my custom field
}
add_action( 'user_register', 'save_consultation_user_profile_fields');
add_action('personal_options_update','save_consultation_user_profile_fields' );
add_action( 'edit_user_profile_update','save_consultation_user_profile_fields' );
``` | I've had this issue on a small number of sites (out of around 60 that I help manage), and I'm wondering if the issue is caused by caching (by a plugin or theme).
If you have a caching plugin, or a theme that does caching, there should be a tool in the Dashboard for emptying/clearing/deleting the cache. Click this, and see if it fixes the issue. I've only tried this once, but it did work.
I believe it is generally recommended to clear the cache whenever a software update is installed (plugin, theme, or WordPress), so that might be something you could try to add to your process in future to prevent the issue. |
324,962 | <p>I have a wordpress website in which I have a specific page for dictionary. This page is actually a custom page and does these things:</p>
<ul>
<li><code>site.com/dictionary</code> lists all the words</li>
<li><code>site.com/dictionary/?w=word</code> shows the definition of the word</li>
</ul>
<p>now I want the URL to be cleaned up and becomes like this:</p>
<pre><code>site.com/dictionary/word
</code></pre>
<p>I have made these lines in <code>.htaccess</code> but I get <code>404</code> error:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /dictionary/
RewriteRule (.*) ?w=$1 [L]
</IfModule>
</code></pre>
<p>May you help me with this?</p>
<p>update:</p>
<p>I have tried the solution here: <a href="https://stackoverflow.com/questions/27162489/">https://stackoverflow.com/questions/27162489/</a> but this also didn't work for me.</p>
| [
{
"answer_id": 324968,
"author": "André Kelling",
"author_id": 136930,
"author_profile": "https://wordpress.stackexchange.com/users/136930",
"pm_score": 1,
"selected": false,
"text": "<p>You can't just rewrite the URL.</p>\n\n<p>You would need to refactor a lot code when using that other URL path <code>/word</code> over an URL parameter <code>?w=word</code>.</p>\n\n<p>That are two different pairs of shoes...</p>\n\n<p><strong>some more info:</strong></p>\n\n<p>Routing with PHP in WordPress is a complex topic and not easy to describe in a few words. Even as an experienced developer, you probably won't want to be confronted with routing problems.</p>\n\n<p>Here there is a short example on how PHP routing can work: <a href=\"https://www.taniarascia.com/the-simplest-php-router/\" rel=\"nofollow noreferrer\">https://www.taniarascia.com/the-simplest-php-router/</a></p>\n"
},
{
"answer_id": 325078,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>You can do this with the internal rewrite system, which is parsed in php, not htaccess.</p>\n\n<p>First, add the rule. This assumes you have created a root page under <code>Pages</code> with the slug <code>dictionary</code>.</p>\n\n<pre><code>function wpd_dictionary_rewrite(){\n add_rewrite_tag( '%dictionary_word%', '([^/]+)' );\n add_rewrite_rule(\n '^dictionary/([^/]+)/?$',\n 'index.php?pagename=dictionary&dictionary_word=$matches[1]',\n 'top'\n );\n}\nadd_action( 'init', 'wpd_dictionary_rewrite' );\n</code></pre>\n\n<p>This code would go in your theme's <code>functions.php</code> file, or your own plugin.</p>\n\n<p>Visit the <code>Settings > Permalinks</code> page to flush rules after adding this.</p>\n\n<p>Now you can visit <code>site.com/dictionary/word</code> and the requested word will be available in the template with <code>get_query_var('dictionary_word')</code>.</p>\n\n<p>If the code relies on <code>$_GET['w']</code> and you can't / don't want to change this, you can hook before the code runs and set the value manually:</p>\n\n<pre><code>function wpd_set_dictionary_word(){\n if( false !== get_query_var( 'dictionary_word', false ) ){\n $_GET['w'] = get_query_var( 'dictionary_word' );\n }\n}\nadd_action( 'wp', 'wpd_set_dictionary_word' );\n</code></pre>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/324962",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89930/"
] | I have a wordpress website in which I have a specific page for dictionary. This page is actually a custom page and does these things:
* `site.com/dictionary` lists all the words
* `site.com/dictionary/?w=word` shows the definition of the word
now I want the URL to be cleaned up and becomes like this:
```
site.com/dictionary/word
```
I have made these lines in `.htaccess` but I get `404` error:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /dictionary/
RewriteRule (.*) ?w=$1 [L]
</IfModule>
```
May you help me with this?
update:
I have tried the solution here: <https://stackoverflow.com/questions/27162489/> but this also didn't work for me. | You can do this with the internal rewrite system, which is parsed in php, not htaccess.
First, add the rule. This assumes you have created a root page under `Pages` with the slug `dictionary`.
```
function wpd_dictionary_rewrite(){
add_rewrite_tag( '%dictionary_word%', '([^/]+)' );
add_rewrite_rule(
'^dictionary/([^/]+)/?$',
'index.php?pagename=dictionary&dictionary_word=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_dictionary_rewrite' );
```
This code would go in your theme's `functions.php` file, or your own plugin.
Visit the `Settings > Permalinks` page to flush rules after adding this.
Now you can visit `site.com/dictionary/word` and the requested word will be available in the template with `get_query_var('dictionary_word')`.
If the code relies on `$_GET['w']` and you can't / don't want to change this, you can hook before the code runs and set the value manually:
```
function wpd_set_dictionary_word(){
if( false !== get_query_var( 'dictionary_word', false ) ){
$_GET['w'] = get_query_var( 'dictionary_word' );
}
}
add_action( 'wp', 'wpd_set_dictionary_word' );
``` |
324,970 | <p>I was looking for a clean way to group my search results by posttype. I currently have 3 post types: <em>Page</em>, <em>Post</em> and <em>Glossary</em>. After a long search <a href="https://wordpress.stackexchange.com/a/181807/75046">this answer</a> in this thread got me what I needed. </p>
<p>The only problem is that there is no check for when a post type has no search results. If a post type has 0 results, e.g. <em>Glossary</em>, it still shows the post type title (and the container around the post type). I want the post type <code>li.search-results-post-type-item</code> to be hidden in that case.</p>
<p>I am not looking for a css/js hacky <code>display: none;</code> solution. I can't imagine this can't be done with PHP.</p>
<p>Thanks in advance!</p>
<h2>Current situation</h2>
<p><strong>Posts</strong></p>
<ul>
<li>Post search result 1</li>
<li>Post search result 2</li>
<li>etc.</li>
</ul>
<p><strong>Pages</strong></p>
<ul>
<li>Page search result 1</li>
<li>Page search result 2</li>
<li>etc.</li>
</ul>
<p><strong>Glossary</strong></p>
<p>(empty)</p>
<h2>Desired situation</h2>
<p><strong>Posts</strong></p>
<ul>
<li>Post search result 1</li>
<li>Post search result 2</li>
<li>etc.</li>
</ul>
<p><strong>Pages</strong></p>
<ul>
<li>Page search result 1</li>
<li>Page search result 2</li>
<li>etc.</li>
</ul>
<hr>
<p>My code so far:</p>
<pre><code><?php
$search_query = new WP_Query(
array(
'posts_per_page' => 10,
's' => esc_attr( $_POST['keyword'] ),
'paged' => $paged,
'post_status' => 'publish'
)
);
if( $search_query->have_posts() ) : ?>
<div class="search-suggestions-list-header">
<?php echo $search_query->found_posts.' results found'; ?>
</div>
<ul class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
foreach( $types as $type ) : ?>
<li class="search-results-post-type-item post-type-<?php echo $type ?>">
<header class="post-type-header">
<h5 class="post-type-title">
<?php
$post_type_obj = get_post_type_object( $type );
echo $post_type_obj->labels->name
?>
</h5>
</header>
<ul class="search-results-list">
<?php
while( $search_query->have_posts() ): $search_query->the_post();
if( $type == get_post_type() ) : ?>
<li class="search-results-list-item">
<h4 class="entry-title"><?php the_title();?></h4>
</li>
<?php
endif;
endwhile;
wp_reset_postdata();
?>
</ul>
</li>
<?php endforeach; ?>
</ul>
<?php else:
echo '<div class="search-suggestions-no-results">
<p>' . __('Sorry, no results found', 'text-domain') . '</p>
</div>';
endif;
</code></pre>
| [
{
"answer_id": 324971,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>Try to put <code><?php wp_reset_postdata(); ?></code> just after endif and check it is working or not and let me know if the problem is still persist.</p>\n"
},
{
"answer_id": 333914,
"author": "Samuel Esteban",
"author_id": 164767,
"author_profile": "https://wordpress.stackexchange.com/users/164767",
"pm_score": 0,
"selected": false,
"text": "<p>I has the same trouble.</p>\n\n<p>My solution:</p>\n\n<ol>\n<li>The <code>$post_type</code> array must be outside the <code>WP_Query</code>.</li>\n<li>The <code>WP_Query</code> must be inside the <code>foreach</code> statement.</li>\n</ol>\n\n<p>So... Your code goes like this:</p>\n\n<pre><code><?php\n // Here, the Types\n $types = array( 'post', 'page', 'glossary' );\n\n foreach( $types as $type ) :\n\n // Search Args better in a variable (for order purposes)\n $search_args = array(\n 'posts_per_page' => 10,\n 's' => esc_attr( $_POST['keyword'] ),\n 'paged' => $paged,\n 'post_status' => 'publish',\n 'post_type' => $type // This line was added\n );\n\n $search_query = new WP_Query($search_args);\n\n if( $search_query->have_posts() ) : ?>\n\n <div class=\"search-suggestions-list-header\">\n <?php echo $search_query->found_posts.' results found'; ?>\n </div>\n\n <ul class=\"search-results-list\">\n\n <li class=\"search-results-post-type-item post-type-<?php echo $type; ?>\">\n\n <header class=\"post-type-header\">\n <h5 class=\"post-type-title\">\n <?php\n $post_type_obj = get_post_type_object($type);\n echo $post_type_obj->labels->name;\n ?>\n </h5>\n </header>\n\n <ul class=\"search-results-list\">\n <?php\n while( $search_query->have_posts() ): $search_query->the_post();\n if( $type == get_post_type() ) : ?>\n <li class=\"search-results-list-item\">\n <h4 class=\"entry-title\"><?php the_title();?></h4>\n </li>\n <?php\n endif; // I think you'll need for style propouses\n endwhile;\n ?>\n </ul>\n </li>\n\n </ul>\n\n<?php else:\n echo '<div class=\"search-suggestions-no-results\">\n <p>' . __('Sorry, no results found', 'text-domain') . '</p>\n </div>';\nendif;\n\nwp_reset_postdata(); // Here goes the reset\n\nendforeach; // End Foreach ?>\n</code></pre>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 333920,
"author": "nmr",
"author_id": 147428,
"author_profile": "https://wordpress.stackexchange.com/users/147428",
"pm_score": 1,
"selected": false,
"text": "<p>To avoid types with no results you can e.g.</p>\n\n<ul>\n<li>one additional time go through the loop and count the occurrences of each type, the number of returned results is not large (only 10 per page)</li>\n<li>display the type title when you encounter the first post with the given type (move to inside <code>while</code> loop, I know, less readable code)</li>\n<li>go through the loop one time and collect post titles to the table divided into types</li>\n</ul>\n\n<h2>First option</h2>\n\n<pre><code><ul class=\"search-results-list\">\n <?php\n\n $types = array( 'post', 'page', 'glossary' );\n $occurrences = [];\n while( $search_query->have_posts() )\n {\n $search_query->next_post();\n $type = $search_query->post->post_type;\n if ( !isset($occurrences[$type]) )\n $occurrences[$type] = 1;\n else\n $occurrences[$type] += 1;\n }\n rewind_posts();\n\n foreach( $types as $type ) : \n\n if ( !isset($occurrences[$type]) )\n continue;\n ?>\n <li class=\"search-results-post-type-item post-type-<?php echo $type ?>\">\n //\n // remaining code\n //\n </li>\n\n <?php endforeach; ?>\n</ul>\n</code></pre>\n\n<h2>Second option</h2>\n\n<pre><code>$types = array( 'post', 'page', 'glossary' );\nforeach( $types as $type ) : \n\n $type_header_printed = false;\n ?>\n <?php\n while( $search_query->have_posts() ): \n $search_query->the_post();\n if( $type == get_post_type() ) :\n\n // -- post type header -----\n if ( !$type_header_printed ) : \n\n $type_header_printed = true;\n ?>\n <li class=\"search-results-post-type-item post-type-<?php echo $type ?>\">\n <header class=\"post-type-header\">\n <h5 class=\"post-type-title\">\n <?php\n $post_type_obj = get_post_type_object( $type );\n echo $post_type_obj->labels->name\n ?>\n </h5>\n </header> \n <ul class=\"search-results-list\">\n\n <?php // -- header end -----\n endif; ?>\n\n <li class=\"search-results-list-item\">\n <h4 class=\"entry-title\"><?php the_title();?></h4>\n </li>\n <?php\n\n endif;\n endwhile;\n rewind_posts();\n\n if ( $type_header_printed ) : ?>\n </ul>\n </li>\n <?php endif; ?>\n\n<?php endforeach; ?>\n</code></pre>\n\n<h2>Third option</h2>\n\n<pre><code><ul class=\"search-results-list\">\n <?php\n\n $types = array( 'post', 'page', 'glossary' );\n $posts_titles = [];\n while( $search_query->have_posts() )\n {\n $search_query->the_post();\n $type = $search_query->post->post_type;\n if ( !isset($posts_titles[$type]) )\n $posts_titles[$type] = [];\n\n $posts_titles[$type][] = get_the_title();\n }\n rewind_posts();\n\n foreach( $types as $type ) : \n\n if ( !isset($posts_titles[$type]) )\n continue;\n ?>\n <li class=\"search-results-post-type-item post-type-<?php echo $type ?>\">\n <header class=\"post-type-header\">\n <h5 class=\"post-type-title\">\n <?php\n $post_type_obj = get_post_type_object( $type );\n echo $post_type_obj->labels->name\n ?>\n </h5>\n </header>\n <ul class=\"search-results-list\">\n\n <?php foreach( $posts_titles[$type] as $title ) : ?>\n <li class=\"search-results-list-item\">\n <h4 class=\"entry-title\"><?php echo htmlspecialchars($title); ?></h4>\n </li>\n <?php endforeach; ?>\n\n </ul>\n </li>\n\n <?php endforeach; ?>\n</ul>\n</code></pre>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/324970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75046/"
] | I was looking for a clean way to group my search results by posttype. I currently have 3 post types: *Page*, *Post* and *Glossary*. After a long search [this answer](https://wordpress.stackexchange.com/a/181807/75046) in this thread got me what I needed.
The only problem is that there is no check for when a post type has no search results. If a post type has 0 results, e.g. *Glossary*, it still shows the post type title (and the container around the post type). I want the post type `li.search-results-post-type-item` to be hidden in that case.
I am not looking for a css/js hacky `display: none;` solution. I can't imagine this can't be done with PHP.
Thanks in advance!
Current situation
-----------------
**Posts**
* Post search result 1
* Post search result 2
* etc.
**Pages**
* Page search result 1
* Page search result 2
* etc.
**Glossary**
(empty)
Desired situation
-----------------
**Posts**
* Post search result 1
* Post search result 2
* etc.
**Pages**
* Page search result 1
* Page search result 2
* etc.
---
My code so far:
```
<?php
$search_query = new WP_Query(
array(
'posts_per_page' => 10,
's' => esc_attr( $_POST['keyword'] ),
'paged' => $paged,
'post_status' => 'publish'
)
);
if( $search_query->have_posts() ) : ?>
<div class="search-suggestions-list-header">
<?php echo $search_query->found_posts.' results found'; ?>
</div>
<ul class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
foreach( $types as $type ) : ?>
<li class="search-results-post-type-item post-type-<?php echo $type ?>">
<header class="post-type-header">
<h5 class="post-type-title">
<?php
$post_type_obj = get_post_type_object( $type );
echo $post_type_obj->labels->name
?>
</h5>
</header>
<ul class="search-results-list">
<?php
while( $search_query->have_posts() ): $search_query->the_post();
if( $type == get_post_type() ) : ?>
<li class="search-results-list-item">
<h4 class="entry-title"><?php the_title();?></h4>
</li>
<?php
endif;
endwhile;
wp_reset_postdata();
?>
</ul>
</li>
<?php endforeach; ?>
</ul>
<?php else:
echo '<div class="search-suggestions-no-results">
<p>' . __('Sorry, no results found', 'text-domain') . '</p>
</div>';
endif;
``` | To avoid types with no results you can e.g.
* one additional time go through the loop and count the occurrences of each type, the number of returned results is not large (only 10 per page)
* display the type title when you encounter the first post with the given type (move to inside `while` loop, I know, less readable code)
* go through the loop one time and collect post titles to the table divided into types
First option
------------
```
<ul class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
$occurrences = [];
while( $search_query->have_posts() )
{
$search_query->next_post();
$type = $search_query->post->post_type;
if ( !isset($occurrences[$type]) )
$occurrences[$type] = 1;
else
$occurrences[$type] += 1;
}
rewind_posts();
foreach( $types as $type ) :
if ( !isset($occurrences[$type]) )
continue;
?>
<li class="search-results-post-type-item post-type-<?php echo $type ?>">
//
// remaining code
//
</li>
<?php endforeach; ?>
</ul>
```
Second option
-------------
```
$types = array( 'post', 'page', 'glossary' );
foreach( $types as $type ) :
$type_header_printed = false;
?>
<?php
while( $search_query->have_posts() ):
$search_query->the_post();
if( $type == get_post_type() ) :
// -- post type header -----
if ( !$type_header_printed ) :
$type_header_printed = true;
?>
<li class="search-results-post-type-item post-type-<?php echo $type ?>">
<header class="post-type-header">
<h5 class="post-type-title">
<?php
$post_type_obj = get_post_type_object( $type );
echo $post_type_obj->labels->name
?>
</h5>
</header>
<ul class="search-results-list">
<?php // -- header end -----
endif; ?>
<li class="search-results-list-item">
<h4 class="entry-title"><?php the_title();?></h4>
</li>
<?php
endif;
endwhile;
rewind_posts();
if ( $type_header_printed ) : ?>
</ul>
</li>
<?php endif; ?>
<?php endforeach; ?>
```
Third option
------------
```
<ul class="search-results-list">
<?php
$types = array( 'post', 'page', 'glossary' );
$posts_titles = [];
while( $search_query->have_posts() )
{
$search_query->the_post();
$type = $search_query->post->post_type;
if ( !isset($posts_titles[$type]) )
$posts_titles[$type] = [];
$posts_titles[$type][] = get_the_title();
}
rewind_posts();
foreach( $types as $type ) :
if ( !isset($posts_titles[$type]) )
continue;
?>
<li class="search-results-post-type-item post-type-<?php echo $type ?>">
<header class="post-type-header">
<h5 class="post-type-title">
<?php
$post_type_obj = get_post_type_object( $type );
echo $post_type_obj->labels->name
?>
</h5>
</header>
<ul class="search-results-list">
<?php foreach( $posts_titles[$type] as $title ) : ?>
<li class="search-results-list-item">
<h4 class="entry-title"><?php echo htmlspecialchars($title); ?></h4>
</li>
<?php endforeach; ?>
</ul>
</li>
<?php endforeach; ?>
</ul>
``` |
324,979 | <p>I've registered a sidebar component in the block editor. I'd like to access the <code>state</code> of the component (<code>MyPlugin</code>) from outside of that component, in some arbitrary JavaScript in the same file. Is it possible to access the state via e.g. the <code>wp</code> object?</p>
<p>Or, is it possible, and would it be better to do this using <code>props</code>?</p>
<pre><code>class MyPlugin extends Component {
constructor() {
super( ...arguments );
// initial state
this.state = {
key: 'my_key',
value: ''
}
}
render() {
return el(
PluginPostStatusInfo,
{
className: 'my-panel-class'
},
el(
TextControl,
{
name: 'my_text_control_name',
label: __( 'My label', 'my-text-domain' ),
value: this.state.value,
onChange: ( value ) => {
this.setState( {
value
})
}
}
)
);
}
}
registerPlugin( 'my-plugin', {
render: MyPlugin
} );
const myFunction = () => {
// this function is hooked into an action elsewhere,
// and needs to access the state of MyPlugin
}
</code></pre>
<p>What I'd ultimately like to do is access the textbox's value from a separate function. I don't mind how this is achieved, e.g. with <code>state</code> or <code>props</code> or some other means. I guess another approach would be to have the component write its value into a global variable when it changes, but that seems a bit clunky.</p>
| [
{
"answer_id": 324980,
"author": "Sean",
"author_id": 138112,
"author_profile": "https://wordpress.stackexchange.com/users/138112",
"pm_score": 1,
"selected": false,
"text": "<p>I found a solution, but I'm not sure it's really the intended way to do this. I use the core editor datastore to set the value, then retrieve it from there in my function.</p>\n\n<p>In the <code>onChange</code> callback in <code>MyPlugin</code>, in addition to setting the state I also save the value:</p>\n\n<pre><code>onChange: ( value ) => {\n this.setState( {\n value\n })\n\n // set data in store\n wp.data.select('core/editor').my_custom_key = value;\n}\n</code></pre>\n\n<p>then in my function I just grab it out:</p>\n\n<pre><code>const myFunction = () => {\n var myData = wp.data.select('core/editor').my_custom_key;\n\n // do stuff with myData...\n}\n</code></pre>\n"
},
{
"answer_id": 325042,
"author": "Alvaro",
"author_id": 16533,
"author_profile": "https://wordpress.stackexchange.com/users/16533",
"pm_score": 4,
"selected": true,
"text": "<p>To do so you need to use a redux store. To register your own you can follow the steps in the <a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/data\" rel=\"noreferrer\">documentation</a>. Here is the minimum that should achieve what you are looking for.</p>\n\n<p>First, lets give the \"shape\" of the store in the initial state object:</p>\n\n<pre><code>const initial_state = {\n my_control: {\n value: \"\"\n },\n};\n</code></pre>\n\n<p>Lets create a reducer that manipulates the state:</p>\n\n<pre><code>const reducer = (state = initial_state, action) => {\n switch (action.type) {\n case \"UPDATE_MY_CONTROL_VALUE\": {\n return {\n ...state,\n my_control: {\n ...state.my_control,\n value: action.value\n }\n };\n }\n }\n\n return state;\n};\n</code></pre>\n\n<p>As you can see, we set the <code>initial_state</code> object we just created as the default value of the state.</p>\n\n<p>Now lets add an action which updates the store, sending data to the reducer:</p>\n\n<pre><code>const actions = {\n updateMyControlValue(value) {\n return {\n type: \"UPDATE_MY_CONTROL_VALUE\",\n value\n };\n },\n}\n</code></pre>\n\n<p>Lets add a selector that gets the data from the store:</p>\n\n<pre><code>const selectors = {\n getMyControlValue(state) {\n return state.my_control.value;\n },\n};\n</code></pre>\n\n<p>And now we will register the store with the previous constants:</p>\n\n<pre><code>const { registerStore } = wp.data;\n\nregisterStore(\"my_plugin/my_store\", {\n reducer,\n actions,\n selectors\n});\n</code></pre>\n\n<p>Now the store is registered. We will connect the component to the store to get the latest value of my_control and to update it:</p>\n\n<pre><code>const { Component } = wp.element;\nconst { TextControl } = wp.components;\nconst { compose } = wp.compose;\nconst { withDispatch, withSelect } = wp.data;\n\nclass Text extends Component {\n render() {\n const { value, updateMyControlValue } = this.props;\n\n return (\n <TextControl\n value={value}\n onChange={updateMyControlValue}\n />\n );\n }\n}\n\nexport default compose([\n withDispatch((dispatch, props) => {\n // This function here is the action we created before.\n const { updateMyControlValue } = dispatch(\"my_plugin/my_store\");\n\n return {\n updateMyControlValue\n };\n }),\n withSelect((select, props) => {\n // This function here is the selector we created before.\n const { getMyControlValue } = select(\"my_plugin/my_store\");\n\n return {\n value: getMyControlValue()\n };\n }),\n])(Text);\n</code></pre>\n\n<hr>\n\n<p>This is a simple example, but you can take a look at the link on the documentation to see how you can use other functionality to enhance the store (for example, with controls and resolvers).</p>\n\n<p>Also you can make use the <a href=\"https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/data\" rel=\"noreferrer\">core stores</a> and their selectors and actions inside your component's <code>withSelect</code> and <code>withDispatch</code>.</p>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/324979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/138112/"
] | I've registered a sidebar component in the block editor. I'd like to access the `state` of the component (`MyPlugin`) from outside of that component, in some arbitrary JavaScript in the same file. Is it possible to access the state via e.g. the `wp` object?
Or, is it possible, and would it be better to do this using `props`?
```
class MyPlugin extends Component {
constructor() {
super( ...arguments );
// initial state
this.state = {
key: 'my_key',
value: ''
}
}
render() {
return el(
PluginPostStatusInfo,
{
className: 'my-panel-class'
},
el(
TextControl,
{
name: 'my_text_control_name',
label: __( 'My label', 'my-text-domain' ),
value: this.state.value,
onChange: ( value ) => {
this.setState( {
value
})
}
}
)
);
}
}
registerPlugin( 'my-plugin', {
render: MyPlugin
} );
const myFunction = () => {
// this function is hooked into an action elsewhere,
// and needs to access the state of MyPlugin
}
```
What I'd ultimately like to do is access the textbox's value from a separate function. I don't mind how this is achieved, e.g. with `state` or `props` or some other means. I guess another approach would be to have the component write its value into a global variable when it changes, but that seems a bit clunky. | To do so you need to use a redux store. To register your own you can follow the steps in the [documentation](https://github.com/WordPress/gutenberg/tree/master/packages/data). Here is the minimum that should achieve what you are looking for.
First, lets give the "shape" of the store in the initial state object:
```
const initial_state = {
my_control: {
value: ""
},
};
```
Lets create a reducer that manipulates the state:
```
const reducer = (state = initial_state, action) => {
switch (action.type) {
case "UPDATE_MY_CONTROL_VALUE": {
return {
...state,
my_control: {
...state.my_control,
value: action.value
}
};
}
}
return state;
};
```
As you can see, we set the `initial_state` object we just created as the default value of the state.
Now lets add an action which updates the store, sending data to the reducer:
```
const actions = {
updateMyControlValue(value) {
return {
type: "UPDATE_MY_CONTROL_VALUE",
value
};
},
}
```
Lets add a selector that gets the data from the store:
```
const selectors = {
getMyControlValue(state) {
return state.my_control.value;
},
};
```
And now we will register the store with the previous constants:
```
const { registerStore } = wp.data;
registerStore("my_plugin/my_store", {
reducer,
actions,
selectors
});
```
Now the store is registered. We will connect the component to the store to get the latest value of my\_control and to update it:
```
const { Component } = wp.element;
const { TextControl } = wp.components;
const { compose } = wp.compose;
const { withDispatch, withSelect } = wp.data;
class Text extends Component {
render() {
const { value, updateMyControlValue } = this.props;
return (
<TextControl
value={value}
onChange={updateMyControlValue}
/>
);
}
}
export default compose([
withDispatch((dispatch, props) => {
// This function here is the action we created before.
const { updateMyControlValue } = dispatch("my_plugin/my_store");
return {
updateMyControlValue
};
}),
withSelect((select, props) => {
// This function here is the selector we created before.
const { getMyControlValue } = select("my_plugin/my_store");
return {
value: getMyControlValue()
};
}),
])(Text);
```
---
This is a simple example, but you can take a look at the link on the documentation to see how you can use other functionality to enhance the store (for example, with controls and resolvers).
Also you can make use the [core stores](https://github.com/WordPress/gutenberg/tree/master/docs/designers-developers/developers/data) and their selectors and actions inside your component's `withSelect` and `withDispatch`. |
325,001 | <p>I would really like to keep my template files as clean as possible, without including too much argument data. Is it possible with the following example...</p>
<pre><code> $args = array(
'theme_location' => 'main-menu',
'menu_class' => 'list-inline',
'add_li_class' => 'list-inline-item'
);
wp_nav_menu($args);
</code></pre>
<p>...that I can store my array of arguments in a function within my functions.php file, and then simply call the argument data onto my header.php where my wp_nav_menu() lives? Please feel free to correct me if I am wrong, but is this a good time for me to use a add_action/do_action for this specific case?</p>
<p>I want to use my functions.php file as a one-stop-shop to (i.e. register the nav, add basic or advanced argument data to the same nav, etc..). </p>
<p>This is the first time I'm thinking about this, so I'm all for any best practices.</p>
<p>Many thanks!</p>
| [
{
"answer_id": 325020,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": true,
"text": "<p>a function like this:</p>\n\n<pre><code>function get_nav_args($overrides = array()) {\n $defaults = array(\n 'theme_location' => 'main-menu',\n 'menu_class' => 'list-inline',\n 'add_li_class' => 'list-inline-item',\n );\n return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) );\n}\n</code></pre>\n\n<p>would be callable like <code>wp_nav_menu(get_nav_args())</code></p>\n\n<p>using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use <code>include</code> or <code>require</code> to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road.</p>\n"
},
{
"answer_id": 325033,
"author": "EGWorldNP",
"author_id": 138428,
"author_profile": "https://wordpress.stackexchange.com/users/138428",
"pm_score": 0,
"selected": false,
"text": "<p><strong>For 1st phase answer :</strong>\n<br>This function will also works :</p>\n\n<pre><code>if( !function_exists( 'menu_args' ) ) {\n\n function menu_args() {\n $args = array(\n 'theme_location' => 'main-menu',\n 'menu_class' => 'list-inline',\n 'add_li_class' => 'list-inline-item',\n );\n return $args;\n } }\n</code></pre>\n\n<p>After defining the function, you can call it by :</p>\n\n<pre><code>wp_nav_menu( menu_args() );\n</code></pre>\n\n<p><strong>For 2nd phase answer :</strong>\n<br>Functions.php is the essential file for wordpress that does not mean to have all the theme functions, tags/meta tags functions or custom meta, registering and defining own functions, etc on same file. <br><br>\nFor beginner phase, its good to go with only functions.php but if you want to code at professional level, you must know how to organize the files. You can use <code>include</code> or <code>require</code> on the basis of requirements to include the different files.<br><br>\nWhat i recommend is, to make different files for different kinds of functions like you can make theme-functions.php that is related to theme, template-functions.php for template one and so on. You can include it to a folder or different one as per your requirements and convenient.<br><br>\nYou have to maintain the hierarchy of files and folders so that you will not get confused of finding the codes even after gap of time. </p>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/325001",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98671/"
] | I would really like to keep my template files as clean as possible, without including too much argument data. Is it possible with the following example...
```
$args = array(
'theme_location' => 'main-menu',
'menu_class' => 'list-inline',
'add_li_class' => 'list-inline-item'
);
wp_nav_menu($args);
```
...that I can store my array of arguments in a function within my functions.php file, and then simply call the argument data onto my header.php where my wp\_nav\_menu() lives? Please feel free to correct me if I am wrong, but is this a good time for me to use a add\_action/do\_action for this specific case?
I want to use my functions.php file as a one-stop-shop to (i.e. register the nav, add basic or advanced argument data to the same nav, etc..).
This is the first time I'm thinking about this, so I'm all for any best practices.
Many thanks! | a function like this:
```
function get_nav_args($overrides = array()) {
$defaults = array(
'theme_location' => 'main-menu',
'menu_class' => 'list-inline',
'add_li_class' => 'list-inline-item',
);
return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) );
}
```
would be callable like `wp_nav_menu(get_nav_args())`
using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use `include` or `require` to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road. |
325,003 | <p>First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php <br/></p>
<p><strong>SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT</strong><br/></p>
<p><strong>This is my .js file that contains ajax</strong></p>
<pre><code> function kategori(kategori2){
//alert(kategori2);
jQuery.ajax({
url: MyAjax.ajax_url,
type: "POST",
data: { action: "berubah", kategori: "berita"},
success : function(data) {
}
});
}
</code></pre>
<p><strong>This is my function.php</strong> </p>
<pre><code><?php
// Support Featured Images
add_theme_support( 'post-thumbnails' );
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( 'add-order-front', get_template_directory_uri() . '/js/programku.js' );
wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'add-order-front' );
}
add_action( 'wp_ajax_berubah', 'berubah' );
add_action( 'wp_ajax_nopriv_berubah', 'berubah' );
function berubah()
{
$kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : '';
echo $kategori;
wp_die();
}
</code></pre>
<p><hr/><br/></p>
<p>I new to javascript too, I use Mozilla console and got this </p>
<blockquote>
<p>'ReferenceError: ajax_object is not defined'</p>
</blockquote>
<p><hr />
<br /></p>
<p><strong>EDIT #1 -</strong></p>
<p>i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress</p>
<p>now my problem is, <strong>function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code</strong></p>
<p><hr/>
<strong>in my theme i just have 5 files</strong> </p>
<ol>
<li>index.php</li>
<li>programku.js inside the js folder</li>
<li>header.php</li>
<li>footer.php</li>
<li>and last functions.php</li>
</ol>
<p><strong>Is there is a files that important in wordpress theme developing that i left?</strong><hr />
<br/><hr/></p>
<p><a href="https://i.stack.imgur.com/Gsy3g.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Gsy3g.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/SzG9t.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/SzG9t.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 325020,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": true,
"text": "<p>a function like this:</p>\n\n<pre><code>function get_nav_args($overrides = array()) {\n $defaults = array(\n 'theme_location' => 'main-menu',\n 'menu_class' => 'list-inline',\n 'add_li_class' => 'list-inline-item',\n );\n return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) );\n}\n</code></pre>\n\n<p>would be callable like <code>wp_nav_menu(get_nav_args())</code></p>\n\n<p>using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use <code>include</code> or <code>require</code> to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road.</p>\n"
},
{
"answer_id": 325033,
"author": "EGWorldNP",
"author_id": 138428,
"author_profile": "https://wordpress.stackexchange.com/users/138428",
"pm_score": 0,
"selected": false,
"text": "<p><strong>For 1st phase answer :</strong>\n<br>This function will also works :</p>\n\n<pre><code>if( !function_exists( 'menu_args' ) ) {\n\n function menu_args() {\n $args = array(\n 'theme_location' => 'main-menu',\n 'menu_class' => 'list-inline',\n 'add_li_class' => 'list-inline-item',\n );\n return $args;\n } }\n</code></pre>\n\n<p>After defining the function, you can call it by :</p>\n\n<pre><code>wp_nav_menu( menu_args() );\n</code></pre>\n\n<p><strong>For 2nd phase answer :</strong>\n<br>Functions.php is the essential file for wordpress that does not mean to have all the theme functions, tags/meta tags functions or custom meta, registering and defining own functions, etc on same file. <br><br>\nFor beginner phase, its good to go with only functions.php but if you want to code at professional level, you must know how to organize the files. You can use <code>include</code> or <code>require</code> on the basis of requirements to include the different files.<br><br>\nWhat i recommend is, to make different files for different kinds of functions like you can make theme-functions.php that is related to theme, template-functions.php for template one and so on. You can include it to a folder or different one as per your requirements and convenient.<br><br>\nYou have to maintain the hierarchy of files and folders so that you will not get confused of finding the codes even after gap of time. </p>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/325003",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158580/"
] | First please excuse my English. So I built my own WordPress theme and want to use ajax in it, I'm using ajax for change post category in my post loop inside functions.php, so when a person clicked the button in index.php ajax will send the data and functions.php will change the category, the problem is i can't reach admin-ajax.php
**SO IN HERE MY CODE IS JUST FOR TESTING IF THE AJAX WORK OR NOT, IT WONT ECHO THE POST THAT HAD BEEN SENT**
**This is my .js file that contains ajax**
```
function kategori(kategori2){
//alert(kategori2);
jQuery.ajax({
url: MyAjax.ajax_url,
type: "POST",
data: { action: "berubah", kategori: "berita"},
success : function(data) {
}
});
}
```
**This is my function.php**
```
<?php
// Support Featured Images
add_theme_support( 'post-thumbnails' );
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
function my_script_enqueuer() {
wp_register_script( 'add-order-front', get_template_directory_uri() . '/js/programku.js' );
wp_localize_script( 'add-order-front', 'MyAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) );
wp_enqueue_script( 'add-order-front' );
}
add_action( 'wp_ajax_berubah', 'berubah' );
add_action( 'wp_ajax_nopriv_berubah', 'berubah' );
function berubah()
{
$kategori = isset( $_POST['kategori'] ) ? $_POST['kategori'] : '';
echo $kategori;
wp_die();
}
```
---
I new to javascript too, I use Mozilla console and got this
>
> 'ReferenceError: ajax\_object is not defined'
>
>
>
---
**EDIT #1 -**
i can reach admin-ajax.php now, my fault was i didn't have header.php on my theme, sorry i new in wordpress
now my problem is, **function.php can't get the data sent by AJAX from programku.js and response in console is an HTML code**
---
**in my theme i just have 5 files**
1. index.php
2. programku.js inside the js folder
3. header.php
4. footer.php
5. and last functions.php
**Is there is a files that important in wordpress theme developing that i left?**
---
---
[](https://i.stack.imgur.com/Gsy3g.png)
[](https://i.stack.imgur.com/SzG9t.png) | a function like this:
```
function get_nav_args($overrides = array()) {
$defaults = array(
'theme_location' => 'main-menu',
'menu_class' => 'list-inline',
'add_li_class' => 'list-inline-item',
);
return shortcode_atts($defaults, apply_filters('some_custom_identifier_nav_menu_args', $overrides, $defaults) );
}
```
would be callable like `wp_nav_menu(get_nav_args())`
using shortcode atts and allowing an overrides array to be passed in would allow you to change the values if necessary without duplicating the whole thing. As for your put everything in functions.php I would avoid that if possible. Use `include` or `require` to include files that contain your functions. this way you can sort them out by type, use, location, or whatever else you'd like and won't end up digging through a single massive file looking for something down the road. |
325,013 | <p>I am trying to query a custom taxonomy terms in a way that keeps the hierarchical structure. </p>
<p>Here is the code that I am using.. </p>
<pre><code>function ev_test_data() {
$title = 'Mens Levi\'s Jeans';
$titles = str_replace( array("'", '"', '-', '\\' ), '', explode( ' ', trim($title)) );
$cats = array();
foreach ( $titles as $kw ) {
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'orderby' => 'parent', // I guess this is where I am lost.
'hide_empty' => false,
'name__like' => $kw,
) );
foreach ( $terms as $term ) {
$cats[] = $term->term_id;
}
}
$finals = array();
foreach ( $cats as $cat ) {
$catobj = get_term_by( 'id', $cat, 'product_cat' );
$tree = '';
$ancentors = array_reverse(get_ancestors( $cat, 'product_cat', 'taxonomy' ), true);
$i=1;
foreach ( $ancentors as $ancentor ) {
$sterm = get_term_by( 'id', $ancentor, 'product_cat' );
$tree .= $i == 1 ? '<b>' . $sterm->name . '</b>' : ' > ' . $sterm->name;
$i++;
}
$tree .= ' > ' . $catobj->name;
$finals[$cat] = $tree;
}
echo '<pre>' . print_r( $finals, true ) . '</pre>';
}
</code></pre>
<p>This produces this list.</p>
<pre><code>Array
(
[4638] => Fashion > Womens Clothing
[4699] => Fashion > Womens Handbags & Bags
[4709] => Fashion > Womens Shoes
[4461] => Fashion > Mens Accessories
[4493] => Fashion > Mens Clothing
[4512] => Fashion > Mens Shoes
[4603] => Fashion > Womens Accessories
[4779] => Fashion > Vintage > Mens Vintage Clothing
[4821] => Fashion > Vintage > Womens Vintage Clothing
[4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans
[4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans
[4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans
[4500] => Fashion > Mens Clothing > Jeans
[4660] => Fashion > Womens Clothing > Jeans
[4666] => Fashion > Womens Clothing > Maternity > Jeans
)
</code></pre>
<p>However, this list is not ordered as I want. I need it to be ordered by the hierarchical order. Something like this.</p>
<pre><code>Array
(
[4493] => Fashion > Mens Clothing
[4500] => Fashion > Mens Clothing > Jeans
[4638] => Fashion > Womens Clothing
[4660] => Fashion > Womens Clothing > Jeans
[4666] => Fashion > Womens Clothing > Maternity > Jeans
[4699] => Fashion > Womens Handbags & Bags
[4709] => Fashion > Womens Shoes
[4603] => Fashion > Womens Accessories
[4512] => Fashion > Mens Shoes
[4461] => Fashion > Mens Accessories
[4779] => Fashion > Vintage > Mens Vintage Clothing
[4821] => Fashion > Vintage > Womens Vintage Clothing
[4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans
[4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans
[4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans
)
</code></pre>
<p>Can this be done using WordPress built in functions? If not, what would be the logic for the custom query? I am not asking to do it for me, but any help or guide or headstart would be great. </p>
<p>Thanks</p>
| [
{
"answer_id": 325016,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 0,
"selected": false,
"text": "<p>You can use <a href=\"https://developer.wordpress.org/reference/functions/wp_list_categories/#Display_Terms_in_a_custom_taxonomy\" rel=\"nofollow noreferrer\">wp_list_categories</a> taxonomy argument which has built in support for hierarchal lists.</p>\n"
},
{
"answer_id": 329448,
"author": "WizontheWeb",
"author_id": 161735,
"author_profile": "https://wordpress.stackexchange.com/users/161735",
"pm_score": 2,
"selected": false,
"text": "<p>I was looking for the same thing and think this should work for you : <a href=\"https://wordpress.stackexchange.com/questions/37285/custom-taxonomy-get-the-terms-listing-in-order-of-parent-child\">Custom taxonomy, get_the_terms, listing in order of parent > child</a></p>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/325013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26991/"
] | I am trying to query a custom taxonomy terms in a way that keeps the hierarchical structure.
Here is the code that I am using..
```
function ev_test_data() {
$title = 'Mens Levi\'s Jeans';
$titles = str_replace( array("'", '"', '-', '\\' ), '', explode( ' ', trim($title)) );
$cats = array();
foreach ( $titles as $kw ) {
$terms = get_terms( array(
'taxonomy' => 'product_cat',
'orderby' => 'parent', // I guess this is where I am lost.
'hide_empty' => false,
'name__like' => $kw,
) );
foreach ( $terms as $term ) {
$cats[] = $term->term_id;
}
}
$finals = array();
foreach ( $cats as $cat ) {
$catobj = get_term_by( 'id', $cat, 'product_cat' );
$tree = '';
$ancentors = array_reverse(get_ancestors( $cat, 'product_cat', 'taxonomy' ), true);
$i=1;
foreach ( $ancentors as $ancentor ) {
$sterm = get_term_by( 'id', $ancentor, 'product_cat' );
$tree .= $i == 1 ? '<b>' . $sterm->name . '</b>' : ' > ' . $sterm->name;
$i++;
}
$tree .= ' > ' . $catobj->name;
$finals[$cat] = $tree;
}
echo '<pre>' . print_r( $finals, true ) . '</pre>';
}
```
This produces this list.
```
Array
(
[4638] => Fashion > Womens Clothing
[4699] => Fashion > Womens Handbags & Bags
[4709] => Fashion > Womens Shoes
[4461] => Fashion > Mens Accessories
[4493] => Fashion > Mens Clothing
[4512] => Fashion > Mens Shoes
[4603] => Fashion > Womens Accessories
[4779] => Fashion > Vintage > Mens Vintage Clothing
[4821] => Fashion > Vintage > Womens Vintage Clothing
[4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans
[4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans
[4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans
[4500] => Fashion > Mens Clothing > Jeans
[4660] => Fashion > Womens Clothing > Jeans
[4666] => Fashion > Womens Clothing > Maternity > Jeans
)
```
However, this list is not ordered as I want. I need it to be ordered by the hierarchical order. Something like this.
```
Array
(
[4493] => Fashion > Mens Clothing
[4500] => Fashion > Mens Clothing > Jeans
[4638] => Fashion > Womens Clothing
[4660] => Fashion > Womens Clothing > Jeans
[4666] => Fashion > Womens Clothing > Maternity > Jeans
[4699] => Fashion > Womens Handbags & Bags
[4709] => Fashion > Womens Shoes
[4603] => Fashion > Womens Accessories
[4512] => Fashion > Mens Shoes
[4461] => Fashion > Mens Accessories
[4779] => Fashion > Vintage > Mens Vintage Clothing
[4821] => Fashion > Vintage > Womens Vintage Clothing
[4290] => Fashion > Kids Clothing, Shoes & Accs > Boys Clothing (Sizes 4 & Up) > Jeans
[4319] => Fashion > Kids Clothing, Shoes & Accs > Girls Clothing (Sizes 4 & Up) > Jeans
[4354] => Fashion > Kids Clothing, Shoes & Accs > Unisex Clothing > Jeans
)
```
Can this be done using WordPress built in functions? If not, what would be the logic for the custom query? I am not asking to do it for me, but any help or guide or headstart would be great.
Thanks | I was looking for the same thing and think this should work for you : [Custom taxonomy, get\_the\_terms, listing in order of parent > child](https://wordpress.stackexchange.com/questions/37285/custom-taxonomy-get-the-terms-listing-in-order-of-parent-child) |
325,015 | <p>It works in the category.php loop</p>
<pre><code><article>
<p>post-<?php echo $wp_query->current_post +1; ?></p>
</article>
<article>
<p>post-<?php echo $wp_query->current_post +1; ?></p>
</article>
</code></pre>
<p>Result. Shows number 1, 2, 3 ...</p>
<pre><code><article>
<p>post-1</p>
</article>
<article>
<p>post-2</p>
</article>
</code></pre>
<p>Where to add this to widget recent posts?</p>
<p>If you add to the file /wp-includes/widgets/class-wp-widget-recent-posts.php</p>
<p>Result. Shows only number 1.</p>
<pre><code><ul>
<li>post-1</li>
</ul>
<ul>
<li>post-1</li>
</ul>
</code></pre>
<p>This is not a loop? How does this work in a widget?</p>
<blockquote>
<p>$wp_query->current_post +1</p>
<p>class-wp-widget-recent-posts.php or functions.php?</p>
</blockquote>
<p>Thanks.</p>
| [
{
"answer_id": 325040,
"author": "EGWorldNP",
"author_id": 138428,
"author_profile": "https://wordpress.stackexchange.com/users/138428",
"pm_score": -1,
"selected": false,
"text": "<p>I didn't get what actually you are asking for ? Post count or Post ID <br><br>\nAs i understand, i assume you want to show number of post list on widget named called recent posts. <br>\nBefore i say something, going to default setting and checking is not good. Everything you can do that from your theme directory and also you should have information related to widgets api. For reference: <br>\n<a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Widgets_API</a>\n<br>From it, you can create your own widget like for recent posts and add number count to each post as you asked for. <br>\nfor counting, you can use for loop. </p>\n\n<pre><code>if ( have_posts() ) :\n $count = 1;\n /* Start the Loop */\n while ( have_posts() ) :\n the_post();\n ?>\n <ul>\n <li>post-<?php echo $count; ?></li>\n </ul>\n <?php\n $count++; \n endwhile;\nendif;\n</code></pre>\n"
},
{
"answer_id": 325426,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It's not clearly stated in your question, but I guess, you added exactly this code to the widget file:</p>\n\n<pre><code><?php echo $wp_query->current_post +1; ?>\n</code></pre>\n\n<p>Am I right?</p>\n\n<p>If so, then it couldn't work, because this code takes the counter from global <code>$wp_query</code> object, but... This widget doesn't use global <code>$wp_query</code> and uses custom <code>WP_Query</code> instance. You can see it clearly here: <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70</a>. </p>\n\n<p>And even worse (in this case), because this widget doesn't use <code>the_post</code> method and standard way of looping through posts, but native PHP <code>foreach</code> loop (<a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94</a>), to be more efficient. But this also means that this loop doesn't change the counter value...</p>\n\n<p>But... There is one more, major, but. </p>\n\n<p>You should never ever modify core WP files. If you do this, you won't be able to update your WP or you will loose these modifications. You can easily cause any plugin or theme to work incorrectly.</p>\n\n<h2>So...? Is that it? It can't be done?</h2>\n\n<p>Well, it can. If all you want to do is to add numbers in the <code>li</code> element, you can do it with CSS.</p>\n\n<p>One way would be to change the <code>list-style-type</code> to <code>decimal</code> for list in that widget:</p>\n\n<pre><code>.widget_recent_entries ul {list-style-type: decimal;}\n</code></pre>\n\n<p>Another way is to use <code>:before</code> pseudo-class with counter:</p>\n\n<pre><code>.widget_recent_entries ul {\n counter-reset: my-recent-posts-widget-counter;\n}\n.widget_recent_entries ul li {\n counter-increment: my-recent-posts-widget-counter;\n}\n.widget_recent_entries ul li {\n content: counter(my-recent-posts-widget-counter);\n}\n</code></pre>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/325015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | It works in the category.php loop
```
<article>
<p>post-<?php echo $wp_query->current_post +1; ?></p>
</article>
<article>
<p>post-<?php echo $wp_query->current_post +1; ?></p>
</article>
```
Result. Shows number 1, 2, 3 ...
```
<article>
<p>post-1</p>
</article>
<article>
<p>post-2</p>
</article>
```
Where to add this to widget recent posts?
If you add to the file /wp-includes/widgets/class-wp-widget-recent-posts.php
Result. Shows only number 1.
```
<ul>
<li>post-1</li>
</ul>
<ul>
<li>post-1</li>
</ul>
```
This is not a loop? How does this work in a widget?
>
> $wp\_query->current\_post +1
>
>
> class-wp-widget-recent-posts.php or functions.php?
>
>
>
Thanks. | It's not clearly stated in your question, but I guess, you added exactly this code to the widget file:
```
<?php echo $wp_query->current_post +1; ?>
```
Am I right?
If so, then it couldn't work, because this code takes the counter from global `$wp_query` object, but... This widget doesn't use global `$wp_query` and uses custom `WP_Query` instance. You can see it clearly here: <https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70>.
And even worse (in this case), because this widget doesn't use `the_post` method and standard way of looping through posts, but native PHP `foreach` loop (<https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94>), to be more efficient. But this also means that this loop doesn't change the counter value...
But... There is one more, major, but.
You should never ever modify core WP files. If you do this, you won't be able to update your WP or you will loose these modifications. You can easily cause any plugin or theme to work incorrectly.
So...? Is that it? It can't be done?
------------------------------------
Well, it can. If all you want to do is to add numbers in the `li` element, you can do it with CSS.
One way would be to change the `list-style-type` to `decimal` for list in that widget:
```
.widget_recent_entries ul {list-style-type: decimal;}
```
Another way is to use `:before` pseudo-class with counter:
```
.widget_recent_entries ul {
counter-reset: my-recent-posts-widget-counter;
}
.widget_recent_entries ul li {
counter-increment: my-recent-posts-widget-counter;
}
.widget_recent_entries ul li {
content: counter(my-recent-posts-widget-counter);
}
``` |
325,022 | <p>I want to have what would appear if I chose
"homepage display to: Your latest posts"
but on a page of my choosing and Not as the front page of my site. </p>
| [
{
"answer_id": 325040,
"author": "EGWorldNP",
"author_id": 138428,
"author_profile": "https://wordpress.stackexchange.com/users/138428",
"pm_score": -1,
"selected": false,
"text": "<p>I didn't get what actually you are asking for ? Post count or Post ID <br><br>\nAs i understand, i assume you want to show number of post list on widget named called recent posts. <br>\nBefore i say something, going to default setting and checking is not good. Everything you can do that from your theme directory and also you should have information related to widgets api. For reference: <br>\n<a href=\"https://codex.wordpress.org/Widgets_API\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Widgets_API</a>\n<br>From it, you can create your own widget like for recent posts and add number count to each post as you asked for. <br>\nfor counting, you can use for loop. </p>\n\n<pre><code>if ( have_posts() ) :\n $count = 1;\n /* Start the Loop */\n while ( have_posts() ) :\n the_post();\n ?>\n <ul>\n <li>post-<?php echo $count; ?></li>\n </ul>\n <?php\n $count++; \n endwhile;\nendif;\n</code></pre>\n"
},
{
"answer_id": 325426,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>It's not clearly stated in your question, but I guess, you added exactly this code to the widget file:</p>\n\n<pre><code><?php echo $wp_query->current_post +1; ?>\n</code></pre>\n\n<p>Am I right?</p>\n\n<p>If so, then it couldn't work, because this code takes the counter from global <code>$wp_query</code> object, but... This widget doesn't use global <code>$wp_query</code> and uses custom <code>WP_Query</code> instance. You can see it clearly here: <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70</a>. </p>\n\n<p>And even worse (in this case), because this widget doesn't use <code>the_post</code> method and standard way of looping through posts, but native PHP <code>foreach</code> loop (<a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94\" rel=\"nofollow noreferrer\">https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94</a>), to be more efficient. But this also means that this loop doesn't change the counter value...</p>\n\n<p>But... There is one more, major, but. </p>\n\n<p>You should never ever modify core WP files. If you do this, you won't be able to update your WP or you will loose these modifications. You can easily cause any plugin or theme to work incorrectly.</p>\n\n<h2>So...? Is that it? It can't be done?</h2>\n\n<p>Well, it can. If all you want to do is to add numbers in the <code>li</code> element, you can do it with CSS.</p>\n\n<p>One way would be to change the <code>list-style-type</code> to <code>decimal</code> for list in that widget:</p>\n\n<pre><code>.widget_recent_entries ul {list-style-type: decimal;}\n</code></pre>\n\n<p>Another way is to use <code>:before</code> pseudo-class with counter:</p>\n\n<pre><code>.widget_recent_entries ul {\n counter-reset: my-recent-posts-widget-counter;\n}\n.widget_recent_entries ul li {\n counter-increment: my-recent-posts-widget-counter;\n}\n.widget_recent_entries ul li {\n content: counter(my-recent-posts-widget-counter);\n}\n</code></pre>\n"
}
] | 2019/01/08 | [
"https://wordpress.stackexchange.com/questions/325022",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158618/"
] | I want to have what would appear if I chose
"homepage display to: Your latest posts"
but on a page of my choosing and Not as the front page of my site. | It's not clearly stated in your question, but I guess, you added exactly this code to the widget file:
```
<?php echo $wp_query->current_post +1; ?>
```
Am I right?
If so, then it couldn't work, because this code takes the counter from global `$wp_query` object, but... This widget doesn't use global `$wp_query` and uses custom `WP_Query` instance. You can see it clearly here: <https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L70>.
And even worse (in this case), because this widget doesn't use `the_post` method and standard way of looping through posts, but native PHP `foreach` loop (<https://github.com/WordPress/WordPress/blob/master/wp-includes/widgets/class-wp-widget-recent-posts.php#L94>), to be more efficient. But this also means that this loop doesn't change the counter value...
But... There is one more, major, but.
You should never ever modify core WP files. If you do this, you won't be able to update your WP or you will loose these modifications. You can easily cause any plugin or theme to work incorrectly.
So...? Is that it? It can't be done?
------------------------------------
Well, it can. If all you want to do is to add numbers in the `li` element, you can do it with CSS.
One way would be to change the `list-style-type` to `decimal` for list in that widget:
```
.widget_recent_entries ul {list-style-type: decimal;}
```
Another way is to use `:before` pseudo-class with counter:
```
.widget_recent_entries ul {
counter-reset: my-recent-posts-widget-counter;
}
.widget_recent_entries ul li {
counter-increment: my-recent-posts-widget-counter;
}
.widget_recent_entries ul li {
content: counter(my-recent-posts-widget-counter);
}
``` |
325,113 | <p>when I tried to edit a post of a custom post type, I experienced this error.</p>
<p><a href="https://i.stack.imgur.com/mWpXa.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mWpXa.jpg" alt="enter image description here"></a></p>
<p>When I press "Copy Error" I am getting this:</p>
<pre class="lang-php prettyprint-override"><code>TypeError: Cannot read property 'prefix' of null
at https://example.com/wp-includes/js/dist/edit-post.min.js?ver=3.1.6:12:56693
at ph (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:97:88)
at eg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:125:307)
at fg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:126:168)
at wc (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:138:237)
at fa (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:137:115)
at gg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:135:196)
at Ca (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:133:365)
at Object.enqueueSetState (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:191:324)
at r.q.setState (https://example.com/wp-includes/js/dist/vendor/react.min.js?ver=16.6.3:20:304)
</code></pre>
| [
{
"answer_id": 325114,
"author": "marvinpoo",
"author_id": 94786,
"author_profile": "https://wordpress.stackexchange.com/users/94786",
"pm_score": 2,
"selected": true,
"text": "<p>So,\nI was researching this topic a bit deeper. All answers found on this SE suggested disabling Gutenberg with a plugin. This couldn't be a valid \"fix\" in my oppinion.</p>\n\n<p>After researching and browsing through the git issues of <code>WordPress/gutenberg</code> I've found a pretty easy solution for this problem.</p>\n\n<p>The user <code>joshuafredrickson</code> on the git suggested changing the args of the custom post type array from <code>'public' => false,</code> to <strong>true</strong>.</p>\n\n<p>I have checked that fix on multiple of my clients projects and it has worked every single time.</p>\n\n<p><strong>Credits:</strong> </p>\n\n<ul>\n<li><a href=\"https://github.com/WordPress/gutenberg/issues/12482#issuecomment-445022253\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/12482#issuecomment-445022253</a></li>\n</ul>\n"
},
{
"answer_id": 401772,
"author": "Michael",
"author_id": 42925,
"author_profile": "https://wordpress.stackexchange.com/users/42925",
"pm_score": 0,
"selected": false,
"text": "<p>Now in 2022, this was solved by changing <code>'show_in_rest' => true</code> to <code>'show_in_rest' => false</code>. My <code>public</code> option was already set to true. I thought I needed <code>show_in_rest</code> to be set to true for some reason, but turning it off doesn't seem to be affecting my site at all. We'll see...</p>\n"
}
] | 2019/01/09 | [
"https://wordpress.stackexchange.com/questions/325113",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94786/"
] | when I tried to edit a post of a custom post type, I experienced this error.
[](https://i.stack.imgur.com/mWpXa.jpg)
When I press "Copy Error" I am getting this:
```php
TypeError: Cannot read property 'prefix' of null
at https://example.com/wp-includes/js/dist/edit-post.min.js?ver=3.1.6:12:56693
at ph (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:97:88)
at eg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:125:307)
at fg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:126:168)
at wc (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:138:237)
at fa (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:137:115)
at gg (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:135:196)
at Ca (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:133:365)
at Object.enqueueSetState (https://example.com/wp-includes/js/dist/vendor/react-dom.min.js?ver=16.6.3:191:324)
at r.q.setState (https://example.com/wp-includes/js/dist/vendor/react.min.js?ver=16.6.3:20:304)
``` | So,
I was researching this topic a bit deeper. All answers found on this SE suggested disabling Gutenberg with a plugin. This couldn't be a valid "fix" in my oppinion.
After researching and browsing through the git issues of `WordPress/gutenberg` I've found a pretty easy solution for this problem.
The user `joshuafredrickson` on the git suggested changing the args of the custom post type array from `'public' => false,` to **true**.
I have checked that fix on multiple of my clients projects and it has worked every single time.
**Credits:**
* <https://github.com/WordPress/gutenberg/issues/12482#issuecomment-445022253> |
325,127 | <p>I recently switched to ssl in order to provide a better and more secure website experience for my users.</p>
<p>I nearly solved all of my mixed content issues, but the mixed content warnings of the Wordpress plugin kk star ratings are still unsolved.</p>
<p>When I open a blog post, I always get the following notifications:</p>
<p><strong>The following content is displayed in an insecure manner.</strong></p>
<p>/wp-content/plugins/kk-star-ratings/yellow.png.</p>
<p>/wp-content/plugins/kk-star-ratings/gray.png.</p>
<p>I've already looked into the plugin folder, but I don't have any php knowledge to fix it.</p>
<p>Could these lines be responsible for the mixed content warning?</p>
<pre><code>echo $star_gray ? '.kk-star-ratings .kksr-star.gray { background-image: url('.$star_gray.'); }' : '';
echo $star_yellow ? '.kk-star-ratings .kksr-star.yellow { background-image: url('.$star_yellow.'); }' : '';
echo $star_orange ? '.kk-star-ratings .kksr-star.orange { background-image: url('.$star_orange.'); }' : '';
</code></pre>
<p>I would be grateful if someone could help me to load these files via ssl.</p>
| [
{
"answer_id": 325226,
"author": "Arvind Singh",
"author_id": 113501,
"author_profile": "https://wordpress.stackexchange.com/users/113501",
"pm_score": 0,
"selected": false,
"text": "<p>Can try replacing all URL from database to https, you can use the plugin \"Search and replace\" or if you have phpMyAdmin access you can use this script </p>\n\n<pre><code>UPDATE wp_posts SET guid = replace(guid, 'http://www.yoursite.com','https://www.yoursite.com');\n\nUPDATE wp_posts SET post_content = replace(post_content, 'http://www.yoursite.com', 'https://www.yoursite.com');\n\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'http://www.yoursite.com','https://www.yoursite.com');\n</code></pre>\n\n<p>Redirect HTTP to HTTPS Using .htaccess file. You this code to force a redirect to https URL. </p>\n\n<pre><code>RewriteEngineOn\nRewriteCond%{HTTPS}off\nRewriteRule ^(.*)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]\n</code></pre>\n"
},
{
"answer_id": 325377,
"author": "Niklas",
"author_id": 158448,
"author_profile": "https://wordpress.stackexchange.com/users/158448",
"pm_score": 3,
"selected": true,
"text": "<p>I solved it myself. You have to remove the stars in settings / stars. Afterwards the tool recognizes ssl and will load it from a secure version of the website.</p>\n"
},
{
"answer_id": 338544,
"author": "CMS Tutorials",
"author_id": 168599,
"author_profile": "https://wordpress.stackexchange.com/users/168599",
"pm_score": -1,
"selected": false,
"text": "<p>You can easy do this from your kk star rating dashboard. Just follow this link: <a href=\"https://ask.wpcrons.com/how-can-i-fix-the-mixed-content-problems-of-the-kk-star-ratings-plugin/\" rel=\"nofollow noreferrer\">https://ask.wpcrons.com/how-can-i-fix-the-mixed-content-problems-of-the-kk-star-ratings-plugin/</a></p>\n"
}
] | 2019/01/09 | [
"https://wordpress.stackexchange.com/questions/325127",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158448/"
] | I recently switched to ssl in order to provide a better and more secure website experience for my users.
I nearly solved all of my mixed content issues, but the mixed content warnings of the Wordpress plugin kk star ratings are still unsolved.
When I open a blog post, I always get the following notifications:
**The following content is displayed in an insecure manner.**
/wp-content/plugins/kk-star-ratings/yellow.png.
/wp-content/plugins/kk-star-ratings/gray.png.
I've already looked into the plugin folder, but I don't have any php knowledge to fix it.
Could these lines be responsible for the mixed content warning?
```
echo $star_gray ? '.kk-star-ratings .kksr-star.gray { background-image: url('.$star_gray.'); }' : '';
echo $star_yellow ? '.kk-star-ratings .kksr-star.yellow { background-image: url('.$star_yellow.'); }' : '';
echo $star_orange ? '.kk-star-ratings .kksr-star.orange { background-image: url('.$star_orange.'); }' : '';
```
I would be grateful if someone could help me to load these files via ssl. | I solved it myself. You have to remove the stars in settings / stars. Afterwards the tool recognizes ssl and will load it from a secure version of the website. |
325,136 | <p>I have this custom query:</p>
<pre><code>if (isset($_COOKIE['myCookie']) && $_COOKIE['myCookie'] == $f_r) {
$args = array(
'posts_per_page' => 4,
'nopaging' => false,
'order' => 'ASC',
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'Count',
'field' => 'slug',
'terms' => $f_r,
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
<a href="<?php the_field('the_link'); ?> ">
<img src="<?php echo the_field('the_img'); ?>" />
</a>
} else {
echo 'Oops! Something went wrong!';
}
wp_reset_postdata();
</code></pre>
<p>The query works, but it does not reset the data. Every time a visitor lands on the page where the query runs, it shows the exact same 4 posts as it always does. </p>
<p>This code run just fine in my local environment (fetching different posts each time it runs), but on the live server it seems to be "fixed" to 4 specific posts. </p>
<p>I don't understand why this is happening, so I could really use some advice here. Thanks!</p>
<p>Ps. It's not the plugins or theme, because it works fine in a local environment.</p>
| [
{
"answer_id": 325145,
"author": "ClodClod91",
"author_id": 110442,
"author_profile": "https://wordpress.stackexchange.com/users/110442",
"pm_score": 0,
"selected": false,
"text": "<p>try to use</p>\n\n<p><code>wp_reset_query();\n wp_reset_postdata();</code></p>\n\n<p>As you can see here: <a href=\"https://codex.wordpress.org/it:Riferimento_classi/WP_Query\" rel=\"nofollow noreferrer\">documentation</a>\nwith wp_reset_query and wp_reset_postdata reset Query and Original Post Data</p>\n"
},
{
"answer_id": 325146,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 1,
"selected": false,
"text": "<p>If order by RAND is disabled at server level, you can try doing the rand by hand by running the query and get the ids first, then running a new query from the result including x random post ids:</p>\n\n<pre><code>$get_all_args = array(\n 'fields' => 'ids',\n 'posts_per_page' => 99,\n 'order' => 'DESC',\n 'orderby' => 'modified',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'Count',\n 'field' => 'slug',\n 'terms' => $f_r,\n )\n ) \n);\n\n\n$query_all = new WP_Query( $get_all_args );\n\n// additional code and checks\n// ...\n// ...\n\nwp_reset_postdata();\n\n$args = array(\n 'post__in ' => array_rand(array_flip( $query_all ), 4)\n);\n$query = new WP_Query( $get_all_args );\n\n// additional code and checks\n// ...\n// ...\n\nwp_reset_postdata();\n</code></pre>\n\n<p>You will get 4 random posts from the latest modified posts, notice I'm not using <code>'posts_per_page'=> -1</code> since this is not a good practice and can harm your site speed</p>\n"
},
{
"answer_id": 325162,
"author": "Arturo Gallegos",
"author_id": 130585,
"author_profile": "https://wordpress.stackexchange.com/users/130585",
"pm_score": 0,
"selected": false,
"text": "<p>you have missing a } after while, if you check </p>\n\n<pre><code>while ( $query->have_posts() ) {\n\n} else {\n</code></pre>\n\n<p>Please try with </p>\n\n<pre><code>if ( $query->have_posts() ) {\n\nwhile ( $query->have_posts() ) {\n\n$query->the_post();\n\n <a href=\"<?php the_field('the_link'); ?> \">\n <img src=\"<?php echo the_field('the_img'); ?>\" />\n </a> \n\n}\n} else {\n\n echo 'Oops! Something went wrong!';\n\n}\n\nwp_reset_postdata();\nwp_reset_query();\n</code></pre>\n"
}
] | 2019/01/09 | [
"https://wordpress.stackexchange.com/questions/325136",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/157978/"
] | I have this custom query:
```
if (isset($_COOKIE['myCookie']) && $_COOKIE['myCookie'] == $f_r) {
$args = array(
'posts_per_page' => 4,
'nopaging' => false,
'order' => 'ASC',
'orderby' => 'rand',
'tax_query' => array(
array(
'taxonomy' => 'Count',
'field' => 'slug',
'terms' => $f_r,
)
)
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) {
while ( $query->have_posts() ) {
$query->the_post();
<a href="<?php the_field('the_link'); ?> ">
<img src="<?php echo the_field('the_img'); ?>" />
</a>
} else {
echo 'Oops! Something went wrong!';
}
wp_reset_postdata();
```
The query works, but it does not reset the data. Every time a visitor lands on the page where the query runs, it shows the exact same 4 posts as it always does.
This code run just fine in my local environment (fetching different posts each time it runs), but on the live server it seems to be "fixed" to 4 specific posts.
I don't understand why this is happening, so I could really use some advice here. Thanks!
Ps. It's not the plugins or theme, because it works fine in a local environment. | If order by RAND is disabled at server level, you can try doing the rand by hand by running the query and get the ids first, then running a new query from the result including x random post ids:
```
$get_all_args = array(
'fields' => 'ids',
'posts_per_page' => 99,
'order' => 'DESC',
'orderby' => 'modified',
'tax_query' => array(
array(
'taxonomy' => 'Count',
'field' => 'slug',
'terms' => $f_r,
)
)
);
$query_all = new WP_Query( $get_all_args );
// additional code and checks
// ...
// ...
wp_reset_postdata();
$args = array(
'post__in ' => array_rand(array_flip( $query_all ), 4)
);
$query = new WP_Query( $get_all_args );
// additional code and checks
// ...
// ...
wp_reset_postdata();
```
You will get 4 random posts from the latest modified posts, notice I'm not using `'posts_per_page'=> -1` since this is not a good practice and can harm your site speed |
325,151 | <p>From my research there are only two questions I've found around this topic on this site:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/questions/206907/how-to-change-in-customizer-the-site-identity-tab-required-capabilities">How to change in customizer the “site identity” tab required capabilities</a></li>
<li><a href="https://wordpress.stackexchange.com/questions/84200/how-to-change-default-icon-of-custom-plugin">how to change default icon of custom plugin?</a></li>
</ul>
<p>outside of the site I did find:</p>
<ul>
<li><a href="https://premium.wpmudev.org/forums/topic/how-to-add-a-default-site-icon-in-themes-customizer" rel="nofollow noreferrer">How to Add a Default Site Icon in Theme's Customizer</a></li>
</ul>
<p>but when I try:</p>
<pre><code>function default_icon() {
global $wp_customize;
$wp_customize->get_setting('site_icon',array (
'default' => home_url() . 'img/test.png'
));
}
add_action('customize_register','default_icon');
</code></pre>
<p>I've also tried <code>add_setting</code> with:</p>
<pre><code>function default_icon() {
global $wp_customize;
$wp_customize->add_setting('site_icon', array(
'default' => home_url() . 'img/test.png'
));
}
add_action('customize_register','default_icon');
</code></pre>
<p>but that doesn't work either. It will not show the default icon in the drag and drop area and renders "No Image selected":</p>
<p><a href="https://i.stack.imgur.com/JOyBz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/JOyBz.png" alt="enter image description here"></a></p>
<p>In my functions.php how can I code my theme to render the default icon presently being used in the drag and drop area?</p>
<p>After further testing I can set the <code>default when I code</code>:</p>
<pre><code>add_action('customize_register','default_icon',10,2);
</code></pre>
<p>and I can see it in a dump of <code>$wp_customize</code> but as far as rendering it will not.</p>
| [
{
"answer_id": 325145,
"author": "ClodClod91",
"author_id": 110442,
"author_profile": "https://wordpress.stackexchange.com/users/110442",
"pm_score": 0,
"selected": false,
"text": "<p>try to use</p>\n\n<p><code>wp_reset_query();\n wp_reset_postdata();</code></p>\n\n<p>As you can see here: <a href=\"https://codex.wordpress.org/it:Riferimento_classi/WP_Query\" rel=\"nofollow noreferrer\">documentation</a>\nwith wp_reset_query and wp_reset_postdata reset Query and Original Post Data</p>\n"
},
{
"answer_id": 325146,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 1,
"selected": false,
"text": "<p>If order by RAND is disabled at server level, you can try doing the rand by hand by running the query and get the ids first, then running a new query from the result including x random post ids:</p>\n\n<pre><code>$get_all_args = array(\n 'fields' => 'ids',\n 'posts_per_page' => 99,\n 'order' => 'DESC',\n 'orderby' => 'modified',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'Count',\n 'field' => 'slug',\n 'terms' => $f_r,\n )\n ) \n);\n\n\n$query_all = new WP_Query( $get_all_args );\n\n// additional code and checks\n// ...\n// ...\n\nwp_reset_postdata();\n\n$args = array(\n 'post__in ' => array_rand(array_flip( $query_all ), 4)\n);\n$query = new WP_Query( $get_all_args );\n\n// additional code and checks\n// ...\n// ...\n\nwp_reset_postdata();\n</code></pre>\n\n<p>You will get 4 random posts from the latest modified posts, notice I'm not using <code>'posts_per_page'=> -1</code> since this is not a good practice and can harm your site speed</p>\n"
},
{
"answer_id": 325162,
"author": "Arturo Gallegos",
"author_id": 130585,
"author_profile": "https://wordpress.stackexchange.com/users/130585",
"pm_score": 0,
"selected": false,
"text": "<p>you have missing a } after while, if you check </p>\n\n<pre><code>while ( $query->have_posts() ) {\n\n} else {\n</code></pre>\n\n<p>Please try with </p>\n\n<pre><code>if ( $query->have_posts() ) {\n\nwhile ( $query->have_posts() ) {\n\n$query->the_post();\n\n <a href=\"<?php the_field('the_link'); ?> \">\n <img src=\"<?php echo the_field('the_img'); ?>\" />\n </a> \n\n}\n} else {\n\n echo 'Oops! Something went wrong!';\n\n}\n\nwp_reset_postdata();\nwp_reset_query();\n</code></pre>\n"
}
] | 2019/01/09 | [
"https://wordpress.stackexchange.com/questions/325151",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] | From my research there are only two questions I've found around this topic on this site:
* [How to change in customizer the “site identity” tab required capabilities](https://wordpress.stackexchange.com/questions/206907/how-to-change-in-customizer-the-site-identity-tab-required-capabilities)
* [how to change default icon of custom plugin?](https://wordpress.stackexchange.com/questions/84200/how-to-change-default-icon-of-custom-plugin)
outside of the site I did find:
* [How to Add a Default Site Icon in Theme's Customizer](https://premium.wpmudev.org/forums/topic/how-to-add-a-default-site-icon-in-themes-customizer)
but when I try:
```
function default_icon() {
global $wp_customize;
$wp_customize->get_setting('site_icon',array (
'default' => home_url() . 'img/test.png'
));
}
add_action('customize_register','default_icon');
```
I've also tried `add_setting` with:
```
function default_icon() {
global $wp_customize;
$wp_customize->add_setting('site_icon', array(
'default' => home_url() . 'img/test.png'
));
}
add_action('customize_register','default_icon');
```
but that doesn't work either. It will not show the default icon in the drag and drop area and renders "No Image selected":
[](https://i.stack.imgur.com/JOyBz.png)
In my functions.php how can I code my theme to render the default icon presently being used in the drag and drop area?
After further testing I can set the `default when I code`:
```
add_action('customize_register','default_icon',10,2);
```
and I can see it in a dump of `$wp_customize` but as far as rendering it will not. | If order by RAND is disabled at server level, you can try doing the rand by hand by running the query and get the ids first, then running a new query from the result including x random post ids:
```
$get_all_args = array(
'fields' => 'ids',
'posts_per_page' => 99,
'order' => 'DESC',
'orderby' => 'modified',
'tax_query' => array(
array(
'taxonomy' => 'Count',
'field' => 'slug',
'terms' => $f_r,
)
)
);
$query_all = new WP_Query( $get_all_args );
// additional code and checks
// ...
// ...
wp_reset_postdata();
$args = array(
'post__in ' => array_rand(array_flip( $query_all ), 4)
);
$query = new WP_Query( $get_all_args );
// additional code and checks
// ...
// ...
wp_reset_postdata();
```
You will get 4 random posts from the latest modified posts, notice I'm not using `'posts_per_page'=> -1` since this is not a good practice and can harm your site speed |
325,160 | <p>I have the Twenty Seventeen theme and I would like to turn off generate SVG (social icons menu) in DOM.</p>
<p><a href="https://i.imgur.com/HZCqOgV.png" rel="nofollow noreferrer">https://i.imgur.com/HZCqOgV.png</a></p>
<p>How can I turn off it? I do not use the social icons, but it is g</p>
<p>In function.php my parent theme i see it:</p>
<pre><code>require get_parent_theme_file_path( '/inc/icon-functions.php' );
</code></pre>
<p>How can I override it in my child-theme to avoid generate it?</p>
<p>Thank you in advance.</p>
| [
{
"answer_id": 325163,
"author": "mahdi azarm",
"author_id": 94280,
"author_profile": "https://wordpress.stackexchange.com/users/94280",
"pm_score": 1,
"selected": false,
"text": "<p>Create <code>/inc/icon-functions.php</code> file in your child-theme and modify it as you want!</p>\n\n<p>EDIT</p>\n\n<p>You must hook to the <code>parent_theme_file_path</code> to tell wordpress load file from child theme, so use the following code:</p>\n\n<pre><code>function override_parent_theme_file($path,$file) {\n if ($file == '/inc/icon-functions.php')\n return get_stylesheet_directory() . '/' . $file;\n}\nadd_filter('parent_theme_file_path','override_parent_theme_file',10,2);\n</code></pre>\n\n<p>Also you can remove the if statement if you want override to other files included this way.</p>\n"
},
{
"answer_id": 325164,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 3,
"selected": true,
"text": "<p>If you look at <code>get_parent_theme_file_path()</code> it returns <code>apply_filters( 'parent_theme_file_path', $path, $file );</code>\nYou need to add a filter here to override the location to something in your child theme, like so.</p>\n\n<pre><code>add_filter('parent_theme_file_path', function($path, $file) {\n if ($file !== '/inc/icon-functions.php') {\n return $path;\n }\n\n $path = get_stylesheet_directory() . '/' . $file;\n\n return $path;\n}, 10, 2);\n</code></pre>\n\n<p>You will still need to have a file for it to find at that location in your child theme, but you can put whatever you want in there.</p>\n"
}
] | 2019/01/09 | [
"https://wordpress.stackexchange.com/questions/325160",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/140882/"
] | I have the Twenty Seventeen theme and I would like to turn off generate SVG (social icons menu) in DOM.
<https://i.imgur.com/HZCqOgV.png>
How can I turn off it? I do not use the social icons, but it is g
In function.php my parent theme i see it:
```
require get_parent_theme_file_path( '/inc/icon-functions.php' );
```
How can I override it in my child-theme to avoid generate it?
Thank you in advance. | If you look at `get_parent_theme_file_path()` it returns `apply_filters( 'parent_theme_file_path', $path, $file );`
You need to add a filter here to override the location to something in your child theme, like so.
```
add_filter('parent_theme_file_path', function($path, $file) {
if ($file !== '/inc/icon-functions.php') {
return $path;
}
$path = get_stylesheet_directory() . '/' . $file;
return $path;
}, 10, 2);
```
You will still need to have a file for it to find at that location in your child theme, but you can put whatever you want in there. |
325,183 | <p>Having the exact same problem as <a href="https://wordpress.stackexchange.com/questions/248057/oembed-fails-half-of-the-times-could-i-reload-the-request-on-fail">@Hjalmar</a> on Advanced Custom Fields, but still no fix. Only the URL text displays.</p>
<p><a href="https://i.stack.imgur.com/wzWos.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/wzWos.png" alt="Front End oembed output"></a></p>
<p>Tried the original ACF oembed option:</p>
<pre><code><div class="embed-container">
<?php echo get_field('video_embedd'); ?>
</div>
</code></pre>
<p>No luck.</p>
<p>Placed the YouTube embed URL in the ACF text field and outputting it into an HTML iframe:</p>
<pre><code><?php
$videoEmbeddPlease = get_field('video_embedd');
if (!empty($videoEmbeddPlease)): ?>
<iframe width="560" height="315" src="<?php echo $videoEmbeddPlease?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<?php endif ?>
</code></pre>
<p>No luck.</p>
<p>Even tried the Advanced ACF example:</p>
<pre><code><?php
// get iframe HTML
$iframe = get_field('video_embedd');
// use preg_match to find iframe src
preg_match('/src="(.+?)"/', $iframe, $matches);
$src = $matches[1];
// add extra params to iframe src
$params = array(
'controls' => 0,
'hd' => 1,
'autohide' => 1
);
$new_src = add_query_arg($params, $src);
$iframe = str_replace($src, $new_src, $iframe);
// add extra attributes to iframe html
$attributes = 'frameborder="0"';
$iframe = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $iframe);
// echo $iframe
echo $iframe;
?>
</code></pre>
<p>Even tried the WYSIWYG option. </p>
<pre><code><?php the_field('video_embedd'); ?>
</code></pre>
<p>Still! No embedded video display, just the YouTube URL text on the screen.</p>
<p>Any help would be incredible.</p>
<p>Thank you!</p>
| [
{
"answer_id": 329708,
"author": "Roman Nazarkin",
"author_id": 92253,
"author_profile": "https://wordpress.stackexchange.com/users/92253",
"pm_score": 1,
"selected": false,
"text": "<p>Such happens when video is <strong>not publicly accessible</strong>. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video.</p>\n"
},
{
"answer_id": 365969,
"author": "nigelheap",
"author_id": 54810,
"author_profile": "https://wordpress.stackexchange.com/users/54810",
"pm_score": 0,
"selected": false,
"text": "<p>It's also possible that google is blocking the api request to fetch the embed data.</p>\n\n<p>ACF uses the <code>wp_oembed_get</code> function which goes off and grabs metadata from Youtube before displaying the iframe.</p>\n\n<p>Sometimes google may block your server or network if it thinks you have been making too many requests. Google will return the confirm you're not a robot page with the message </p>\n\n<p>\"Our systems have detected unusual traffic from your computer network\"</p>\n"
}
] | 2019/01/10 | [
"https://wordpress.stackexchange.com/questions/325183",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/150803/"
] | Having the exact same problem as [@Hjalmar](https://wordpress.stackexchange.com/questions/248057/oembed-fails-half-of-the-times-could-i-reload-the-request-on-fail) on Advanced Custom Fields, but still no fix. Only the URL text displays.
[](https://i.stack.imgur.com/wzWos.png)
Tried the original ACF oembed option:
```
<div class="embed-container">
<?php echo get_field('video_embedd'); ?>
</div>
```
No luck.
Placed the YouTube embed URL in the ACF text field and outputting it into an HTML iframe:
```
<?php
$videoEmbeddPlease = get_field('video_embedd');
if (!empty($videoEmbeddPlease)): ?>
<iframe width="560" height="315" src="<?php echo $videoEmbeddPlease?>" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
<?php endif ?>
```
No luck.
Even tried the Advanced ACF example:
```
<?php
// get iframe HTML
$iframe = get_field('video_embedd');
// use preg_match to find iframe src
preg_match('/src="(.+?)"/', $iframe, $matches);
$src = $matches[1];
// add extra params to iframe src
$params = array(
'controls' => 0,
'hd' => 1,
'autohide' => 1
);
$new_src = add_query_arg($params, $src);
$iframe = str_replace($src, $new_src, $iframe);
// add extra attributes to iframe html
$attributes = 'frameborder="0"';
$iframe = str_replace('></iframe>', ' ' . $attributes . '></iframe>', $iframe);
// echo $iframe
echo $iframe;
?>
```
Even tried the WYSIWYG option.
```
<?php the_field('video_embedd'); ?>
```
Still! No embedded video display, just the YouTube URL text on the screen.
Any help would be incredible.
Thank you! | Such happens when video is **not publicly accessible**. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video. |
325,252 | <p><strong>Code</strong></p>
<p>Currently, I'm working project to automatically generate all my theme customizer options with simple array.</p>
<pre><code>'nav_font_style' => array(
'default_options' => array(
1 => 'default',),
'css' => " nav#for-mobile h1 { font-family: $",
'stylesheet_handle' => 'semperfi-navigation',
'label' => __('Font', 'semper-fi-lite'),
'description' => array(
1 => '', ),
'panel_title' => __('Navigation', 'semper-fi-lite'),
'panel_priority' => 1,
'priority' => 10,
'section_title' => __('Menu Title', 'semper-fi-lite'),
'section_priority' => 10,
'selector' => 'nav#for-mobile h1',
'type' => 'font'),
</code></pre>
<p>This array has everything needed to generate a theme option. Bellow is the loop that it will run through.</p>
<pre><code> // Add a font selector to Customizer
if ($values['type'] == 'font') {
$wp_customize->add_setting( $option . '_' . $i, array(
'default' => 'Default',
'sanitize_callback' => 'semperfi_sanitize_css', ) );
$wp_customize->add_control( $option . '_' . $i . '_control', array(
'section' => str_replace( "~", $semperfi_customizer_multi_dimensional_array[$i], $section_title_transformed ),
'label' => $values['label'],
'description' => $values['description'][$i],
'priority' => $values['priority'],
'type' => 'select',
'settings' => $option . '_' . $i,
'stylesheet_handle' => $values['stylesheet_handle'],
'choices' => $finalized_google_font_array));
}
</code></pre>
<p>When I go the sanitize_callback I'm having issues using this to access all the choices like it's explained on <a href="https://wordpress.stackexchange.com/questions/308248/how-to-get-input-attrs-in-the-sanitize-function">How to get input_attrs in the sanitize function?</a> </p>
<pre><code>function semperfi_sanitize_css( $input , $setting ) {
set_theme_mod( 'semperfi_testing' , $setting->manager->get_control( 'nav_font_style_1' )->input_attrs );
return $input;
</code></pre>
<p>}</p>
<p>The above sanitize function is just for testing but I really need to access the handle so that I can apply CSS to the correct sheet style.</p>
<p>Thanks for your help!</p>
| [
{
"answer_id": 329708,
"author": "Roman Nazarkin",
"author_id": 92253,
"author_profile": "https://wordpress.stackexchange.com/users/92253",
"pm_score": 1,
"selected": false,
"text": "<p>Such happens when video is <strong>not publicly accessible</strong>. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video.</p>\n"
},
{
"answer_id": 365969,
"author": "nigelheap",
"author_id": 54810,
"author_profile": "https://wordpress.stackexchange.com/users/54810",
"pm_score": 0,
"selected": false,
"text": "<p>It's also possible that google is blocking the api request to fetch the embed data.</p>\n\n<p>ACF uses the <code>wp_oembed_get</code> function which goes off and grabs metadata from Youtube before displaying the iframe.</p>\n\n<p>Sometimes google may block your server or network if it thinks you have been making too many requests. Google will return the confirm you're not a robot page with the message </p>\n\n<p>\"Our systems have detected unusual traffic from your computer network\"</p>\n"
}
] | 2019/01/10 | [
"https://wordpress.stackexchange.com/questions/325252",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76309/"
] | **Code**
Currently, I'm working project to automatically generate all my theme customizer options with simple array.
```
'nav_font_style' => array(
'default_options' => array(
1 => 'default',),
'css' => " nav#for-mobile h1 { font-family: $",
'stylesheet_handle' => 'semperfi-navigation',
'label' => __('Font', 'semper-fi-lite'),
'description' => array(
1 => '', ),
'panel_title' => __('Navigation', 'semper-fi-lite'),
'panel_priority' => 1,
'priority' => 10,
'section_title' => __('Menu Title', 'semper-fi-lite'),
'section_priority' => 10,
'selector' => 'nav#for-mobile h1',
'type' => 'font'),
```
This array has everything needed to generate a theme option. Bellow is the loop that it will run through.
```
// Add a font selector to Customizer
if ($values['type'] == 'font') {
$wp_customize->add_setting( $option . '_' . $i, array(
'default' => 'Default',
'sanitize_callback' => 'semperfi_sanitize_css', ) );
$wp_customize->add_control( $option . '_' . $i . '_control', array(
'section' => str_replace( "~", $semperfi_customizer_multi_dimensional_array[$i], $section_title_transformed ),
'label' => $values['label'],
'description' => $values['description'][$i],
'priority' => $values['priority'],
'type' => 'select',
'settings' => $option . '_' . $i,
'stylesheet_handle' => $values['stylesheet_handle'],
'choices' => $finalized_google_font_array));
}
```
When I go the sanitize\_callback I'm having issues using this to access all the choices like it's explained on [How to get input\_attrs in the sanitize function?](https://wordpress.stackexchange.com/questions/308248/how-to-get-input-attrs-in-the-sanitize-function)
```
function semperfi_sanitize_css( $input , $setting ) {
set_theme_mod( 'semperfi_testing' , $setting->manager->get_control( 'nav_font_style_1' )->input_attrs );
return $input;
```
}
The above sanitize function is just for testing but I really need to access the handle so that I can apply CSS to the correct sheet style.
Thanks for your help! | Such happens when video is **not publicly accessible**. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video. |
325,260 | <p>I want to add an author image for each thumbnail-preview on my homepage.</p>
<p>I tried <code><?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?></code> but it gives me the same image in every thumbnail.</p>
<p>Here's the full code for the thumbnails:</p>
<pre><code> <?php
$recentp_args = array( 'numberposts' => '4' );
$recent_posts = wp_get_recent_posts($recentp_args);
foreach( $recent_posts as $recent ){ ?>
<article>
<a href="<?php echo get_permalink($recent["ID"]); ?>">
<?php
$thumb = get_the_post_thumbnail( $recent["ID"], 'featuredmedium', array( 'class' => 'lazyload' ) );
if ( !empty($thumb) ) { // check if the post has a Post Thumbnail assigned to it.
echo $thumb;
} else {
echo '<img src="'.get_bloginfo('template_url').'/images/photo_default.png" width="320" height="167" alt="" />';
}
?>
<h2 class="title"><?php echo $recent["post_title"]; ?></h2>
<?php echo apply_filters( 'the_content', limit_words(strip_tags($recent["post_content"]),38) ); ?>
<?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?>
</a>
</article>
<?php } ?>
</code></pre>
| [
{
"answer_id": 329708,
"author": "Roman Nazarkin",
"author_id": 92253,
"author_profile": "https://wordpress.stackexchange.com/users/92253",
"pm_score": 1,
"selected": false,
"text": "<p>Such happens when video is <strong>not publicly accessible</strong>. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video.</p>\n"
},
{
"answer_id": 365969,
"author": "nigelheap",
"author_id": 54810,
"author_profile": "https://wordpress.stackexchange.com/users/54810",
"pm_score": 0,
"selected": false,
"text": "<p>It's also possible that google is blocking the api request to fetch the embed data.</p>\n\n<p>ACF uses the <code>wp_oembed_get</code> function which goes off and grabs metadata from Youtube before displaying the iframe.</p>\n\n<p>Sometimes google may block your server or network if it thinks you have been making too many requests. Google will return the confirm you're not a robot page with the message </p>\n\n<p>\"Our systems have detected unusual traffic from your computer network\"</p>\n"
}
] | 2019/01/10 | [
"https://wordpress.stackexchange.com/questions/325260",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107225/"
] | I want to add an author image for each thumbnail-preview on my homepage.
I tried `<?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?>` but it gives me the same image in every thumbnail.
Here's the full code for the thumbnails:
```
<?php
$recentp_args = array( 'numberposts' => '4' );
$recent_posts = wp_get_recent_posts($recentp_args);
foreach( $recent_posts as $recent ){ ?>
<article>
<a href="<?php echo get_permalink($recent["ID"]); ?>">
<?php
$thumb = get_the_post_thumbnail( $recent["ID"], 'featuredmedium', array( 'class' => 'lazyload' ) );
if ( !empty($thumb) ) { // check if the post has a Post Thumbnail assigned to it.
echo $thumb;
} else {
echo '<img src="'.get_bloginfo('template_url').'/images/photo_default.png" width="320" height="167" alt="" />';
}
?>
<h2 class="title"><?php echo $recent["post_title"]; ?></h2>
<?php echo apply_filters( 'the_content', limit_words(strip_tags($recent["post_content"]),38) ); ?>
<?php echo get_avatar( get_the_author_meta( 'ID' ), 32 ); ?>
</a>
</article>
<?php } ?>
``` | Such happens when video is **not publicly accessible**. In my case the video was simply removed from YouTube by their author and ACF's oEmbed module was unable to get metadata to properly display video. |
325,269 | <p>I am working for a public service website and we really need a text-only version of the website, or a black and white version, for people with special needs.</p>
<p>Is there any plug-in or script that can do this?
Thank you so much!</p>
| [
{
"answer_id": 325270,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": false,
"text": "<p>Sounds like your actual goal is accessibility. You should check out <a href=\"https://www.w3.org/WAI/standards-guidelines/wcag/\" rel=\"nofollow noreferrer\">WCAG 2.0</a> standards to see what they recommend. But the short answer is no, there's not a good way to automagically make your site accessible. You could also use the <a href=\"https://wave.webaim.org/\" rel=\"nofollow noreferrer\">WAVE scanner</a> to find out what you need to fix on a specific page.</p>\n"
},
{
"answer_id": 325292,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": true,
"text": "<p>If you wanted to remove all colorful text from your site, you could use a global CSS rule, as in </p>\n\n<pre><code>* {color:black !important; background-color:white !important}\n</code></pre>\n\n<p>which should turn all text to black on white background. (The '*\" should apply to all CSS elements.) That wouldn't get rid of images or other things, so you might add this for images</p>\n\n<pre><code>img {display:none !important;}\n</code></pre>\n\n<p>And then add additional elements as needed. </p>\n\n<p>The problem with this is that it would affect the entire site, so you would need to have a way to change the theme on the fly just for the text-only users. That's not easy to do, I think.</p>\n\n<p>Maybe create another WP installation that uses the same database, but set up a theme for that new site that adds the above CSS and others as needed. The new site would be at <a href=\"https://www.example.com/textonly\" rel=\"nofollow noreferrer\">https://www.example.com/textonly</a> , for example. You'd also need to copy the plugins folder to the new site. </p>\n\n<p>Probably some additional tweaks needed, but that might get you started.</p>\n\n<p><strong>Added</strong></p>\n\n<p>As I think about the duplicate site/same database idea, with the duplicate site using a different theme, there might be an issue.</p>\n\n<p>The active theme is stored in wp-options table (I think), so a shared database couldn't have a different theme. </p>\n\n<p>So you would need to use a hook to change the theme name (and location) during the very first part of the page load process. You would still need a separate install with the shared database, but the hook would load a different theme.</p>\n\n<p>Perhaps function that uses a hook that would change the theme name (and location) is all that is needed. The hook would look at the page's query parameter (say <a href=\"https://www.example.com/some-page?theme=textonly\" rel=\"nofollow noreferrer\">https://www.example.com/some-page?theme=textonly</a> )and inspect the 'theme' query parameter to decide which theme to load.</p>\n\n<p>I don't think that a query parameter that specifies a theme name is available in WP core - although that would be a great idea; very useful for testing new themes on an active site, which some people would like to do.</p>\n\n<p>But perhaps my random thoughts might get you going into a direction that will meet your needs. I'd be interested in other thoughts about this.</p>\n\n<p><strong>Added More</strong></p>\n\n<p>So, digging around possible hooks, I came up with the '<code>setup_theme</code>' hook, in the wp-settings.php around line 407. A bit later in that file (around line 438) (line numbers are there from my copy/paste from the code):</p>\n\n<pre><code>// Load the functions for the active theme, for both parent and child theme if applicable.\n439 if ( ! wp_installing() || 'wp-activate.php' === $pagenow ) {\n440 if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) )\n441 include( STYLESHEETPATH . '/functions.php' );\n442 if ( file_exists( TEMPLATEPATH . '/functions.php' ) )\n443 include( TEMPLATEPATH . '/functions.php' );\n444 }\n</code></pre>\n\n<p>So, it would seem that by changing the <code>TEMPLATEPATH</code> and <code>STYLESHEETPATH</code> constants, we could change the theme being used. </p>\n\n<p>So, psuedocode:</p>\n\n<pre><code>add_action('setup_theme', 'my_use_different_theme');\nfunction my_use_different_theme() {\n TEMPLATEPATH = \"path/to/the/other/theme/templates';\n STYLESHEETPATH = \"path/to/the/other/theme/styles\";\nreturn;\n}\n</code></pre>\n\n<p>Might allow you to create a function that would add the action if the query parameter contained a value like '<code>theme=newtheme</code>', where '<code>newtheme</code>' is name of the theme you want to use. Psuedocode:</p>\n\n<pre><code>$themename = \"get/the/query/value\";\nif ($themename =='newtheme') {\n add_action('setup_theme', 'my_use_different_theme');\n}\n</code></pre>\n\n<p>which would call our '<code>my_use_different_theme</code>' function if the query parameter for the page was <code>theme=newtheme</code> .</p>\n"
},
{
"answer_id": 325310,
"author": "Stefano Tombolini",
"author_id": 96268,
"author_profile": "https://wordpress.stackexchange.com/users/96268",
"pm_score": 0,
"selected": false,
"text": "<p>I really like this plugin: <a href=\"https://it.wordpress.org/plugins/wp-accessibility-helper/\" rel=\"nofollow noreferrer\">https://it.wordpress.org/plugins/wp-accessibility-helper/</a></p>\n\n<p>It has many features, unload CSS included.</p>\n"
}
] | 2019/01/10 | [
"https://wordpress.stackexchange.com/questions/325269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/147952/"
] | I am working for a public service website and we really need a text-only version of the website, or a black and white version, for people with special needs.
Is there any plug-in or script that can do this?
Thank you so much! | If you wanted to remove all colorful text from your site, you could use a global CSS rule, as in
```
* {color:black !important; background-color:white !important}
```
which should turn all text to black on white background. (The '\*" should apply to all CSS elements.) That wouldn't get rid of images or other things, so you might add this for images
```
img {display:none !important;}
```
And then add additional elements as needed.
The problem with this is that it would affect the entire site, so you would need to have a way to change the theme on the fly just for the text-only users. That's not easy to do, I think.
Maybe create another WP installation that uses the same database, but set up a theme for that new site that adds the above CSS and others as needed. The new site would be at <https://www.example.com/textonly> , for example. You'd also need to copy the plugins folder to the new site.
Probably some additional tweaks needed, but that might get you started.
**Added**
As I think about the duplicate site/same database idea, with the duplicate site using a different theme, there might be an issue.
The active theme is stored in wp-options table (I think), so a shared database couldn't have a different theme.
So you would need to use a hook to change the theme name (and location) during the very first part of the page load process. You would still need a separate install with the shared database, but the hook would load a different theme.
Perhaps function that uses a hook that would change the theme name (and location) is all that is needed. The hook would look at the page's query parameter (say <https://www.example.com/some-page?theme=textonly> )and inspect the 'theme' query parameter to decide which theme to load.
I don't think that a query parameter that specifies a theme name is available in WP core - although that would be a great idea; very useful for testing new themes on an active site, which some people would like to do.
But perhaps my random thoughts might get you going into a direction that will meet your needs. I'd be interested in other thoughts about this.
**Added More**
So, digging around possible hooks, I came up with the '`setup_theme`' hook, in the wp-settings.php around line 407. A bit later in that file (around line 438) (line numbers are there from my copy/paste from the code):
```
// Load the functions for the active theme, for both parent and child theme if applicable.
439 if ( ! wp_installing() || 'wp-activate.php' === $pagenow ) {
440 if ( TEMPLATEPATH !== STYLESHEETPATH && file_exists( STYLESHEETPATH . '/functions.php' ) )
441 include( STYLESHEETPATH . '/functions.php' );
442 if ( file_exists( TEMPLATEPATH . '/functions.php' ) )
443 include( TEMPLATEPATH . '/functions.php' );
444 }
```
So, it would seem that by changing the `TEMPLATEPATH` and `STYLESHEETPATH` constants, we could change the theme being used.
So, psuedocode:
```
add_action('setup_theme', 'my_use_different_theme');
function my_use_different_theme() {
TEMPLATEPATH = "path/to/the/other/theme/templates';
STYLESHEETPATH = "path/to/the/other/theme/styles";
return;
}
```
Might allow you to create a function that would add the action if the query parameter contained a value like '`theme=newtheme`', where '`newtheme`' is name of the theme you want to use. Psuedocode:
```
$themename = "get/the/query/value";
if ($themename =='newtheme') {
add_action('setup_theme', 'my_use_different_theme');
}
```
which would call our '`my_use_different_theme`' function if the query parameter for the page was `theme=newtheme` . |
325,271 | <p>I have an ACF-field, that gives an output like this:</p>
<pre><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p><img class="alignnone size-large wp-image-48" src="http://example.org/wp-content/uploads/2019/01/foo-bar.jpg" alt="" width="1024" height="640" /></p>
<p>Sed lacinia enim a <strong>est aliquet</strong>, et accumsan ex pellentesque. </p>
<p>Adipiscing elit, lorem ipsum dolor sit amet, consectetur.</p>
</code></pre>
<p>... Both images and text. </p>
<p>With <a href="https://codex.wordpress.org/Function_Reference/wp_html_excerpt" rel="nofollow noreferrer">wp_html_excerpt</a> I can remove all tags, so I get one long text-blurp. </p>
<p>But with WordPress' native excerpts, then it doesn't remove line-breaks or bold text, which I find nice. </p>
<p>How would I go about achieving, getting an excerpt like that, from my ACF-wysiwyg-field? </p>
<p>So ideally, I would call my function like this: <code>create_neat_excerpt( $html, 15 );</code> and get an output like this (from above-given input):</p>
<pre><code><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Sed lacinia enim a <strong>est aliquet</strong>, et accumsan...</p>
</code></pre>
<h2>Addition: My current attempt</h2>
<pre><code>$project_desc = get_field( 'project_description' );
if( !empty( $project_desc ) ):
$trimmed_text = wp_html_excerpt( $project_desc, 800 );
$last_space = strrpos( $trimmed_text, ' ' );
$modified_trimmed_text = substr( $trimmed_text, 0, $last_space );
echo $modified_trimmed_text . '...';
endif;
</code></pre>
| [
{
"answer_id": 325351,
"author": "Peter HvD",
"author_id": 134918,
"author_profile": "https://wordpress.stackexchange.com/users/134918",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>the_excerpt</code> filter (see <a href=\"https://developer.wordpress.org/reference/hooks/the_excerpt/\" rel=\"nofollow noreferrer\">Codex</a>)</p>\n\n<p><code>apply_filters( 'the_excerpt', get_field( 'my-wysiwyg-field' ) );</code></p>\n"
},
{
"answer_id": 325686,
"author": "mrben522",
"author_id": 84703,
"author_profile": "https://wordpress.stackexchange.com/users/84703",
"pm_score": 2,
"selected": false,
"text": "<p>using <code>apply_filters( 'the_excerpt', get_field( 'project_description' ) );</code> is close, but it's missing a vital step in getting you where you want. the core excerpt builder runs another filter before it hits <code>the_excerpt</code>. it's <code>get_the_excerpt</code> and on that filter is a call to <code>wp_trim_excerpt()</code> which runs <code>wp_trim_words()</code>. if you look at that function you will see it runs <code>wp_strip_all_tags()</code> before trimming content to 55 words. This is the part you are missing to get your content to look like a regular excerpt without any images. I haven't tested the below but it should work without too much modification needed.</p>\n\n<pre><code>$raw_content = get_field( 'project_description' );\n$trimmed_content = wp_trim_words($raw_content);\n$clean_excerpt = apply_filters('the_excerpt', $trimmed_content);\n\necho $clean_excerpt;\n</code></pre>\n\n<p>Clean that up however you like, I spread it all out for readability.</p>\n\n<p>EDIT: <code>wp_trim_excerpt()</code> only runs all the fun filters if it's pulling from post content. replaced with <code>wp_trim_words()</code></p>\n"
},
{
"answer_id": 325750,
"author": "Ibrahim Mohamed",
"author_id": 141791,
"author_profile": "https://wordpress.stackexchange.com/users/141791",
"pm_score": 4,
"selected": true,
"text": "<p>You can provide your own implementation of <code>wp_trim_excerpt</code> which is responsible for trimming and stripping HTML tags (it uses <code>wp_strip_all_tags</code>), </p>\n\n<p>By copying the function source code and applying the change that you want (which is keeping the <code><p></code> and <code><strong></code> tags (or any additional tags as you wish) and it will work nicely.</p>\n\n<p>I copied the function for you and applied the change of allowing <code><p></code> and <code><strong></code> to be on your final excerpt. <strong>(You should put this code in your <code>functions.php</code> file)</strong></p>\n\n<pre><code>function wp_trim_excerpt_modified($text, $content_length = 55, $remove_breaks = false) {\n if ( '' != $text ) {\n $text = strip_shortcodes( $text );\n $text = excerpt_remove_blocks( $text );\n $text = apply_filters( 'the_content', $text );\n $text = str_replace(']]>', ']]&gt;', $text);\n $num_words = $content_length;\n $more = $excerpt_more ? $excerpt_more : null;\n if ( null === $more ) {\n $more = __( '&hellip;' );\n }\n $original_text = $text;\n $text = preg_replace( '@<(script|style)[^>]*?>.*?</\\\\1>@si', '', $text );\n\n // Here is our modification\n // Allow <p> and <strong>\n $text = strip_tags($text, '<p>,<strong>');\n\n if ( $remove_breaks )\n $text = preg_replace('/[\\r\\n\\t ]+/', ' ', $text);\n $text = trim( $text );\n if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\\-?8$/i', get_option( 'blog_charset' ) ) ) {\n $text = trim( preg_replace( \"/[\\n\\r\\t ]+/\", ' ', $text ), ' ' );\n preg_match_all( '/./u', $text, $words_array );\n $words_array = array_slice( $words_array[0], 0, $num_words + 1 );\n $sep = '';\n } else {\n $words_array = preg_split( \"/[\\n\\r\\t ]+/\", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );\n $sep = ' ';\n }\n if ( count( $words_array ) > $num_words ) {\n array_pop( $words_array );\n $text = implode( $sep, $words_array );\n $text = $text . $more;\n } else {\n $text = implode( $sep, $words_array );\n }\n }\n return $text;\n}\n</code></pre>\n\n<p>Notice the line that is doing the stripping:</p>\n\n<p><strong>Line:22</strong> <code>$text = strip_tags($text, '<p>,<strong>');</code></p>\n\n<p>And your code should be like this:</p>\n\n<pre><code>$project_desc = get_field( 'project_description' );\nif( !empty( $project_desc ) ):\n $trimmed_text = wp_trim_excerpt_modified( $project_desc, 15 );\n $last_space = strrpos( $trimmed_text, ' ' );\n $modified_trimmed_text = substr( $trimmed_text, 0, $last_space );\n echo $modified_trimmed_text . '...';\nendif; \n</code></pre>\n\n<p>For more information, you can checkout <a href=\"https://stackoverflow.com/a/24160854/4365678\">this answer</a> on stackoverflow it is more detailed.</p>\n"
}
] | 2019/01/10 | [
"https://wordpress.stackexchange.com/questions/325271",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/128304/"
] | I have an ACF-field, that gives an output like this:
```
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p><img class="alignnone size-large wp-image-48" src="http://example.org/wp-content/uploads/2019/01/foo-bar.jpg" alt="" width="1024" height="640" /></p>
<p>Sed lacinia enim a <strong>est aliquet</strong>, et accumsan ex pellentesque. </p>
<p>Adipiscing elit, lorem ipsum dolor sit amet, consectetur.</p>
```
... Both images and text.
With [wp\_html\_excerpt](https://codex.wordpress.org/Function_Reference/wp_html_excerpt) I can remove all tags, so I get one long text-blurp.
But with WordPress' native excerpts, then it doesn't remove line-breaks or bold text, which I find nice.
How would I go about achieving, getting an excerpt like that, from my ACF-wysiwyg-field?
So ideally, I would call my function like this: `create_neat_excerpt( $html, 15 );` and get an output like this (from above-given input):
```
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
<p>Sed lacinia enim a <strong>est aliquet</strong>, et accumsan...</p>
```
Addition: My current attempt
----------------------------
```
$project_desc = get_field( 'project_description' );
if( !empty( $project_desc ) ):
$trimmed_text = wp_html_excerpt( $project_desc, 800 );
$last_space = strrpos( $trimmed_text, ' ' );
$modified_trimmed_text = substr( $trimmed_text, 0, $last_space );
echo $modified_trimmed_text . '...';
endif;
``` | You can provide your own implementation of `wp_trim_excerpt` which is responsible for trimming and stripping HTML tags (it uses `wp_strip_all_tags`),
By copying the function source code and applying the change that you want (which is keeping the `<p>` and `<strong>` tags (or any additional tags as you wish) and it will work nicely.
I copied the function for you and applied the change of allowing `<p>` and `<strong>` to be on your final excerpt. **(You should put this code in your `functions.php` file)**
```
function wp_trim_excerpt_modified($text, $content_length = 55, $remove_breaks = false) {
if ( '' != $text ) {
$text = strip_shortcodes( $text );
$text = excerpt_remove_blocks( $text );
$text = apply_filters( 'the_content', $text );
$text = str_replace(']]>', ']]>', $text);
$num_words = $content_length;
$more = $excerpt_more ? $excerpt_more : null;
if ( null === $more ) {
$more = __( '…' );
}
$original_text = $text;
$text = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $text );
// Here is our modification
// Allow <p> and <strong>
$text = strip_tags($text, '<p>,<strong>');
if ( $remove_breaks )
$text = preg_replace('/[\r\n\t ]+/', ' ', $text);
$text = trim( $text );
if ( strpos( _x( 'words', 'Word count type. Do not translate!' ), 'characters' ) === 0 && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) {
$text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' );
preg_match_all( '/./u', $text, $words_array );
$words_array = array_slice( $words_array[0], 0, $num_words + 1 );
$sep = '';
} else {
$words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY );
$sep = ' ';
}
if ( count( $words_array ) > $num_words ) {
array_pop( $words_array );
$text = implode( $sep, $words_array );
$text = $text . $more;
} else {
$text = implode( $sep, $words_array );
}
}
return $text;
}
```
Notice the line that is doing the stripping:
**Line:22** `$text = strip_tags($text, '<p>,<strong>');`
And your code should be like this:
```
$project_desc = get_field( 'project_description' );
if( !empty( $project_desc ) ):
$trimmed_text = wp_trim_excerpt_modified( $project_desc, 15 );
$last_space = strrpos( $trimmed_text, ' ' );
$modified_trimmed_text = substr( $trimmed_text, 0, $last_space );
echo $modified_trimmed_text . '...';
endif;
```
For more information, you can checkout [this answer](https://stackoverflow.com/a/24160854/4365678) on stackoverflow it is more detailed. |
325,303 | <p>My lost password option in the wp login page redirect to woocommerce lost password page.How to set it back to the standard wp lost password option.?I want it to redirect to "wp-login.php?action=lostpassword".
I am using,woocommerce,paid membership pro,buddypress plugins.
I found this <a href="https://wordpress.stackexchange.com/q/290858/158576">Lost password link is redirecting to /shop/my-account/lost-password/</a>, but I couldn't understand it.</p>
<p>Thanks.</p>
| [
{
"answer_id": 325304,
"author": "Pratik Patel",
"author_id": 143123,
"author_profile": "https://wordpress.stackexchange.com/users/143123",
"pm_score": 2,
"selected": true,
"text": "<p>Try to put below code into your theme <strong>functions.php</strong> file</p>\n\n<pre><code>remove_filter( 'lostpassword_url', 'wc_lostpassword_url', 10 );\n</code></pre>\n\n<p>OR</p>\n\n<pre><code>function reset_pass_url() {\n $siteURL = get_option('siteurl');\n return \"{$siteURL}/wp-login.php?action=lostpassword\";\n}\nadd_filter( 'lostpassword_url', 'reset_pass_url', 10, 2 );\n</code></pre>\n\n<p>Please let me know if any query.</p>\n\n<p>Hope it will help you.</p>\n"
},
{
"answer_id": 325306,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>You can remove the filter that WooCommerce uses to replace the lost password URL like so:</p>\n\n<pre><code>remove_filter( 'lostpassword_url', 'wc_lostpassword_url', 10 );\n</code></pre>\n"
},
{
"answer_id": 331694,
"author": "Dan Wich",
"author_id": 157603,
"author_profile": "https://wordpress.stackexchange.com/users/157603",
"pm_score": 2,
"selected": false,
"text": "<p>You can do this without code by going to the WooCommerce administration, Settings, Advanced, and removing the \"lost-password\" text from the Lost password field under Account Endpoints:\n<a href=\"https://i.stack.imgur.com/IWXwr.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/IWXwr.png\" alt=\"arrow pointing to lost password field\"></a></p>\n"
},
{
"answer_id": 395919,
"author": "Mr SKT",
"author_id": 210558,
"author_profile": "https://wordpress.stackexchange.com/users/210558",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this code:</p>\n<pre><code>function wdm_lostpassword_url() {\n return site_url( '/wp-login.php?action=lostpassword' );\n}\nadd_filter( 'lostpassword_url', 'wdm_lostpassword_url', 10, 0 );\n</code></pre>\n<p>Add it to to your current active theme's functions.php file</p>\n"
}
] | 2019/01/11 | [
"https://wordpress.stackexchange.com/questions/325303",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158576/"
] | My lost password option in the wp login page redirect to woocommerce lost password page.How to set it back to the standard wp lost password option.?I want it to redirect to "wp-login.php?action=lostpassword".
I am using,woocommerce,paid membership pro,buddypress plugins.
I found this [Lost password link is redirecting to /shop/my-account/lost-password/](https://wordpress.stackexchange.com/q/290858/158576), but I couldn't understand it.
Thanks. | Try to put below code into your theme **functions.php** file
```
remove_filter( 'lostpassword_url', 'wc_lostpassword_url', 10 );
```
OR
```
function reset_pass_url() {
$siteURL = get_option('siteurl');
return "{$siteURL}/wp-login.php?action=lostpassword";
}
add_filter( 'lostpassword_url', 'reset_pass_url', 10, 2 );
```
Please let me know if any query.
Hope it will help you. |
325,361 | <p>My old permalink structure is <code>/index.php/%year%/%monthnum%/%day%/%postname%/</code>.
For example:</p>
<p><code>https://example.com/index.php/2019/01/08/technological-innovation-for-agriculture-sector-in-india/</code></p>
<p>but I want to change to "Post name". For example:</p>
<pre><code>https://example.com/sample-post/
</code></pre>
<p>also, want to remove <code>index.php</code>.</p>
<p>When I change the permalink my old post or pages are not working </p>
| [
{
"answer_id": 325319,
"author": "Stefano Tombolini",
"author_id": 96268,
"author_profile": "https://wordpress.stackexchange.com/users/96268",
"pm_score": 0,
"selected": false,
"text": "<p>I suggest using BuddyPress user profiles feature, you don't need to enable all BuddyPress features.</p>\n\n<p>Gravity Forms can be used to create profile-like fields, but it is not really tied to real WordPress user profiles: <a href=\"https://www.gravityforms.com/creating-team-member-profiles/\" rel=\"nofollow noreferrer\">https://www.gravityforms.com/creating-team-member-profiles/</a></p>\n"
},
{
"answer_id": 407813,
"author": "Abdul Qadir",
"author_id": 223764,
"author_profile": "https://wordpress.stackexchange.com/users/223764",
"pm_score": -1,
"selected": false,
"text": "<p>Here are the following steps that can help you to achieve this.</p>\n<ul>\n<li><p>create child theme or plugin</p>\n</li>\n<li><p>Create template file for that custom page (<a href=\"https://developer.wordpress.org/themes/template-files-section/page-template-files/\" rel=\"nofollow noreferrer\">Reference</a>)</p>\n</li>\n<li><p>Check login user user by using <a href=\"https://developer.wordpress.org/reference/functions/wp_get_current_user/\" rel=\"nofollow noreferrer\">get_curent_user()</a></p>\n</li>\n</ul>\n<ul>\n<li>Now create form based on that information and update information based on that form</li>\n<li>Now last step create Wordpress page and select that template</li>\n</ul>\n<p>Congratulation now you can edit user information from front end.</p>\n"
}
] | 2019/01/11 | [
"https://wordpress.stackexchange.com/questions/325361",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/142924/"
] | My old permalink structure is `/index.php/%year%/%monthnum%/%day%/%postname%/`.
For example:
`https://example.com/index.php/2019/01/08/technological-innovation-for-agriculture-sector-in-india/`
but I want to change to "Post name". For example:
```
https://example.com/sample-post/
```
also, want to remove `index.php`.
When I change the permalink my old post or pages are not working | I suggest using BuddyPress user profiles feature, you don't need to enable all BuddyPress features.
Gravity Forms can be used to create profile-like fields, but it is not really tied to real WordPress user profiles: <https://www.gravityforms.com/creating-team-member-profiles/> |
325,391 | <p>I am creating a custom field <code>Tracking_ID</code> on Woocommerce, where the admin will enter the tracking ID as value.</p>
<p>How can i get the value of the created custom field and display it inside the <code>customer-completed-order.php</code> </p>
<p>Also (Optional) i want to show the tracking ID field in the user's <code>track-order</code> order page in his/her my-account.</p>
<p><strong>Woocommerce>order field:</strong></p>
<p><a href="https://i.stack.imgur.com/0Q78e.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/0Q78e.png" alt="enter image description here"></a></p>
<p><strong>oceanwp-child/woocommerce/emails/customer-completed-order.php</strong></p>
<pre><code><?php /* translators: %s: Customer first name */ ?>
<p><?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?></p>
<?php /* translators: %s: Site title */ ?>
<p><?php printf( esc_html__( 'Your %s order is completed. Your tracking number is: {$fld}', 'woocommerce' ), esc_html( wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ) ); ?></p>
</code></pre>
| [
{
"answer_id": 325437,
"author": "Melissa Freeman",
"author_id": 84867,
"author_profile": "https://wordpress.stackexchange.com/users/84867",
"pm_score": 1,
"selected": false,
"text": "<p>The syntax to get your custom field is:</p>\n\n<pre><code>get_post_meta($post_id, $key, $single);\n</code></pre>\n\n<p>In your context, you should try:</p>\n\n<pre><code>$tracking_id = get_post_meta($order->get_order_number(), 'Tracking_ID', true);\n</code></pre>\n\n<p>To show you in your example:</p>\n\n<pre><code><?php /* translators: %s: Site title */ \n$tracking_id = get_post_meta($order->get_order_number(), 'Tracking_ID', true); ?>\n<p><?php printf( esc_html__( 'Your %s order is completed. Your tracking number is: %s', 'woocommerce' ), esc_html( wp_specialchars_decode( get_option( 'blogname' ), esc_html($tracking_id) ) ) ); ?></p>\n</code></pre>\n"
},
{
"answer_id": 325455,
"author": "csandreas1",
"author_id": 87667,
"author_profile": "https://wordpress.stackexchange.com/users/87667",
"pm_score": 1,
"selected": true,
"text": "<p>Based on Melissa's answer, here is what i did and it worked for me.</p>\n\n<pre><code> <?php\n #Tracking ID\n\n $tracking_id = get_post_meta($order->get_order_number(), 'Tracking_ID', true);\n\n if( ! empty($tracking_id) )\n { ?>\n<p> <?php\nprintf( esc_html__( 'Your tracking number is: %s', 'woocommerce' ), esc_html($tracking_id) );?> \n</p> <?php \n }\n ?>\n</code></pre>\n"
}
] | 2019/01/12 | [
"https://wordpress.stackexchange.com/questions/325391",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87667/"
] | I am creating a custom field `Tracking_ID` on Woocommerce, where the admin will enter the tracking ID as value.
How can i get the value of the created custom field and display it inside the `customer-completed-order.php`
Also (Optional) i want to show the tracking ID field in the user's `track-order` order page in his/her my-account.
**Woocommerce>order field:**
[](https://i.stack.imgur.com/0Q78e.png)
**oceanwp-child/woocommerce/emails/customer-completed-order.php**
```
<?php /* translators: %s: Customer first name */ ?>
<p><?php printf( esc_html__( 'Hi %s,', 'woocommerce' ), esc_html( $order->get_billing_first_name() ) ); ?></p>
<?php /* translators: %s: Site title */ ?>
<p><?php printf( esc_html__( 'Your %s order is completed. Your tracking number is: {$fld}', 'woocommerce' ), esc_html( wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES ) ) ); ?></p>
``` | Based on Melissa's answer, here is what i did and it worked for me.
```
<?php
#Tracking ID
$tracking_id = get_post_meta($order->get_order_number(), 'Tracking_ID', true);
if( ! empty($tracking_id) )
{ ?>
<p> <?php
printf( esc_html__( 'Your tracking number is: %s', 'woocommerce' ), esc_html($tracking_id) );?>
</p> <?php
}
?>
``` |
325,428 | <p>I have a site where I created a page that takes the gallery images from a post and puts them into a slider. </p>
<p>I used the following code:</p>
<pre><code>// gets the gallery info
$gallery = get_post_gallery( $post->ID, false );
// makes an array of image ids
$ids = explode ( ",", $gallery['ids'] );
</code></pre>
<p>Then I inserted the images using wp_get_attachment_image(). </p>
<p>Unfortunately, with WP 5.0 and Gutenberg, get_post_gallery no longer works with newly added content. It seems that get_post_gallery used a shortcode that no longer works with Gutenberg. </p>
<p>I am still getting up to speed on Gutenberg and the block system. Until I understand that all better, I was wondering if anyone has any advice on how to get the image ids from a gallery in Gutenberg?</p>
| [
{
"answer_id": 325431,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>get_post_gallery()</code> is a wrapper for <code>get_post_galleries()</code> that has an open ticket \n<a href=\"https://core.trac.wordpress.org/ticket/43826\" rel=\"nofollow noreferrer\">#43826</a> for gallery blocks support. This is currently set to the 5.1 milestone, but it might change.</p>\n\n<p>You can even look at the proposed <a href=\"https://core.trac.wordpress.org/attachment/ticket/43826/43826.6.diff\" rel=\"nofollow noreferrer\">patches</a>, that uses e.g. <code>parse_blocks( $post->post_content )</code> and <code>has_block( 'gallery', $post->post_content )</code> , to get an idea what's needed to fully support this.</p>\n\n<p>In the meanwhile you could look into the <code>render_block</code> filter to modify the rendered output of gallery blocks to your needs. </p>\n\n<p>Here's an example that targets the <code>core/gallery</code> block and uses the block attribute containing the gallery image IDs:</p>\n\n<pre><code>/**\n * Modify the output of the rendered core/gallery block.\n */\nadd_filter( 'render_block', function( $block_content, $block ) {\n if ( 'core/gallery' !== $block['blockName'] || ! isset( $block['attrs']['ids'] ) ) {\n return $block_content;\n }\n $li = '';\n foreach( (array) $block['attrs']['ids'] as $id ) {\n $li .= sprintf( '<li>%s</li>', wp_get_attachment_image( $id, 'large' ) );\n }\n return sprintf( '<ul>%s</ul>', $li ); \n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 325708,
"author": "kosher",
"author_id": 120936,
"author_profile": "https://wordpress.stackexchange.com/users/120936",
"pm_score": 4,
"selected": true,
"text": "<p>Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. </p>\n\n<pre><code>// if there is a gallery block do this\nif (has_block('gallery', $post->post_content)) {\n $post_blocks = parse_blocks($post->post_content);\n $ids = $post_blocks[0][attrs][ids];\n} \n// if there is not a gallery block do this\nelse {\n // gets the gallery info\n $gallery = get_post_gallery( $post->ID, false );\n // makes an array of image ids\n $ids = explode ( \",\", $gallery['ids'] );\n}\n</code></pre>\n"
}
] | 2019/01/12 | [
"https://wordpress.stackexchange.com/questions/325428",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120936/"
] | I have a site where I created a page that takes the gallery images from a post and puts them into a slider.
I used the following code:
```
// gets the gallery info
$gallery = get_post_gallery( $post->ID, false );
// makes an array of image ids
$ids = explode ( ",", $gallery['ids'] );
```
Then I inserted the images using wp\_get\_attachment\_image().
Unfortunately, with WP 5.0 and Gutenberg, get\_post\_gallery no longer works with newly added content. It seems that get\_post\_gallery used a shortcode that no longer works with Gutenberg.
I am still getting up to speed on Gutenberg and the block system. Until I understand that all better, I was wondering if anyone has any advice on how to get the image ids from a gallery in Gutenberg? | Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0.
```
// if there is a gallery block do this
if (has_block('gallery', $post->post_content)) {
$post_blocks = parse_blocks($post->post_content);
$ids = $post_blocks[0][attrs][ids];
}
// if there is not a gallery block do this
else {
// gets the gallery info
$gallery = get_post_gallery( $post->ID, false );
// makes an array of image ids
$ids = explode ( ",", $gallery['ids'] );
}
``` |
325,429 | <p>I have a website running WP connected to a MySql db, where the latter uses PHP. I did not make the site and have only small experience with WP. This may be a simple question. The WP also uses Elementor. I interact with the db via phpMyAdmin.</p>
<p>I have this page = <a href="http://linket.info/signup/" rel="nofollow noreferrer">http://linket.info/signup/</a>
It accepts input data that does into the db.</p>
<p>See the labels ('First Name' etc). I can't seem to find them defined in WP. So they are in the db? I looked in the various db tables. But still can't seem to find these labels. Can you suggest what tables I might focus on?</p>
| [
{
"answer_id": 325431,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>get_post_gallery()</code> is a wrapper for <code>get_post_galleries()</code> that has an open ticket \n<a href=\"https://core.trac.wordpress.org/ticket/43826\" rel=\"nofollow noreferrer\">#43826</a> for gallery blocks support. This is currently set to the 5.1 milestone, but it might change.</p>\n\n<p>You can even look at the proposed <a href=\"https://core.trac.wordpress.org/attachment/ticket/43826/43826.6.diff\" rel=\"nofollow noreferrer\">patches</a>, that uses e.g. <code>parse_blocks( $post->post_content )</code> and <code>has_block( 'gallery', $post->post_content )</code> , to get an idea what's needed to fully support this.</p>\n\n<p>In the meanwhile you could look into the <code>render_block</code> filter to modify the rendered output of gallery blocks to your needs. </p>\n\n<p>Here's an example that targets the <code>core/gallery</code> block and uses the block attribute containing the gallery image IDs:</p>\n\n<pre><code>/**\n * Modify the output of the rendered core/gallery block.\n */\nadd_filter( 'render_block', function( $block_content, $block ) {\n if ( 'core/gallery' !== $block['blockName'] || ! isset( $block['attrs']['ids'] ) ) {\n return $block_content;\n }\n $li = '';\n foreach( (array) $block['attrs']['ids'] as $id ) {\n $li .= sprintf( '<li>%s</li>', wp_get_attachment_image( $id, 'large' ) );\n }\n return sprintf( '<ul>%s</ul>', $li ); \n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 325708,
"author": "kosher",
"author_id": 120936,
"author_profile": "https://wordpress.stackexchange.com/users/120936",
"pm_score": 4,
"selected": true,
"text": "<p>Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. </p>\n\n<pre><code>// if there is a gallery block do this\nif (has_block('gallery', $post->post_content)) {\n $post_blocks = parse_blocks($post->post_content);\n $ids = $post_blocks[0][attrs][ids];\n} \n// if there is not a gallery block do this\nelse {\n // gets the gallery info\n $gallery = get_post_gallery( $post->ID, false );\n // makes an array of image ids\n $ids = explode ( \",\", $gallery['ids'] );\n}\n</code></pre>\n"
}
] | 2019/01/12 | [
"https://wordpress.stackexchange.com/questions/325429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158888/"
] | I have a website running WP connected to a MySql db, where the latter uses PHP. I did not make the site and have only small experience with WP. This may be a simple question. The WP also uses Elementor. I interact with the db via phpMyAdmin.
I have this page = <http://linket.info/signup/>
It accepts input data that does into the db.
See the labels ('First Name' etc). I can't seem to find them defined in WP. So they are in the db? I looked in the various db tables. But still can't seem to find these labels. Can you suggest what tables I might focus on? | Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0.
```
// if there is a gallery block do this
if (has_block('gallery', $post->post_content)) {
$post_blocks = parse_blocks($post->post_content);
$ids = $post_blocks[0][attrs][ids];
}
// if there is not a gallery block do this
else {
// gets the gallery info
$gallery = get_post_gallery( $post->ID, false );
// makes an array of image ids
$ids = explode ( ",", $gallery['ids'] );
}
``` |
325,469 | <p>In my index page there are two slider one is working fine but the second one is giving some problems.</p>
<h2>FIRST ONE</h2>
<pre><code><?php
global $post;
$i=0;
$args = array('post_per_page' => -1, 'post_type' => 'slider-items', 'page' => $paged, 'order' => 'ASC');
$myposts = get_posts($args);
foreach( $myposts as $post ) : setup_postdata($post);
$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'slider-items');
$i++;
?>
<!-- Slider Item -->
<div class="owl-item main_slider_item">
<div class="main_slider_item_bg" style="background-image:url(<?php echo $large_image_url[0]; ?>)"></div>
<div class="main_slider_shapes"><img src="<?php echo get_template_directory_uri() ?>/images/main_slider_shapes.png" alt="" style="width: 100% !important;"></div>
<div class="container">
<div class="row">
<div class="col slider_content_col">
<div class="main_slider_content">
<h2></h2>
<h2><?php the_content(); ?></h2>
<div class="button discover_button">
<a href="#" class="d-flex flex-row align-items-center justify-content-center">discover<img src="<?php echo get_template_directory_uri() ?>/images/arrow_right.svg" alt=""></a>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
endforeach;
?>
</code></pre>
<h2>SECOND ONE</h2>
<pre><code><?php
global $small_post;
$x=0;
$small_args = array('post_per_page' => -1, 'post_type' => 'bottom-slider-items', 'page' => $small_paged);
$small_myposts = get_posts($small_args);
foreach( $small_myposts as $small_post ) : setup_postdata($small_post);
$small_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($small_post->ID), 'bottom-slider-items');
$x++;
?>
<div class="owl-item testimonials_item d-flex flex-column align-items-center justify-content-center text-center">
<div class="testimonials_content">
<div class="test_user_pic" style="background-image:url(<?php echo $small_image_url[0]; ?>)"></div>
<div class="test_name"><?php echo get_the_title(); ?></div>
<div class="test_title">Company CEO</div>
<div class="test_quote">"</div>
<p><?php the_content(); ?></p>
</div>
</div>
<?php
endforeach;
?>
</code></pre>
<hr>
<p>When I call <code>get_the_title()</code> it shows me the title of first loop. I have added three sliders post in the first one and the second loop showing title of the last one. Please help.</p>
| [
{
"answer_id": 325431,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>The <code>get_post_gallery()</code> is a wrapper for <code>get_post_galleries()</code> that has an open ticket \n<a href=\"https://core.trac.wordpress.org/ticket/43826\" rel=\"nofollow noreferrer\">#43826</a> for gallery blocks support. This is currently set to the 5.1 milestone, but it might change.</p>\n\n<p>You can even look at the proposed <a href=\"https://core.trac.wordpress.org/attachment/ticket/43826/43826.6.diff\" rel=\"nofollow noreferrer\">patches</a>, that uses e.g. <code>parse_blocks( $post->post_content )</code> and <code>has_block( 'gallery', $post->post_content )</code> , to get an idea what's needed to fully support this.</p>\n\n<p>In the meanwhile you could look into the <code>render_block</code> filter to modify the rendered output of gallery blocks to your needs. </p>\n\n<p>Here's an example that targets the <code>core/gallery</code> block and uses the block attribute containing the gallery image IDs:</p>\n\n<pre><code>/**\n * Modify the output of the rendered core/gallery block.\n */\nadd_filter( 'render_block', function( $block_content, $block ) {\n if ( 'core/gallery' !== $block['blockName'] || ! isset( $block['attrs']['ids'] ) ) {\n return $block_content;\n }\n $li = '';\n foreach( (array) $block['attrs']['ids'] as $id ) {\n $li .= sprintf( '<li>%s</li>', wp_get_attachment_image( $id, 'large' ) );\n }\n return sprintf( '<ul>%s</ul>', $li ); \n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 325708,
"author": "kosher",
"author_id": 120936,
"author_profile": "https://wordpress.stackexchange.com/users/120936",
"pm_score": 4,
"selected": true,
"text": "<p>Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0. </p>\n\n<pre><code>// if there is a gallery block do this\nif (has_block('gallery', $post->post_content)) {\n $post_blocks = parse_blocks($post->post_content);\n $ids = $post_blocks[0][attrs][ids];\n} \n// if there is not a gallery block do this\nelse {\n // gets the gallery info\n $gallery = get_post_gallery( $post->ID, false );\n // makes an array of image ids\n $ids = explode ( \",\", $gallery['ids'] );\n}\n</code></pre>\n"
}
] | 2019/01/13 | [
"https://wordpress.stackexchange.com/questions/325469",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158922/"
] | In my index page there are two slider one is working fine but the second one is giving some problems.
FIRST ONE
---------
```
<?php
global $post;
$i=0;
$args = array('post_per_page' => -1, 'post_type' => 'slider-items', 'page' => $paged, 'order' => 'ASC');
$myposts = get_posts($args);
foreach( $myposts as $post ) : setup_postdata($post);
$large_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'slider-items');
$i++;
?>
<!-- Slider Item -->
<div class="owl-item main_slider_item">
<div class="main_slider_item_bg" style="background-image:url(<?php echo $large_image_url[0]; ?>)"></div>
<div class="main_slider_shapes"><img src="<?php echo get_template_directory_uri() ?>/images/main_slider_shapes.png" alt="" style="width: 100% !important;"></div>
<div class="container">
<div class="row">
<div class="col slider_content_col">
<div class="main_slider_content">
<h2></h2>
<h2><?php the_content(); ?></h2>
<div class="button discover_button">
<a href="#" class="d-flex flex-row align-items-center justify-content-center">discover<img src="<?php echo get_template_directory_uri() ?>/images/arrow_right.svg" alt=""></a>
</div>
</div>
</div>
</div>
</div>
</div>
<?php
endforeach;
?>
```
SECOND ONE
----------
```
<?php
global $small_post;
$x=0;
$small_args = array('post_per_page' => -1, 'post_type' => 'bottom-slider-items', 'page' => $small_paged);
$small_myposts = get_posts($small_args);
foreach( $small_myposts as $small_post ) : setup_postdata($small_post);
$small_image_url = wp_get_attachment_image_src( get_post_thumbnail_id($small_post->ID), 'bottom-slider-items');
$x++;
?>
<div class="owl-item testimonials_item d-flex flex-column align-items-center justify-content-center text-center">
<div class="testimonials_content">
<div class="test_user_pic" style="background-image:url(<?php echo $small_image_url[0]; ?>)"></div>
<div class="test_name"><?php echo get_the_title(); ?></div>
<div class="test_title">Company CEO</div>
<div class="test_quote">"</div>
<p><?php the_content(); ?></p>
</div>
</div>
<?php
endforeach;
?>
```
---
When I call `get_the_title()` it shows me the title of first loop. I have added three sliders post in the first one and the second loop showing title of the last one. Please help. | Using birgire's suggestions, I came up with the following solution that is working well with both the old pre-WP 4.x data and the newer posts that have been added under 5.0.
```
// if there is a gallery block do this
if (has_block('gallery', $post->post_content)) {
$post_blocks = parse_blocks($post->post_content);
$ids = $post_blocks[0][attrs][ids];
}
// if there is not a gallery block do this
else {
// gets the gallery info
$gallery = get_post_gallery( $post->ID, false );
// makes an array of image ids
$ids = explode ( ",", $gallery['ids'] );
}
``` |
325,489 | <p>In a template, I have a need to <code>include_once</code> an external PHP (an <code>include.php</code>) that contains functions that I need to use inside the template.</p>
<p>Included in those functions are CSS styles and an external JS script.</p>
<p>The CSS is inside a function in the include.php. And the JS script also needs to be in the area.</p>
<p>So I need to <code>include_once("includes.php")</code> (which is in the theme's root folder). I figured I would use code similar to this:</p>
<pre><code>add_action('wp_head', 'fst_include',20);
function fst_include() {
include_once get_stylesheet_directory(). "/includes.php"; // load required functions
return;
}
</code></pre>
<p>Since the action is 'wp_head', that should get the <code>include_once("includes.php")</code> in the head area. I use <code>get_stylesheet_directory</code> because the includes.php file will be in a Child Theme.</p>
<p>Once that is loaded, then I can add some CSS with this:</p>
<pre><code>add_action('wp_head', 'more_css',30) // 'more_css' is a function inside the includes.php file that contains some CSS
</code></pre>
<p>And add some JS with</p>
<pre><code>add_action('wp_head', 'some_script',30) // 'some_script' is a function inside the includes.php file that adds some JS
</code></pre>
<p>I give the last two add_actions a priority of '30' so they will be loaded after the includes.php file is loaded. (Because the includes.php has a priority of 20.)</p>
<p>But the includes.php file doesn't appear to be loading, as the 'some_script' function (contained in includes.php) is not available, and causes an error.</p>
<p>So I need a way to add a <code>include_once('includes.php')</code> so that the functions inside there are available 'later' in the template. I don't think that <code>get_template_part</code> is appropriate because the <code>include_once</code> needs to be in the section.</p>
<p><strong>Added - But Why?</strong></p>
<p>Why do I need to do this? My template displays a form. The form's code and functions are in the include.php file. Even the form is displayed by a function in the include.php.</p>
<p>The include.php file is a 'package' of functions and scripts and actions and changing of DOM elements to perform specific functions when the form is displayed - and the user fills out the form and submits it. (The 'package' is the process that is used to protect forms - like contact forms - against spam-bots. It's an effective process, but a bit complex. If you are really interested, you can go <a href="https://www.formspammertrap.com" rel="nofollow noreferrer">here</a> to learn about it.)</p>
<p>The include.php file is also built as a standalone/non-WP code that can be used on non-WP pages. I don't want to maintain two versions of the code.</p>
<p>The form has to 'live' in the visual look of whatever theme is being used, if used on a WP site. I figured a template would be the best way to do that. So I need to get my include.php 'inside' the template so that it's functions can be called.</p>
<p>As for the priorty used in the add_action, that was an attempt to make sure that the include.php file is included in the area so that I can call the function that includes the CSS used for the form. If include.php is not loaded first, then the CSS-calling function will fail.</p>
| [
{
"answer_id": 325490,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>Including PHP files inside actions isn't recommended, and is considered <strong>highly unusual</strong>. If what you were trying to do worked, it would be fragile, and heavily dependent on ordering.</p>\n\n<p>The reason your code didn't work:</p>\n\n<pre><code>add_action('wp_head', 'fst_include',20);\n</code></pre>\n\n<p>Is because actions are added with a priority of <code>10</code> by default, yet your include is on priority 20, so it happens after the other hooks, not before. As a result, when <code>more_css</code> is executed, it has yet to be defined.</p>\n\n<p>Instead, don't load the file on a hook, just load it immediatley so that the functions are defined, but not executed, then add the functions as actions.</p>\n\n<p>In general, it is a bad idea to mix loading code, and running code. Try to:</p>\n\n<ul>\n<li>Load the code or autoloader</li>\n<li>Create all the objects but don't run them</li>\n<li>Then run it once everything is assembled</li>\n</ul>\n"
},
{
"answer_id": 326293,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": true,
"text": "<p>After much experimentation, and limited help from the googles, I figured how to do an '<code>include</code>' of an external functions file inside a Template.</p>\n\n<p>The key is to use the <code>get_template_part</code> in your Template at the beginning (after the template header). The file specified in that function must be in your Theme's root folder, although I think it could also be in the theme's template folder.</p>\n\n<pre><code>get_template_part('my_custom_functions');\n</code></pre>\n\n<p>This will do the equivalent of a '<code>include</code>' in a non-WP PHP code. It will '<code>include</code>' the file called <code>my_custom_functions.php</code> . </p>\n\n<p>Once you do that, then you can use filters to include things in the generated page's <code><head></code> area, or any other filters you need, as in:</p>\n\n<pre><code>add_filter('wp_head','some_function');\n</code></pre>\n\n<p>Which will call the <code>some_function()</code> function in your <code>my_custom_functions.php</code> file. (Make sure that your function names are unique, of course.)</p>\n\n<p>This process, which is not easily found via the googles, will let you 'include' a file and then use functions in your include file in your WP Template.</p>\n"
}
] | 2019/01/13 | [
"https://wordpress.stackexchange.com/questions/325489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29416/"
] | In a template, I have a need to `include_once` an external PHP (an `include.php`) that contains functions that I need to use inside the template.
Included in those functions are CSS styles and an external JS script.
The CSS is inside a function in the include.php. And the JS script also needs to be in the area.
So I need to `include_once("includes.php")` (which is in the theme's root folder). I figured I would use code similar to this:
```
add_action('wp_head', 'fst_include',20);
function fst_include() {
include_once get_stylesheet_directory(). "/includes.php"; // load required functions
return;
}
```
Since the action is 'wp\_head', that should get the `include_once("includes.php")` in the head area. I use `get_stylesheet_directory` because the includes.php file will be in a Child Theme.
Once that is loaded, then I can add some CSS with this:
```
add_action('wp_head', 'more_css',30) // 'more_css' is a function inside the includes.php file that contains some CSS
```
And add some JS with
```
add_action('wp_head', 'some_script',30) // 'some_script' is a function inside the includes.php file that adds some JS
```
I give the last two add\_actions a priority of '30' so they will be loaded after the includes.php file is loaded. (Because the includes.php has a priority of 20.)
But the includes.php file doesn't appear to be loading, as the 'some\_script' function (contained in includes.php) is not available, and causes an error.
So I need a way to add a `include_once('includes.php')` so that the functions inside there are available 'later' in the template. I don't think that `get_template_part` is appropriate because the `include_once` needs to be in the section.
**Added - But Why?**
Why do I need to do this? My template displays a form. The form's code and functions are in the include.php file. Even the form is displayed by a function in the include.php.
The include.php file is a 'package' of functions and scripts and actions and changing of DOM elements to perform specific functions when the form is displayed - and the user fills out the form and submits it. (The 'package' is the process that is used to protect forms - like contact forms - against spam-bots. It's an effective process, but a bit complex. If you are really interested, you can go [here](https://www.formspammertrap.com) to learn about it.)
The include.php file is also built as a standalone/non-WP code that can be used on non-WP pages. I don't want to maintain two versions of the code.
The form has to 'live' in the visual look of whatever theme is being used, if used on a WP site. I figured a template would be the best way to do that. So I need to get my include.php 'inside' the template so that it's functions can be called.
As for the priorty used in the add\_action, that was an attempt to make sure that the include.php file is included in the area so that I can call the function that includes the CSS used for the form. If include.php is not loaded first, then the CSS-calling function will fail. | After much experimentation, and limited help from the googles, I figured how to do an '`include`' of an external functions file inside a Template.
The key is to use the `get_template_part` in your Template at the beginning (after the template header). The file specified in that function must be in your Theme's root folder, although I think it could also be in the theme's template folder.
```
get_template_part('my_custom_functions');
```
This will do the equivalent of a '`include`' in a non-WP PHP code. It will '`include`' the file called `my_custom_functions.php` .
Once you do that, then you can use filters to include things in the generated page's `<head>` area, or any other filters you need, as in:
```
add_filter('wp_head','some_function');
```
Which will call the `some_function()` function in your `my_custom_functions.php` file. (Make sure that your function names are unique, of course.)
This process, which is not easily found via the googles, will let you 'include' a file and then use functions in your include file in your WP Template. |
325,536 | <p>I have 2 categories in my cutom post type:
Cat 1
Cat 2</p>
<p>I wish display a random category from this post type. I made this and it works:</p>
<pre><code>function categorie(){
$global;
$args = array('type' => 'carte', 'taxonomy' => 'carte-category', 'parent' => 0);
$categories = get_categories($args);
shuffle( $categories);
$i = 0;
foreach($categories as $category) {
$i++;
$categoryname= $category->name;
$html.= '<h3> '. $category->name. '</h3>';
$html.= '<p class="txtContent"> '. $category->description. '</p>';
if (++$i == 2) break;
}
return $html;
}
add_shortcode( 'categorie', 'categorie' );
</code></pre>
<p>But now in this random category, I wish display a thumbnail from random post</p>
<p>To be clear:</p>
<p>Cat1 = Menus
Posts: Menu 1, menu 2...</p>
<p>Cat 2 = Dishes
Posts: Dish 1, Dish 2...</p>
<p>If my random cat is displaying Cat1, I need the thumbnail of Menu 1 or Menu 2</p>
<p>How can I do that ?</p>
| [
{
"answer_id": 325538,
"author": "wpdev",
"author_id": 133897,
"author_profile": "https://wordpress.stackexchange.com/users/133897",
"pm_score": -1,
"selected": false,
"text": "<p>Inser this inside foreach loop:</p>\n\n<pre><code>$args_query = array(\n 'order' => 'DESC',\n 'orderby' => 'rand',\n 'posts_per_page' => 1,\n 'cat' => $category->term_id,\n);\n\n$query = new WP_Query( $args_query );\n\nif( $query->have_posts() ) {\n while( $query->have_posts() ) {\n $query->the_post();\n the_post_thumbnail();\n }\n} else {\n echo 'No post found';\n}\n\nwp_reset_postdata();\n</code></pre>\n"
},
{
"answer_id": 325544,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 2,
"selected": true,
"text": "<p>All you need to do is to add another query in your code:</p>\n\n<pre><code>function categorie_shortcode_callback() { \n $html = '';\n $categories = get_categories( array( \n // 'type' => 'carte', <- THERE IS NO ATTRIBUTE CALLED type FOR get_categories, SO REMOVE THAT\n 'taxonomy' => 'carte-category',\n 'parent' => 0\n ));\n shuffle( $categories);\n\n // you also don't need to loop through that array, since you only want to get first one\n if ( ! empty($categories) ) {\n $category = $categories[0];\n $html.= '<h3> '. $category->name. '</h3>';\n $html.= '<p class=\"txtContent\"> '. $category->description. '</p>'; \n\n $random_posts = get_posts( array(\n 'post_type' => 'carte',\n 'posts_per_page' => 1,\n 'orderby' => 'rand',\n 'fields' => 'ids',\n 'tax_query' => array(\n array( 'taxonomy' => 'carte-category', 'terms' => $category->term_id, 'field' => 'term_id' )\n )\n ) );\n if ( ! empty($random_posts) ) {\n $html .= get_the_post_thumbnail( $random_posts[0] );\n }\n }\n\n return $html;\n}\nadd_shortcode( 'categorie', 'categorie_shortcode_callback' );\n</code></pre>\n"
}
] | 2019/01/14 | [
"https://wordpress.stackexchange.com/questions/325536",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158978/"
] | I have 2 categories in my cutom post type:
Cat 1
Cat 2
I wish display a random category from this post type. I made this and it works:
```
function categorie(){
$global;
$args = array('type' => 'carte', 'taxonomy' => 'carte-category', 'parent' => 0);
$categories = get_categories($args);
shuffle( $categories);
$i = 0;
foreach($categories as $category) {
$i++;
$categoryname= $category->name;
$html.= '<h3> '. $category->name. '</h3>';
$html.= '<p class="txtContent"> '. $category->description. '</p>';
if (++$i == 2) break;
}
return $html;
}
add_shortcode( 'categorie', 'categorie' );
```
But now in this random category, I wish display a thumbnail from random post
To be clear:
Cat1 = Menus
Posts: Menu 1, menu 2...
Cat 2 = Dishes
Posts: Dish 1, Dish 2...
If my random cat is displaying Cat1, I need the thumbnail of Menu 1 or Menu 2
How can I do that ? | All you need to do is to add another query in your code:
```
function categorie_shortcode_callback() {
$html = '';
$categories = get_categories( array(
// 'type' => 'carte', <- THERE IS NO ATTRIBUTE CALLED type FOR get_categories, SO REMOVE THAT
'taxonomy' => 'carte-category',
'parent' => 0
));
shuffle( $categories);
// you also don't need to loop through that array, since you only want to get first one
if ( ! empty($categories) ) {
$category = $categories[0];
$html.= '<h3> '. $category->name. '</h3>';
$html.= '<p class="txtContent"> '. $category->description. '</p>';
$random_posts = get_posts( array(
'post_type' => 'carte',
'posts_per_page' => 1,
'orderby' => 'rand',
'fields' => 'ids',
'tax_query' => array(
array( 'taxonomy' => 'carte-category', 'terms' => $category->term_id, 'field' => 'term_id' )
)
) );
if ( ! empty($random_posts) ) {
$html .= get_the_post_thumbnail( $random_posts[0] );
}
}
return $html;
}
add_shortcode( 'categorie', 'categorie_shortcode_callback' );
``` |
325,563 | <p>I created a page (<a href="https://padigital.org/rights/" rel="nofollow noreferrer">https://padigital.org/rights/</a>) to test something, then deleted it. It still appears in Google searches. However, it no longer appears in the Admin Dashboard, so I'm unable to delete/make it private. How do I find it to delete it again?</p>
| [
{
"answer_id": 325566,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 1,
"selected": false,
"text": "<p>Since that page has already been indexed you can do a couple things.</p>\n\n<p><strong>1</strong> - Add a rule in your .htaccess file that tells search engines not to index the page</p>\n\n<pre><code>User-agent: *\nDisallow: /rights\n</code></pre>\n\n<p><strong>2</strong> - Use Google's Remove URLs Tool. The Remove URLs tool enables you to temporarily block pages from Google Search results. You can <a href=\"https://www.google.com/webmasters/tools/url-removal\" rel=\"nofollow noreferrer\">start that process here</a>.</p>\n"
},
{
"answer_id": 325567,
"author": "Arturo Gallegos",
"author_id": 130585,
"author_profile": "https://wordpress.stackexchange.com/users/130585",
"pm_score": -1,
"selected": false,
"text": "<p>Don't worry, google check your page with the time and remove automatically.</p>\n\n<p>Also, you can enter in your search console of google and resend your sitemaps</p>\n"
}
] | 2019/01/14 | [
"https://wordpress.stackexchange.com/questions/325563",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159001/"
] | I created a page (<https://padigital.org/rights/>) to test something, then deleted it. It still appears in Google searches. However, it no longer appears in the Admin Dashboard, so I'm unable to delete/make it private. How do I find it to delete it again? | Since that page has already been indexed you can do a couple things.
**1** - Add a rule in your .htaccess file that tells search engines not to index the page
```
User-agent: *
Disallow: /rights
```
**2** - Use Google's Remove URLs Tool. The Remove URLs tool enables you to temporarily block pages from Google Search results. You can [start that process here](https://www.google.com/webmasters/tools/url-removal). |
325,569 | <p>I want to create on my blog a category loop with the featured image.
But i don't know how i do that technical.</p>
<p>You should only see a list of categories and click on them to get the category site. It's like a article loop only with categories.</p>
<p>Thank you for any help :)</p>
<p><a href="https://i.stack.imgur.com/mRLy9.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mRLy9.jpg" alt="enter image description here"></a></p>
| [
{
"answer_id": 325583,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 1,
"selected": false,
"text": "<p>Well, in WP the word \"loop\" is mainly related to posts. It's easier to say that you want to display categories.</p>\n\n<p>All you have to do is to get them using <a href=\"https://developer.wordpress.org/reference/functions/get_categories/\" rel=\"nofollow noreferrer\"><code>get_categories</code></a> function and display them.</p>\n\n<pre><code><?php\n $categories = get_categories( array(\n 'orderby' => 'name',\n 'order' => 'ASC'\n ) );\n if ( ! empty( $categories ) ) :\n?>\n<ul>\n <?php foreach ( $categories as $category ) : ?>\n <li><a href=\"<?php echo esc_attr(get_category_link( $category->term_id ) ); ?>\"><?php echo esc_html( $category->name ); ?></a></li>\n <?php endforeach; ?>\n</ul>\n<?php endif; ?>\n</code></pre>\n\n<p>And if you want to change the category title to some ACF custom field, then change this part:</p>\n\n<pre><code><?php echo esc_html( $category->name ); ?>\n</code></pre>\n\n<p>to:</p>\n\n<pre><code><?php echo wp_get_attachment_image( get_field('<FIELD_NAME>', $category), 'full' ); ?>\n</code></pre>\n\n<p>PS. Remember to change to real name of the field. It should return the ID of an image (and not the array - you should set it in field setting). You can also change the 'full' size to some other size.</p>\n"
},
{
"answer_id": 325585,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>The key to this is <a href=\"https://developer.wordpress.org/reference/functions/get_categories/\" rel=\"nofollow noreferrer\"><code>get_categories()</code></a> function.</p>\n\n<p>You can use it as follows, note that I assumed the featured image url is stored in a meta of the category which may not be your case:</p>\n\n<pre><code>$categories = get_categories();\nif(count($categories)) {\n foreach($categories as $cat) {\n $catID = $cat->term_id;\n $img = get_term_meta($catID, 'featured_image', true);\n $url = esc_url( get_category_link( $catID ) );\n echo \"<a href='$url'><img src='$img' /></a>\";\n }\n} else {\n echo \"No categories!\";\n}\n</code></pre>\n\n<p>In case you're using <strong>ACF image field</strong> to add the featured image to the category, it's better to use <a href=\"https://www.advancedcustomfields.com/resources/get_field/\" rel=\"nofollow noreferrer\"><code>get_field('featured_image', 'category_'.$catID)</code></a> instead of <code>get_term_meta()</code>. The code in that case depends on your field settings, so I encourage you to read the <a href=\"https://www.advancedcustomfields.com/resources/image/\" rel=\"nofollow noreferrer\">documentation here</a>.</p>\n"
}
] | 2019/01/14 | [
"https://wordpress.stackexchange.com/questions/325569",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158400/"
] | I want to create on my blog a category loop with the featured image.
But i don't know how i do that technical.
You should only see a list of categories and click on them to get the category site. It's like a article loop only with categories.
Thank you for any help :)
[](https://i.stack.imgur.com/mRLy9.jpg) | Well, in WP the word "loop" is mainly related to posts. It's easier to say that you want to display categories.
All you have to do is to get them using [`get_categories`](https://developer.wordpress.org/reference/functions/get_categories/) function and display them.
```
<?php
$categories = get_categories( array(
'orderby' => 'name',
'order' => 'ASC'
) );
if ( ! empty( $categories ) ) :
?>
<ul>
<?php foreach ( $categories as $category ) : ?>
<li><a href="<?php echo esc_attr(get_category_link( $category->term_id ) ); ?>"><?php echo esc_html( $category->name ); ?></a></li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
```
And if you want to change the category title to some ACF custom field, then change this part:
```
<?php echo esc_html( $category->name ); ?>
```
to:
```
<?php echo wp_get_attachment_image( get_field('<FIELD_NAME>', $category), 'full' ); ?>
```
PS. Remember to change to real name of the field. It should return the ID of an image (and not the array - you should set it in field setting). You can also change the 'full' size to some other size. |
325,574 | <p>The following code should redirect the user to a specific page if they have the manage_woocommerce capability or higher - but it doesn't and just goes to the main dashboard.</p>
<pre><code> add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );
public function login_redirect( $redirect_to, $request, $user ) {
if( is_user_logged_in() == 1 ) {
if( $user->has_cap( 'manage_woocommerce' ) ) {
$redirect_to = get_admin_url() . 'admin.php?page=my-page';
}
}
return $redirect_to;
}
</code></pre>
<p>I have tried <code>$user->has_cap</code>, <a href="https://codex.wordpress.org/Function_Reference/current_user_can" rel="nofollow noreferrer">current_user_can</a> with the same result. </p>
| [
{
"answer_id": 325587,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, it wasn't easy to catch, but... There is one major problem in your code...</p>\n\n<p>First check you make is:</p>\n\n<pre><code>if ( is_user_logged_in() == 1 ) {\n</code></pre>\n\n<p>And <code>is_user_logged_in()</code> is based on global <code>$current_user</code> variable. But... As you can read in <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect\" rel=\"nofollow noreferrer\"><code>login_redirect</code> hook docs</a>:</p>\n\n<blockquote>\n <p>The $current_user global may not be available at the time this filter\n is run. So you should use the $user global or the $user parameter\n passed to this filter.</p>\n</blockquote>\n\n<p>So this condition won't be satisfied - so your code won't change anything.</p>\n\n<p>You should use <code>$user</code> variable that is passed as param, so this should do the trick:</p>\n\n<pre><code>public function login_redirect( $redirect_to, $request, $user ) {\n\n if ( is_a ( $user , 'WP_User' ) && $user->exists() ) {\n\n if ( $user->has_cap( 'manage_woocommerce' ) ) {\n\n $redirect_to = get_admin_url() . 'admin.php?page=my-page';\n\n }\n\n }\n\n return $redirect_to;\n}\nadd_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 325599,
"author": "John Zenith",
"author_id": 136579,
"author_profile": "https://wordpress.stackexchange.com/users/136579",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is fine, but you're calling the <code>is_user_logged_in()</code> function too early. It will only work after another page load. So here's a simplified and efficient version to achieve the functionality:</p>\n\n<pre>\nadd_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );\n\npublic function login_redirect( $redirect_to, $request, $user )\n{\n if ( $user instanceof WP_User && user_can( $user, 'manage_woocommerce' ) ) {\n $redirect_to = get_admin_url() . 'admin.php?page=userexplorer-userify';\n }\n\n return $redirect_to;\n}\n</pre>\n"
}
] | 2019/01/14 | [
"https://wordpress.stackexchange.com/questions/325574",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/75779/"
] | The following code should redirect the user to a specific page if they have the manage\_woocommerce capability or higher - but it doesn't and just goes to the main dashboard.
```
add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );
public function login_redirect( $redirect_to, $request, $user ) {
if( is_user_logged_in() == 1 ) {
if( $user->has_cap( 'manage_woocommerce' ) ) {
$redirect_to = get_admin_url() . 'admin.php?page=my-page';
}
}
return $redirect_to;
}
```
I have tried `$user->has_cap`, [current\_user\_can](https://codex.wordpress.org/Function_Reference/current_user_can) with the same result. | OK, it wasn't easy to catch, but... There is one major problem in your code...
First check you make is:
```
if ( is_user_logged_in() == 1 ) {
```
And `is_user_logged_in()` is based on global `$current_user` variable. But... As you can read in [`login_redirect` hook docs](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect):
>
> The $current\_user global may not be available at the time this filter
> is run. So you should use the $user global or the $user parameter
> passed to this filter.
>
>
>
So this condition won't be satisfied - so your code won't change anything.
You should use `$user` variable that is passed as param, so this should do the trick:
```
public function login_redirect( $redirect_to, $request, $user ) {
if ( is_a ( $user , 'WP_User' ) && $user->exists() ) {
if ( $user->has_cap( 'manage_woocommerce' ) ) {
$redirect_to = get_admin_url() . 'admin.php?page=my-page';
}
}
return $redirect_to;
}
add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );
``` |
325,622 | <p>How can I put my own code in a wordpress page? </p>
<p>This happens when I tried to
<a href="https://i.stack.imgur.com/27KOk.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/27KOk.png" alt="pic1"></a></p>
<p><a href="https://i.stack.imgur.com/yZOyA.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/yZOyA.png" alt="pic2"></a></p>
| [
{
"answer_id": 325587,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 3,
"selected": true,
"text": "<p>OK, it wasn't easy to catch, but... There is one major problem in your code...</p>\n\n<p>First check you make is:</p>\n\n<pre><code>if ( is_user_logged_in() == 1 ) {\n</code></pre>\n\n<p>And <code>is_user_logged_in()</code> is based on global <code>$current_user</code> variable. But... As you can read in <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect\" rel=\"nofollow noreferrer\"><code>login_redirect</code> hook docs</a>:</p>\n\n<blockquote>\n <p>The $current_user global may not be available at the time this filter\n is run. So you should use the $user global or the $user parameter\n passed to this filter.</p>\n</blockquote>\n\n<p>So this condition won't be satisfied - so your code won't change anything.</p>\n\n<p>You should use <code>$user</code> variable that is passed as param, so this should do the trick:</p>\n\n<pre><code>public function login_redirect( $redirect_to, $request, $user ) {\n\n if ( is_a ( $user , 'WP_User' ) && $user->exists() ) {\n\n if ( $user->has_cap( 'manage_woocommerce' ) ) {\n\n $redirect_to = get_admin_url() . 'admin.php?page=my-page';\n\n }\n\n }\n\n return $redirect_to;\n}\nadd_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );\n</code></pre>\n"
},
{
"answer_id": 325599,
"author": "John Zenith",
"author_id": 136579,
"author_profile": "https://wordpress.stackexchange.com/users/136579",
"pm_score": 1,
"selected": false,
"text": "<p>Your code is fine, but you're calling the <code>is_user_logged_in()</code> function too early. It will only work after another page load. So here's a simplified and efficient version to achieve the functionality:</p>\n\n<pre>\nadd_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );\n\npublic function login_redirect( $redirect_to, $request, $user )\n{\n if ( $user instanceof WP_User && user_can( $user, 'manage_woocommerce' ) ) {\n $redirect_to = get_admin_url() . 'admin.php?page=userexplorer-userify';\n }\n\n return $redirect_to;\n}\n</pre>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325622",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159037/"
] | How can I put my own code in a wordpress page?
This happens when I tried to
[](https://i.stack.imgur.com/27KOk.png)
[](https://i.stack.imgur.com/yZOyA.png) | OK, it wasn't easy to catch, but... There is one major problem in your code...
First check you make is:
```
if ( is_user_logged_in() == 1 ) {
```
And `is_user_logged_in()` is based on global `$current_user` variable. But... As you can read in [`login_redirect` hook docs](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_redirect):
>
> The $current\_user global may not be available at the time this filter
> is run. So you should use the $user global or the $user parameter
> passed to this filter.
>
>
>
So this condition won't be satisfied - so your code won't change anything.
You should use `$user` variable that is passed as param, so this should do the trick:
```
public function login_redirect( $redirect_to, $request, $user ) {
if ( is_a ( $user , 'WP_User' ) && $user->exists() ) {
if ( $user->has_cap( 'manage_woocommerce' ) ) {
$redirect_to = get_admin_url() . 'admin.php?page=my-page';
}
}
return $redirect_to;
}
add_filter( 'login_redirect', array( $this, 'login_redirect' ), 10, 3 );
``` |
325,663 | <p>I'm trying to make some pretty URLs that show content from a category page. An example would be this: <a href="https://example.com/resources/white-paper" rel="nofollow noreferrer">https://example.com/resources/white-paper</a> (not a real WP page) would show content from <a href="https://example.com/resources/?type=white-paper" rel="nofollow noreferrer">https://example.com/resources/?type=white-paper</a>. /resources is an archive page of a custom post type, and the archive page template pulls the query string and displays posts of the respective taxonomy. Any tips on how to approach this?</p>
| [
{
"answer_id": 325671,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": -1,
"selected": false,
"text": "<p>As long as you're only dealing with one CPT, when you register your post type, make sure to set <code>has_archive</code> to true and <code>rewrite</code> to <code>array('slug' => 'resources')</code>. That way you are programmatically creating an archive.</p>\n\n<p>(If you did not set up <code>has_archive</code> when you first registered the CPT, you may need to <code>unregister_post_type()</code> which won't delete your posts but will clear it out, and then re-register it with the new settings. Finally, visit the permalinks settings page to flush permalinks.)</p>\n\n<p>Then, in a child theme or custom theme, create a file called <code>archive-resources.php</code>. This is where you can intercept the query string and respond appropriately. Here's the basic structure:</p>\n\n<pre><code><?php\n// if the query string is present\nif($_GET['type']) {\n get_header();\n // run your tax query here\n $args = array(\n 'post_type' => 'post',\n // tax query is an array of arrays\n 'tax_query' => array(\n array(\n 'taxonomy' => 'type',\n // you can pull various ways; this uses the slug i.e. 'white-paper'\n 'field' => 'slug',\n 'terms' => $_GET['type']\n )\n )\n );\n $posts = new WP_Query($args);\n if($posts->have_posts()) {\n while($posts->have_posts()): $posts->the_post();\n // your loop here\n endwhile;\n }\n get_footer();\n} else {\n // what to do if no query string is present\n // example: you could redirect elsewhere, or show a default taxonomy query\n}\n</code></pre>\n\n<p>The downside is your archive will run a default query, so you're basically throwing the results of that query out the window and then running your own. You could just run a regular Loop in the <code>else</code> condition and make use of it since it will run anyway.</p>\n"
},
{
"answer_id": 325673,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule\" rel=\"nofollow noreferrer\"><code>add_rewrite_rule()</code></a>.</p>\n\n<pre><code>function wpse325663_rewrite_resource_type() {\n add_rewrite_rule('^resources\\/(.+)/?', 'resources/?type=$matches[1]', 'top');\n}\nadd_action('init', 'wpse325663_rewrite_resource_type');\n</code></pre>\n\n<p>An important note from <a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_rule#Example\" rel=\"nofollow noreferrer\">the codex</a>:</p>\n\n<blockquote>\n <p>Do not forget to flush and regenerate the rewrite rules database after\n modifying rules. From <a href=\"https://codex.wordpress.org/Administration_Screens\" rel=\"nofollow noreferrer\">WordPress Administration Screens</a>, Select\n Settings -> Permalinks and just click Save Changes without any\n changes.</p>\n</blockquote>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325663",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28497/"
] | I'm trying to make some pretty URLs that show content from a category page. An example would be this: <https://example.com/resources/white-paper> (not a real WP page) would show content from <https://example.com/resources/?type=white-paper>. /resources is an archive page of a custom post type, and the archive page template pulls the query string and displays posts of the respective taxonomy. Any tips on how to approach this? | Use [`add_rewrite_rule()`](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule).
```
function wpse325663_rewrite_resource_type() {
add_rewrite_rule('^resources\/(.+)/?', 'resources/?type=$matches[1]', 'top');
}
add_action('init', 'wpse325663_rewrite_resource_type');
```
An important note from [the codex](https://codex.wordpress.org/Rewrite_API/add_rewrite_rule#Example):
>
> Do not forget to flush and regenerate the rewrite rules database after
> modifying rules. From [WordPress Administration Screens](https://codex.wordpress.org/Administration_Screens), Select
> Settings -> Permalinks and just click Save Changes without any
> changes.
>
>
> |
325,670 | <p>Any ideal way how to change Gutenberg's categories checkboxes to radio inputs? I have tried using this plugin: <a href="https://wordpress.org/plugins/categories-metabox-enhanced/" rel="nofollow noreferrer">Categories Metabox Enhanced</a>. </p>
<p>But it doesn't work fully well with Gutenberg, meaning my conditions to show some field when a term is checked doesn't work. Also this plugin adds an extra meta box without replacing Gutenberg's default categories box.</p>
<p><a href="https://i.stack.imgur.com/mbNZY.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mbNZY.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 328707,
"author": "leymannx",
"author_id": 30597,
"author_profile": "https://wordpress.stackexchange.com/users/30597",
"pm_score": -1,
"selected": false,
"text": "<p>Yes, <a href=\"https://wordpress.org/plugins/categories-metabox-enhanced/\" rel=\"nofollow noreferrer\">Categories Metabox Enhanced</a> quite cleverly adds its own custom meta boxes displaying the options of categories and custom taxonomies the way you configured it in the plugin's settings (as checkbox, radios or select).</p>\n\n<p>You then additionally just need to ensure to hide the default meta boxes manually by clicking the three small dots at the top of the post edit screen to \"Adjust display\" and uncheck \"Categories\" and your custom taxonomies.</p>\n\n<p>Above UI setting probably can be overridden by every other user. To programmatically remove the default category meta box from Gutenberg do the following. Source: <a href=\"https://github.com/WordPress/gutenberg/issues/6912#issuecomment-428403380\" rel=\"nofollow noreferrer\">[GitHub] Custom Taxonomy: Show in REST, Hide default Gutenberg Panel (comment)</a>.</p>\n\n<pre><code>/**\n * Disable display of Gutenberg Post Setting UI for a specific\n * taxonomy. While this isn't the official API for this need,\n * it works for now because only Gutenberg is dependent on the\n * REST API response.\n */\nadd_filter('rest_prepare_taxonomy', function ($response, $taxonomy) {\n if ('category' === $taxonomy->name) {\n $response->data['visibility']['show_ui'] = FALSE;\n }\n return $response;\n}, 10, 2);\n</code></pre>\n"
},
{
"answer_id": 346069,
"author": "paulthewalton",
"author_id": 174220,
"author_profile": "https://wordpress.stackexchange.com/users/174220",
"pm_score": 3,
"selected": false,
"text": "<p>Fortunately there is a hook that we can use to customize what component is used to render the taxonomy panels called <code>editor.PostTaxonomyType</code>.</p>\n\n<p>Gutenberg renders taxonomy panels with a component called <code>PostTaxonomies</code>, which really just checks whether the taxonomy is heirarchical or not, and passes the props along to either the <code>HierarchicalTermSelector</code> or <code>FlatTermSelector</code> components accordingly. Normally, these two components don't appear to be exposed in the Gutenberg API, except for within the <code>editor.PostTaxonomyType</code> hook, which passes the relevant component as the 1st argument.</p>\n\n<p>From there, all we have to do is extend the component, override the <code>renderTerms</code> method to change the input type from <code>checkbox</code> to <code>radio</code>, and override the <code>onChange</code> method to only return one selected term.</p>\n\n<p>Unfortunately, extending the class within the hook seemed to cause a noticable performance hit, but storing the extended class in the <code>window</code> seemed to mitigate that.</p>\n\n<p><a href=\"https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-taxonomies#posttaxonomies\" rel=\"noreferrer\">PostTaxonomies</a></p>\n\n<p><a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js\" rel=\"noreferrer\">HierarchicalTermSelector</a></p>\n\n<pre class=\"lang-js prettyprint-override\"><code>/**\n * External dependencies\n */\nimport { unescape as unescapeString } from 'lodash';\n\nfunction customizeTaxonomySelector( OriginalComponent ) {\n return function( props ) {\n if ( props.slug === 'my_taxonomy') {\n if ( ! window.HierarchicalTermRadioSelector ) {\n window.HierarchicalTermRadioSelector = class HierarchicalTermRadioSelector extends OriginalComponent {\n // Return only the selected term ID\n onChange( event ) {\n const { onUpdateTerms, taxonomy } = this.props;\n const termId = parseInt( event.target.value, 10 );\n onUpdateTerms( [ termId ], taxonomy.rest_base );\n }\n\n // Copied from HierarchicalTermSelector, changed input type to radio\n renderTerms( renderedTerms ) {\n const { terms = [] } = this.props;\n return renderedTerms.map( ( term ) => {\n const id = `editor-post-taxonomies-hierarchical-term-${ term.id }`;\n return (\n <div key={ term.id } className=\"editor-post-taxonomies__hierarchical-terms-choice\">\n <input\n id={ id }\n className=\"editor-post-taxonomies__hierarchical-terms-input\"\n type=\"radio\"\n checked={ terms.indexOf( term.id ) !== -1 }\n value={ term.id }\n onChange={ this.onChange }\n />\n <label htmlFor={ id }>{ unescapeString( term.name ) }</label>\n { !! term.children.length && <div className=\"editor-post-taxonomies__hierarchical-terms-subchoices\">{ this.renderTerms( term.children ) }</div> }\n </div>\n );\n } );\n }\n };\n }\n return <window.HierarchicalTermRadioSelector { ...props } />;\n }\n return <OriginalComponent { ...props } />;\n };\n}\nwp.hooks.addFilter( 'editor.PostTaxonomyType', 'my-custom-plugin', customizeTaxonomySelector );\n</code></pre>\n"
},
{
"answer_id": 349957,
"author": "luckyape",
"author_id": 101230,
"author_profile": "https://wordpress.stackexchange.com/users/101230",
"pm_score": 2,
"selected": false,
"text": "<p>Just in case someone needs the select box version, you can try the following, A slight modification to @Paul_Walton answer: </p>\n\n<pre><code>const {\n SelectControl,\n} = wp.components;\n\nfunction customizeTaxonomySelector(OriginalComponent) {\n return function(props) {\n if (props.slug === 'my_taxonomy') {\n if (!window.HierarchicalTermRadioSelector) {\n window.HierarchicalTermRadioSelector = class HierarchicalTermRadioSelector extends OriginalComponent {\n // Return only the selected term ID\n onChange(val) {\n console.info(event);\n const {\n onUpdateTerms,\n taxonomy\n } = this.props;\n const termId = parseInt(val, 10);\n onUpdateTerms([termId], taxonomy.rest_base);\n }\n // Copied from HierarchicalTermSelector, changed input type to radio\n renderTerms(renderedTerms) {\n const {\n terms = []\n } = this.props;\n return ( < SelectControl label = {\n __('Select some users:')\n }\n value = {\n terms[0]\n } // e.g: value = [ 'a', 'c' ]\n onChange = {\n this.onChange\n }\n options = {\n renderedTerms.map((term) => {\n return {\n value: term.id,\n label: term.name\n };\n })\n }\n />)\n }\n };\n }\n return <window.HierarchicalTermRadioSelector { ...props\n }\n />;\n }\n return <OriginalComponent { ...props\n }\n />;\n };\n }\n wp.hooks.addFilter('editor.PostTaxonomyType', 'my-plugin', customizeTaxonomySelector);\n</code></pre>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129306/"
] | Any ideal way how to change Gutenberg's categories checkboxes to radio inputs? I have tried using this plugin: [Categories Metabox Enhanced](https://wordpress.org/plugins/categories-metabox-enhanced/).
But it doesn't work fully well with Gutenberg, meaning my conditions to show some field when a term is checked doesn't work. Also this plugin adds an extra meta box without replacing Gutenberg's default categories box.
[](https://i.stack.imgur.com/mbNZY.png) | Fortunately there is a hook that we can use to customize what component is used to render the taxonomy panels called `editor.PostTaxonomyType`.
Gutenberg renders taxonomy panels with a component called `PostTaxonomies`, which really just checks whether the taxonomy is heirarchical or not, and passes the props along to either the `HierarchicalTermSelector` or `FlatTermSelector` components accordingly. Normally, these two components don't appear to be exposed in the Gutenberg API, except for within the `editor.PostTaxonomyType` hook, which passes the relevant component as the 1st argument.
From there, all we have to do is extend the component, override the `renderTerms` method to change the input type from `checkbox` to `radio`, and override the `onChange` method to only return one selected term.
Unfortunately, extending the class within the hook seemed to cause a noticable performance hit, but storing the extended class in the `window` seemed to mitigate that.
[PostTaxonomies](https://github.com/WordPress/gutenberg/tree/master/packages/editor/src/components/post-taxonomies#posttaxonomies)
[HierarchicalTermSelector](https://github.com/WordPress/gutenberg/blob/master/packages/editor/src/components/post-taxonomies/hierarchical-term-selector.js)
```js
/**
* External dependencies
*/
import { unescape as unescapeString } from 'lodash';
function customizeTaxonomySelector( OriginalComponent ) {
return function( props ) {
if ( props.slug === 'my_taxonomy') {
if ( ! window.HierarchicalTermRadioSelector ) {
window.HierarchicalTermRadioSelector = class HierarchicalTermRadioSelector extends OriginalComponent {
// Return only the selected term ID
onChange( event ) {
const { onUpdateTerms, taxonomy } = this.props;
const termId = parseInt( event.target.value, 10 );
onUpdateTerms( [ termId ], taxonomy.rest_base );
}
// Copied from HierarchicalTermSelector, changed input type to radio
renderTerms( renderedTerms ) {
const { terms = [] } = this.props;
return renderedTerms.map( ( term ) => {
const id = `editor-post-taxonomies-hierarchical-term-${ term.id }`;
return (
<div key={ term.id } className="editor-post-taxonomies__hierarchical-terms-choice">
<input
id={ id }
className="editor-post-taxonomies__hierarchical-terms-input"
type="radio"
checked={ terms.indexOf( term.id ) !== -1 }
value={ term.id }
onChange={ this.onChange }
/>
<label htmlFor={ id }>{ unescapeString( term.name ) }</label>
{ !! term.children.length && <div className="editor-post-taxonomies__hierarchical-terms-subchoices">{ this.renderTerms( term.children ) }</div> }
</div>
);
} );
}
};
}
return <window.HierarchicalTermRadioSelector { ...props } />;
}
return <OriginalComponent { ...props } />;
};
}
wp.hooks.addFilter( 'editor.PostTaxonomyType', 'my-custom-plugin', customizeTaxonomySelector );
``` |
325,672 | <p>I have created a search using WP_Query, it seems like this query is looking for the queried term in title AND tags. </p>
<p>Is there a way to have this search the title OR tags?</p>
<pre><code>$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));
$paged = $request['page'];
$posts_per_page = $request['per_page'];
$result = new WP_Query([
'post_type' => 'post',
'category__in' => 3060,
'posts_per_page' => $posts_per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'desc',
's' => $s,
'tag' => array($tags)
]);
</code></pre>
| [
{
"answer_id": 326512,
"author": "Community",
"author_id": -1,
"author_profile": "https://wordpress.stackexchange.com/users/-1",
"pm_score": -1,
"selected": false,
"text": "<p>You just need to add </p>\n\n<pre><code> 'relation' => 'OR'\n</code></pre>\n\n<p>in your Query arguments.\nadd it and it will return the data with OR condition.</p>\n\n<p>Hope it helps.</p>\n"
},
{
"answer_id": 326513,
"author": "Er Deepak Prabhakar",
"author_id": 159275,
"author_profile": "https://wordpress.stackexchange.com/users/159275",
"pm_score": 1,
"selected": false,
"text": "<p>Please use below code to show posts in texonomy and titles</p>\n\n<pre><code>$s = $request['s'];\n$tags = str_replace(' ', '-', strtolower($request['s']));\n\n$q1 = get_posts(array(\n 'fields' => 'id',\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 's' => $s \n\n));\n $q2 = get_posts(array(\n 'fields' => 'ids',\n 'post_type' => 'post',\n 'post_status' => 'publish',\n 'posts_per_page' => -1,\n 'tag' => array($tags)\n));\n$unique = array_unique( array_merge( $q1, $q2 ) );\n\n$posts = get_posts(array(\n 'post_type' => 'post',\n 'post__in' => $unique,\n 'posts_per_page' => -1\n));\n if ($posts ) : \n\nforeach( $posts as $post ) :\n//show results\nendforeach;\nendif;\n\n</code></pre>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325672",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13679/"
] | I have created a search using WP\_Query, it seems like this query is looking for the queried term in title AND tags.
Is there a way to have this search the title OR tags?
```
$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));
$paged = $request['page'];
$posts_per_page = $request['per_page'];
$result = new WP_Query([
'post_type' => 'post',
'category__in' => 3060,
'posts_per_page' => $posts_per_page,
'paged' => $page,
'orderby' => 'date',
'order' => 'desc',
's' => $s,
'tag' => array($tags)
]);
``` | Please use below code to show posts in texonomy and titles
```
$s = $request['s'];
$tags = str_replace(' ', '-', strtolower($request['s']));
$q1 = get_posts(array(
'fields' => 'id',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
's' => $s
));
$q2 = get_posts(array(
'fields' => 'ids',
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => -1,
'tag' => array($tags)
));
$unique = array_unique( array_merge( $q1, $q2 ) );
$posts = get_posts(array(
'post_type' => 'post',
'post__in' => $unique,
'posts_per_page' => -1
));
if ($posts ) :
foreach( $posts as $post ) :
//show results
endforeach;
endif;
``` |
325,690 | <p>When I try to save my site in the Gutenberg Editor it just says "Updating failed".</p>
<p>How to fix that?</p>
| [
{
"answer_id": 325691,
"author": "Noah Krasser",
"author_id": 159080,
"author_profile": "https://wordpress.stackexchange.com/users/159080",
"pm_score": 1,
"selected": false,
"text": "<p>There are many reasons this error can occur. Those two were the most frequent for me:</p>\n\n<h2>Session-Cookie</h2>\n\n<p>Open the Javascript Console by pressing F12 and click on the tab \"Console\". If you see some error message that goes something like <code>cookie_nonce</code> it's a session cookie problem.</p>\n\n<p>The problem solves by just completely logging out and possibly also deleting all cookies of your website.</p>\n\n<h2>File-Permissions</h2>\n\n<p>If you have a webserver you manage on your own it may be that file permissions are wrong.</p>\n\n<p>The <a href=\"https://askubuntu.com/questions/46331/how-to-avoid-using-sudo-when-working-in-var-www\">instructions here</a> have never failed to resolve my issues so far, so it's worth checking out.</p>\n\n<p>It's those commands:</p>\n\n<p>Add yourself to www-data group:</p>\n\n<pre><code>sudo gpasswd -a \"$USER\" www-data\n</code></pre>\n\n<p>Change file permissions:</p>\n\n<pre><code>sudo chown -R \"$USER\":www-data /var/www\nfind /var/www -type f -exec chmod 0660 {} \\;\nsudo find /var/www -type d -exec chmod 2770 {} \\;\n</code></pre>\n"
},
{
"answer_id": 348478,
"author": "Altin",
"author_id": 175291,
"author_profile": "https://wordpress.stackexchange.com/users/175291",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same exact issue with a client site with GoDaddy. Clearing browser and site cache or disabling plugins wouldn't work either. \nThe only workaround was to <code>login and work from an incognito window</code>. \nIn a normal Chrome window it only seemed to work like 1 in 10 times. </p>\n\n<p><strong>In incognito it works normally without any issue.</strong> </p>\n\n<p>So I'm assuming there should be something going on with browser configurations or extensions. Not a definite solution but I'm just putting this workaround here for anybody else pulling their hair because of this problem.</p>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325690",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159080/"
] | When I try to save my site in the Gutenberg Editor it just says "Updating failed".
How to fix that? | There are many reasons this error can occur. Those two were the most frequent for me:
Session-Cookie
--------------
Open the Javascript Console by pressing F12 and click on the tab "Console". If you see some error message that goes something like `cookie_nonce` it's a session cookie problem.
The problem solves by just completely logging out and possibly also deleting all cookies of your website.
File-Permissions
----------------
If you have a webserver you manage on your own it may be that file permissions are wrong.
The [instructions here](https://askubuntu.com/questions/46331/how-to-avoid-using-sudo-when-working-in-var-www) have never failed to resolve my issues so far, so it's worth checking out.
It's those commands:
Add yourself to www-data group:
```
sudo gpasswd -a "$USER" www-data
```
Change file permissions:
```
sudo chown -R "$USER":www-data /var/www
find /var/www -type f -exec chmod 0660 {} \;
sudo find /var/www -type d -exec chmod 2770 {} \;
``` |
325,717 | <p>I am new to wordpress and I just install version 5.0.3and I installed Consult theme.</p>
<p>At the button of page,I am getting this message:</p>
<pre><code>The-Consult By Themeruler.
</code></pre>
<p>How can I remove it from the pages?</p>
| [
{
"answer_id": 325794,
"author": "Loren Rosen",
"author_id": 158993,
"author_profile": "https://wordpress.stackexchange.com/users/158993",
"pm_score": 1,
"selected": false,
"text": "<p>There probably isn't a simple button you can push (unless there's a special one the theme developer created), but it can most likely be done via some basic theme tweaking.</p>\n\n<p>First, make a child theme. There are lots of tutorials about how to do that.</p>\n\n<p>Second, modify the child theme. Two options for this: </p>\n\n<ul>\n<li>hide the message via CSS: Find the CSS class for some enclosing HTML tag (there are several ways to determine that), and hide it via a CSS <code>display:none</code>. One drawback is that there's a risk Google might be unhappy with the page hiding things.</li>\n<li>customize the footer: Copy <code>footer.php</code> from the parent theme to the child theme. Edit the copy and remove the text you don't want, plus perhaps any enclosing now-empty HTML tags. One drawback is that if you later install an updated version of the parent theme, the child theme will still be using a modified version of the old footer.</li>\n</ul>\n\n<p>Also, the generic WordPress themes have a similar footer message, which many people want to remove. So a web search for 'remove proudly powered by WordPress' should find lots of tutorials. Your situation is probably almost the same.</p>\n"
},
{
"answer_id": 325795,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": -1,
"selected": false,
"text": "<p>There are a million ways to do this but this is the easiest.</p>\n\n<p>In the admin, go to Appearance > Custimize > Additional CSS and add the following CSS, then hit publish.</p>\n\n<pre><code>.footer_btm_left {display: none;}\n</code></pre>\n\n<p>Refresh your site and that text should be gone.</p>\n\n<p>Note: This will remove the text but leave the black box empty. If you want to remove the entire black box add the following CSS.</p>\n\n<pre><code>.site-info {display: none;}\n</code></pre>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325717",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159103/"
] | I am new to wordpress and I just install version 5.0.3and I installed Consult theme.
At the button of page,I am getting this message:
```
The-Consult By Themeruler.
```
How can I remove it from the pages? | There probably isn't a simple button you can push (unless there's a special one the theme developer created), but it can most likely be done via some basic theme tweaking.
First, make a child theme. There are lots of tutorials about how to do that.
Second, modify the child theme. Two options for this:
* hide the message via CSS: Find the CSS class for some enclosing HTML tag (there are several ways to determine that), and hide it via a CSS `display:none`. One drawback is that there's a risk Google might be unhappy with the page hiding things.
* customize the footer: Copy `footer.php` from the parent theme to the child theme. Edit the copy and remove the text you don't want, plus perhaps any enclosing now-empty HTML tags. One drawback is that if you later install an updated version of the parent theme, the child theme will still be using a modified version of the old footer.
Also, the generic WordPress themes have a similar footer message, which many people want to remove. So a web search for 'remove proudly powered by WordPress' should find lots of tutorials. Your situation is probably almost the same. |
325,720 | <p>I tried everything I found online. The backend appears, including dynamic segments (withSelect, etc). But the simplest 'render-callback' doesn't appear on the frontend.</p>
<p>plugin.php
<pre><code>/**
* Plugin Name: My Dynamic Block
*/
function my_plugin_render_dynamic_block( ) {
return '<h1>Sample Block</h1>';
}
function register_dynamic_block() {
wp_register_script(
'dynamic-block',
plugins_url( '/dist/block.js ', __FILE__),
array( 'wp-blocks', 'wp-element', 'wp-editor' ),
filemtime( plugin_dir_path( __FILE__ ) . 'dist/block.js' )
);
register_block_type(
'my-plugin/dynamic-block',
[
'editor_script' => 'dynamic-block',
'render_callback' => 'my_plugin_render_dynamic_block',
]
);
}
add_action('init', 'register_dynamic_block');
</code></pre>
<p>block.js</p>
<pre><code>const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'my-plugin/dynamic-block', {
title: 'My Dynamic Block',
icon: 'megaphone',
category: 'widgets',
edit({attributes}) {
return (
<div>Content</div>
);
},
save() {
return null;
},
} );
</code></pre>
| [
{
"answer_id": 326236,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": -1,
"selected": false,
"text": "<p>Even if you do manage to render frontend with null return, On the next page reload you'll get block validation error. Because your html structure on edit function will not be matching up with save function. So</p>\n\n<p>Instead of</p>\n\n<pre><code> save() {\n return null;\n },\n</code></pre>\n\n<p>Try </p>\n\n<pre><code> save() {\n return (\n <div>Content</div>\n );\n },\n</code></pre>\n\n<p>I hope this helps.</p>\n"
},
{
"answer_id": 346204,
"author": "Jay",
"author_id": 168861,
"author_profile": "https://wordpress.stackexchange.com/users/168861",
"pm_score": -1,
"selected": false,
"text": "<p>Since you're making a dynamic block you don't need to register the block in JavaScript. Take a look at the Latest Posts block in Core to see how they do it. </p>\n"
}
] | 2019/01/15 | [
"https://wordpress.stackexchange.com/questions/325720",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158827/"
] | I tried everything I found online. The backend appears, including dynamic segments (withSelect, etc). But the simplest 'render-callback' doesn't appear on the frontend.
plugin.php
```
/**
* Plugin Name: My Dynamic Block
*/
function my_plugin_render_dynamic_block( ) {
return '<h1>Sample Block</h1>';
}
function register_dynamic_block() {
wp_register_script(
'dynamic-block',
plugins_url( '/dist/block.js ', __FILE__),
array( 'wp-blocks', 'wp-element', 'wp-editor' ),
filemtime( plugin_dir_path( __FILE__ ) . 'dist/block.js' )
);
register_block_type(
'my-plugin/dynamic-block',
[
'editor_script' => 'dynamic-block',
'render_callback' => 'my_plugin_render_dynamic_block',
]
);
}
add_action('init', 'register_dynamic_block');
```
block.js
```
const { __ } = wp.i18n;
const { registerBlockType } = wp.blocks;
registerBlockType( 'my-plugin/dynamic-block', {
title: 'My Dynamic Block',
icon: 'megaphone',
category: 'widgets',
edit({attributes}) {
return (
<div>Content</div>
);
},
save() {
return null;
},
} );
``` | Even if you do manage to render frontend with null return, On the next page reload you'll get block validation error. Because your html structure on edit function will not be matching up with save function. So
Instead of
```
save() {
return null;
},
```
Try
```
save() {
return (
<div>Content</div>
);
},
```
I hope this helps. |
325,724 | <p>With WP 5.0 you can now enable full width blocks in the editor by adding this to your theme:
<code>add_theme_support( 'align-wide' );</code></p>
<p>However, if you are using a custom theme you have to add <em>your own</em> CSS to make that work, as discussed in this <a href="https://github.com/WordPress/gutenberg/issues/8289" rel="nofollow noreferrer">Gutenberg issue</a>. There are lots of examples out there that do work, but there are scrollbar issues with all of them for anyone not on a Mac.</p>
<p>The problem is if you use <code>width: 100vw</code>, which is the best way I've found to do this, on Windows devices you get a horizontal scroll bar as soon as you have a vertical scroll bar on the page. I understand this is actually per the viewport width spec, so I'm really hoping to find another way to actually make this work on <strong>all</strong> devices.</p>
<p>What I have right now to enable full width is this CSS:</p>
<pre><code>.entry-content .alignfull {
position: relative;
width: 100vw;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-right: -50vw;
}
body .entry-content .alignfull > * {
width: 100vw;
max-width: none;
}
</code></pre>
<p>I then add an <code>overflow: hidden;</code> on my outside container <code><div></code> of whatever wraps <code>the_content()</code> so as to hide the scrollbar. But what I'm looking for is a solution that doesn't rely on overflow hidden which can cause all kinds of unintended consequences. Any ideas out there?</p>
| [
{
"answer_id": 327701,
"author": "NickFMC",
"author_id": 56566,
"author_profile": "https://wordpress.stackexchange.com/users/56566",
"pm_score": 3,
"selected": true,
"text": "<p>After banging my head over that horizontal scroll bar issue, I think going the other way and adding a max width to blocks without the alignfull classes. If you just remove your page templates wrapper and assume it as 100%. Here is a pen with the WP markup as closely emulated as I could <a href=\"https://codepen.io/nickfmc/pen/vvbWQa\" rel=\"nofollow noreferrer\">https://codepen.io/nickfmc/pen/vvbWQa</a></p>\n\n<pre><code>.editor-content > *:not(.alignfull) {\n width: 100%;\n max-width: 1200px;\n margin-left: auto;\n margin-right: auto;\n}\n\n.editor-content > *:not(.alignfull).alignwide {\n max-width: 1400px;\n}\n</code></pre>\n"
},
{
"answer_id": 368824,
"author": "Trevor",
"author_id": 17461,
"author_profile": "https://wordpress.stackexchange.com/users/17461",
"pm_score": 0,
"selected": false,
"text": "<p>Actually this can be solved with just a few simple lines, and it has far fewer unintended consequences than anything else I've seen or tried. This is basically what the TwentyTwenty theme is doing, though they do include an <code>overflow: hidden</code> -- but that's not necessary to prevent the horizontal scrollbar.</p>\n\n<pre><code>.entry-content .fullwidth {\n max-width: 100vw;\n position: relative;\n width: 100%; \n}\n</code></pre>\n\n<p>Problem solved with no horizontal scrollbar in Windows.</p>\n"
}
] | 2019/01/16 | [
"https://wordpress.stackexchange.com/questions/325724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17461/"
] | With WP 5.0 you can now enable full width blocks in the editor by adding this to your theme:
`add_theme_support( 'align-wide' );`
However, if you are using a custom theme you have to add *your own* CSS to make that work, as discussed in this [Gutenberg issue](https://github.com/WordPress/gutenberg/issues/8289). There are lots of examples out there that do work, but there are scrollbar issues with all of them for anyone not on a Mac.
The problem is if you use `width: 100vw`, which is the best way I've found to do this, on Windows devices you get a horizontal scroll bar as soon as you have a vertical scroll bar on the page. I understand this is actually per the viewport width spec, so I'm really hoping to find another way to actually make this work on **all** devices.
What I have right now to enable full width is this CSS:
```
.entry-content .alignfull {
position: relative;
width: 100vw;
left: 50%;
right: 50%;
margin-left: -50vw;
margin-right: -50vw;
}
body .entry-content .alignfull > * {
width: 100vw;
max-width: none;
}
```
I then add an `overflow: hidden;` on my outside container `<div>` of whatever wraps `the_content()` so as to hide the scrollbar. But what I'm looking for is a solution that doesn't rely on overflow hidden which can cause all kinds of unintended consequences. Any ideas out there? | After banging my head over that horizontal scroll bar issue, I think going the other way and adding a max width to blocks without the alignfull classes. If you just remove your page templates wrapper and assume it as 100%. Here is a pen with the WP markup as closely emulated as I could <https://codepen.io/nickfmc/pen/vvbWQa>
```
.editor-content > *:not(.alignfull) {
width: 100%;
max-width: 1200px;
margin-left: auto;
margin-right: auto;
}
.editor-content > *:not(.alignfull).alignwide {
max-width: 1400px;
}
``` |
325,803 | <p>I've been working on a wordpress site (geniedrinks.co.uk) using the Jevelin theme. Last night, I deactivated a plugin called WP Bakery Page Builder (js_composer) which immediately resulted in HTTP error 500 across all pages - I can't even access my wp-admin page. </p>
<p>I have a feeling reactivating the plugin might correct the issue, but can't find a way to do so from within the control panel (server host is names.co.uk). I've looked for an options tab within PHPMyAdmin to try and find a list of active plugins (to add the plugin manually to the list), but can't locate said tab. Any help or alternative solutions gratefully received. </p>
<p>Many thanks in advance,</p>
<p>Nic</p>
| [
{
"answer_id": 325808,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 3,
"selected": true,
"text": "<p>You can do this by editing the database via PhpMyAdmin.</p>\n\n<p>Go to your database's <strong>Options table</strong> and find a row called <strong>active_plugins</strong>.</p>\n\n<p>You should see something like this...</p>\n\n<pre><code>a:10:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n}\n</code></pre>\n\n<p>You can add a new row for your plugin. You will need to know the following.</p>\n\n<ul>\n<li>a:10 : 10 = the count of row (how many plugins are in the list)</li>\n<li>i:0;s:49 : i = the item position in the list</li>\n<li>i:0;s:49 : s = the character count</li>\n</ul>\n\n<p>So you you can activate a new plugin by adding a new row and change the values like this...</p>\n\n<pre><code>a:11:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n i:10;s:20:\"my-plugin/plugin.php\";\n}\n</code></pre>\n"
},
{
"answer_id": 325811,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>You can deactivate all other plugins by renaming the plugin directory to a temporary name. Also try to deactivate the current theme by renaming its directory so Wordpress falls back to the default theme. </p>\n\n<p>After you login to the dashboard, rename the directories again to their original then activate the plugins one by one.</p>\n\n<p>Later if you want to troubleshoot issues, use <a href=\"https://wordpress.org/plugins/health-check/\" rel=\"nofollow noreferrer\">Health Check plugin</a> to help you detect if any plugin or theme has bugs without the need to actually deactivate or activate it which may break your site. It's very helpful for debugging and troubleshooting.</p>\n"
}
] | 2019/01/16 | [
"https://wordpress.stackexchange.com/questions/325803",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159173/"
] | I've been working on a wordpress site (geniedrinks.co.uk) using the Jevelin theme. Last night, I deactivated a plugin called WP Bakery Page Builder (js\_composer) which immediately resulted in HTTP error 500 across all pages - I can't even access my wp-admin page.
I have a feeling reactivating the plugin might correct the issue, but can't find a way to do so from within the control panel (server host is names.co.uk). I've looked for an options tab within PHPMyAdmin to try and find a list of active plugins (to add the plugin manually to the list), but can't locate said tab. Any help or alternative solutions gratefully received.
Many thanks in advance,
Nic | You can do this by editing the database via PhpMyAdmin.
Go to your database's **Options table** and find a row called **active\_plugins**.
You should see something like this...
```
a:10:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
}
```
You can add a new row for your plugin. You will need to know the following.
* a:10 : 10 = the count of row (how many plugins are in the list)
* i:0;s:49 : i = the item position in the list
* i:0;s:49 : s = the character count
So you you can activate a new plugin by adding a new row and change the values like this...
```
a:11:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
i:10;s:20:"my-plugin/plugin.php";
}
``` |
325,849 | <p>On a site that has many different image sizes each time an image is uploaded all the different thumbnail sizes are created causing a fair bit of bloat.
What would be the best way of optimising this process?</p>
<p>With a custom post type of <strong>‘product’</strong>, where the different product type images have slightly different aspect orientations, should (the plugin) register all the possible image sizes? e.g.</p>
<pre><code>add_image_size('small-A', 45, 67, array('center', 'center'));
add_image_size('small-B', 35, 49, array('center', 'center'));
add_image_size('small-C', 42, 65, array('center', 'center'));
add_image_size('small-D', 50, 50, array('center', 'center'));...
</code></pre>
<p>But assuming when the plugin creates a product A, and the front end will never use the other formats for that size; should one only register the necessary sizes for ‘A’ format before running <code>media_handle_upload()</code>, would that affect the front end?</p>
<p>Or, run <code>remove_image_size()</code> on all the unnecessary image sizes just before <code>media_handle_upload()</code>?</p>
<p>Or, is there a different / best-practice approach?</p>
<p>Obviously, impact on performance, scalability and especially impact on storage are of some concern.</p>
<p>Thanks in advance.</p>
<p>(PS. one could conceivably just generate a standard image size and place the appropriately sized image inside that with PHP, but that seems a bit like cheating and possibly creating scaling problems down the road)</p>
| [
{
"answer_id": 325808,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 3,
"selected": true,
"text": "<p>You can do this by editing the database via PhpMyAdmin.</p>\n\n<p>Go to your database's <strong>Options table</strong> and find a row called <strong>active_plugins</strong>.</p>\n\n<p>You should see something like this...</p>\n\n<pre><code>a:10:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n}\n</code></pre>\n\n<p>You can add a new row for your plugin. You will need to know the following.</p>\n\n<ul>\n<li>a:10 : 10 = the count of row (how many plugins are in the list)</li>\n<li>i:0;s:49 : i = the item position in the list</li>\n<li>i:0;s:49 : s = the character count</li>\n</ul>\n\n<p>So you you can activate a new plugin by adding a new row and change the values like this...</p>\n\n<pre><code>a:11:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n i:10;s:20:\"my-plugin/plugin.php\";\n}\n</code></pre>\n"
},
{
"answer_id": 325811,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>You can deactivate all other plugins by renaming the plugin directory to a temporary name. Also try to deactivate the current theme by renaming its directory so Wordpress falls back to the default theme. </p>\n\n<p>After you login to the dashboard, rename the directories again to their original then activate the plugins one by one.</p>\n\n<p>Later if you want to troubleshoot issues, use <a href=\"https://wordpress.org/plugins/health-check/\" rel=\"nofollow noreferrer\">Health Check plugin</a> to help you detect if any plugin or theme has bugs without the need to actually deactivate or activate it which may break your site. It's very helpful for debugging and troubleshooting.</p>\n"
}
] | 2019/01/17 | [
"https://wordpress.stackexchange.com/questions/325849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/137417/"
] | On a site that has many different image sizes each time an image is uploaded all the different thumbnail sizes are created causing a fair bit of bloat.
What would be the best way of optimising this process?
With a custom post type of **‘product’**, where the different product type images have slightly different aspect orientations, should (the plugin) register all the possible image sizes? e.g.
```
add_image_size('small-A', 45, 67, array('center', 'center'));
add_image_size('small-B', 35, 49, array('center', 'center'));
add_image_size('small-C', 42, 65, array('center', 'center'));
add_image_size('small-D', 50, 50, array('center', 'center'));...
```
But assuming when the plugin creates a product A, and the front end will never use the other formats for that size; should one only register the necessary sizes for ‘A’ format before running `media_handle_upload()`, would that affect the front end?
Or, run `remove_image_size()` on all the unnecessary image sizes just before `media_handle_upload()`?
Or, is there a different / best-practice approach?
Obviously, impact on performance, scalability and especially impact on storage are of some concern.
Thanks in advance.
(PS. one could conceivably just generate a standard image size and place the appropriately sized image inside that with PHP, but that seems a bit like cheating and possibly creating scaling problems down the road) | You can do this by editing the database via PhpMyAdmin.
Go to your database's **Options table** and find a row called **active\_plugins**.
You should see something like this...
```
a:10:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
}
```
You can add a new row for your plugin. You will need to know the following.
* a:10 : 10 = the count of row (how many plugins are in the list)
* i:0;s:49 : i = the item position in the list
* i:0;s:49 : s = the character count
So you you can activate a new plugin by adding a new row and change the values like this...
```
a:11:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
i:10;s:20:"my-plugin/plugin.php";
}
``` |
325,855 | <p><strong>EDIT</strong> <em>the title of this question was "Does anyone know if Jetpack is caching pages/content" but has been changed following the thread.</em></p>
<p>I just updated a plugin I made.
Among others, it does filter the content of a page using <code>the_content</code> hook.</p>
<p>But I noticed that it does not behaves like it should once I pushed the changes online (some parts of my content are missing).</p>
<p>Once I do disable Jetpack, it works as expected.</p>
<p>Does anyone know if Jetpack is caching pages/content and how to clear that cache ?</p>
<p>I didn't find anything about it online.</p>
<p>Thanks ! </p>
| [
{
"answer_id": 325808,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 3,
"selected": true,
"text": "<p>You can do this by editing the database via PhpMyAdmin.</p>\n\n<p>Go to your database's <strong>Options table</strong> and find a row called <strong>active_plugins</strong>.</p>\n\n<p>You should see something like this...</p>\n\n<pre><code>a:10:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n}\n</code></pre>\n\n<p>You can add a new row for your plugin. You will need to know the following.</p>\n\n<ul>\n<li>a:10 : 10 = the count of row (how many plugins are in the list)</li>\n<li>i:0;s:49 : i = the item position in the list</li>\n<li>i:0;s:49 : s = the character count</li>\n</ul>\n\n<p>So you you can activate a new plugin by adding a new row and change the values like this...</p>\n\n<pre><code>a:11:{\n i:0;s:49:\"1and1-wordpress-wizard/1and1-wordpress-wizard.php\";\n i:1;s:29:\"acf-repeater/acf-repeater.php\";\n i:2;s:30:\"advanced-custom-fields/acf.php\";\n i:3;s:45:\"limit-login-attempts/limit-login-attempts.php\";\n i:4;s:27:\"redirection/redirection.php\";\n i:6;s:33:\"w3-total-cache/w3-total-cache.php\";\n i:7;s:41:\"wordpress-importer/wordpress-importer.php\";\n i:8;s:24:\"wordpress-seo/wp-seo.php\";\n i:9;s:34:\"wpml-string-translation/plugin.php\";\n i:10;s:20:\"my-plugin/plugin.php\";\n}\n</code></pre>\n"
},
{
"answer_id": 325811,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>You can deactivate all other plugins by renaming the plugin directory to a temporary name. Also try to deactivate the current theme by renaming its directory so Wordpress falls back to the default theme. </p>\n\n<p>After you login to the dashboard, rename the directories again to their original then activate the plugins one by one.</p>\n\n<p>Later if you want to troubleshoot issues, use <a href=\"https://wordpress.org/plugins/health-check/\" rel=\"nofollow noreferrer\">Health Check plugin</a> to help you detect if any plugin or theme has bugs without the need to actually deactivate or activate it which may break your site. It's very helpful for debugging and troubleshooting.</p>\n"
}
] | 2019/01/17 | [
"https://wordpress.stackexchange.com/questions/325855",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70449/"
] | **EDIT** *the title of this question was "Does anyone know if Jetpack is caching pages/content" but has been changed following the thread.*
I just updated a plugin I made.
Among others, it does filter the content of a page using `the_content` hook.
But I noticed that it does not behaves like it should once I pushed the changes online (some parts of my content are missing).
Once I do disable Jetpack, it works as expected.
Does anyone know if Jetpack is caching pages/content and how to clear that cache ?
I didn't find anything about it online.
Thanks ! | You can do this by editing the database via PhpMyAdmin.
Go to your database's **Options table** and find a row called **active\_plugins**.
You should see something like this...
```
a:10:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
}
```
You can add a new row for your plugin. You will need to know the following.
* a:10 : 10 = the count of row (how many plugins are in the list)
* i:0;s:49 : i = the item position in the list
* i:0;s:49 : s = the character count
So you you can activate a new plugin by adding a new row and change the values like this...
```
a:11:{
i:0;s:49:"1and1-wordpress-wizard/1and1-wordpress-wizard.php";
i:1;s:29:"acf-repeater/acf-repeater.php";
i:2;s:30:"advanced-custom-fields/acf.php";
i:3;s:45:"limit-login-attempts/limit-login-attempts.php";
i:4;s:27:"redirection/redirection.php";
i:6;s:33:"w3-total-cache/w3-total-cache.php";
i:7;s:41:"wordpress-importer/wordpress-importer.php";
i:8;s:24:"wordpress-seo/wp-seo.php";
i:9;s:34:"wpml-string-translation/plugin.php";
i:10;s:20:"my-plugin/plugin.php";
}
``` |
325,871 | <p>Hi I used the Edin theme to build a wordpress website. I modified a big part of the CSS at the CSS editor, without having a clue what a child theme is. What should I do now? Create a child theme and delete the additional CSS of the parent theme? Any ideas?</p>
<p>Thank you very much!! </p>
| [
{
"answer_id": 325872,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": -1,
"selected": false,
"text": "<p>If you've changed the original theme files, create a child theme and move your changes to the new style.css of the child. If you don't remember what your changes were, just copy the modified style.css from parent to child and reinstall the parent theme.</p>\n\n<p>If you just added the CSS in the customizer then you don't have to do anything since the changes will remain even if the theme is update. </p>\n"
},
{
"answer_id": 325894,
"author": "rsigg",
"author_id": 8052,
"author_profile": "https://wordpress.stackexchange.com/users/8052",
"pm_score": 0,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/39152/jacob-peattie\">Jacob Peattie</a> mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the <em>only</em> place you can make changes that will persist through a theme update or change. All other customizations get wiped. \nSo if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this.</p>\n\n<p>First create a new folder/directory in <code>wp-content/themes/</code></p>\n\n<p>You need to add two files to this directory: <code>style.css</code> and <code>functions.php</code>\nIn the <code>style.css</code> file add the following information:</p>\n\n<pre><code>/*\n Theme Name: Edin Child\n Template: edin\n*/\n</code></pre>\n\n<p>Those are the only two required things in this file. Note that I have assumed that the \"Template\" is \"edin\"; make sure this is actually the parent theme directory name. <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#2-create-a-stylesheet-style-css\" rel=\"nofollow noreferrer\">More info.</a></p>\n\n<p>Next is the <code>functions.php</code> file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info.</p>\n\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\nfunction my_theme_enqueue_styles() {\n\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); // get_template_directory_uri() returns the URI of the current parent theme, set in \"Template\" in your style.css\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()->get('Version')\n ); // get_stylesheet_directory_uri() returns the child theme URI\n}\n?>\n</code></pre>\n\n<p>Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to <code>/wp-content/</code>, no zipping required), and finally activate the child theme. <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet\" rel=\"nofollow noreferrer\">More info.</a></p>\n\n<p>You can find more about creating child themes directly from the <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">WordPress theme development docs.</a></p>\n"
}
] | 2019/01/17 | [
"https://wordpress.stackexchange.com/questions/325871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159229/"
] | Hi I used the Edin theme to build a wordpress website. I modified a big part of the CSS at the CSS editor, without having a clue what a child theme is. What should I do now? Create a child theme and delete the additional CSS of the parent theme? Any ideas?
Thank you very much!! | As [Jacob Peattie](https://wordpress.stackexchange.com/users/39152/jacob-peattie) mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the *only* place you can make changes that will persist through a theme update or change. All other customizations get wiped.
So if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this.
First create a new folder/directory in `wp-content/themes/`
You need to add two files to this directory: `style.css` and `functions.php`
In the `style.css` file add the following information:
```
/*
Theme Name: Edin Child
Template: edin
*/
```
Those are the only two required things in this file. Note that I have assumed that the "Template" is "edin"; make sure this is actually the parent theme directory name. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#2-create-a-stylesheet-style-css)
Next is the `functions.php` file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info.
```
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); // get_template_directory_uri() returns the URI of the current parent theme, set in "Template" in your style.css
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
); // get_stylesheet_directory_uri() returns the child theme URI
}
?>
```
Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to `/wp-content/`, no zipping required), and finally activate the child theme. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet)
You can find more about creating child themes directly from the [WordPress theme development docs.](https://developer.wordpress.org/themes/advanced-topics/child-themes/) |
325,873 | <p>I created a field to enter whatsapp number in the front of a site in wordpress, since the back is simple, but I need to change it from the front section for the users
<a href="https://i.stack.imgur.com/7sGZZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/7sGZZ.png" alt="enter image description here"></a></p>
<p>I have already placed an input where I show the user's information, the other fields already come by default in the subject.</p>
<pre><code><div class="form-group">
<div class="stm-label h4"><?php esc_html_e('Whatsapp', 'motors'); ?></div>
<?php $author_id = get_the_author_meta('ID');
$author_badge = get_field('n_whatsapp', 'user_'. $author_id );
?>
<input class="form-control" type="text" name="stm_phone"
value="<?php echo esc_attr($author_badge); ?>"
placeholder="<?php esc_html_e('Incluir whatsapp', 'motors'); ?>"/>
</div>
<input type="text" id="id_whatsapp" name="acf[n_whatsapp]" value="acf[n_whatsapp]">
<?php acf_form(); ?>
</div>
</div>
</code></pre>
| [
{
"answer_id": 325872,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": -1,
"selected": false,
"text": "<p>If you've changed the original theme files, create a child theme and move your changes to the new style.css of the child. If you don't remember what your changes were, just copy the modified style.css from parent to child and reinstall the parent theme.</p>\n\n<p>If you just added the CSS in the customizer then you don't have to do anything since the changes will remain even if the theme is update. </p>\n"
},
{
"answer_id": 325894,
"author": "rsigg",
"author_id": 8052,
"author_profile": "https://wordpress.stackexchange.com/users/8052",
"pm_score": 0,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/39152/jacob-peattie\">Jacob Peattie</a> mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the <em>only</em> place you can make changes that will persist through a theme update or change. All other customizations get wiped. \nSo if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this.</p>\n\n<p>First create a new folder/directory in <code>wp-content/themes/</code></p>\n\n<p>You need to add two files to this directory: <code>style.css</code> and <code>functions.php</code>\nIn the <code>style.css</code> file add the following information:</p>\n\n<pre><code>/*\n Theme Name: Edin Child\n Template: edin\n*/\n</code></pre>\n\n<p>Those are the only two required things in this file. Note that I have assumed that the \"Template\" is \"edin\"; make sure this is actually the parent theme directory name. <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#2-create-a-stylesheet-style-css\" rel=\"nofollow noreferrer\">More info.</a></p>\n\n<p>Next is the <code>functions.php</code> file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info.</p>\n\n<pre><code><?php\nadd_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );\nfunction my_theme_enqueue_styles() {\n\n wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); // get_template_directory_uri() returns the URI of the current parent theme, set in \"Template\" in your style.css\n wp_enqueue_style( 'child-style',\n get_stylesheet_directory_uri() . '/style.css',\n array( $parent_style ),\n wp_get_theme()->get('Version')\n ); // get_stylesheet_directory_uri() returns the child theme URI\n}\n?>\n</code></pre>\n\n<p>Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to <code>/wp-content/</code>, no zipping required), and finally activate the child theme. <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet\" rel=\"nofollow noreferrer\">More info.</a></p>\n\n<p>You can find more about creating child themes directly from the <a href=\"https://developer.wordpress.org/themes/advanced-topics/child-themes/\" rel=\"nofollow noreferrer\">WordPress theme development docs.</a></p>\n"
}
] | 2019/01/17 | [
"https://wordpress.stackexchange.com/questions/325873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/129154/"
] | I created a field to enter whatsapp number in the front of a site in wordpress, since the back is simple, but I need to change it from the front section for the users
[](https://i.stack.imgur.com/7sGZZ.png)
I have already placed an input where I show the user's information, the other fields already come by default in the subject.
```
<div class="form-group">
<div class="stm-label h4"><?php esc_html_e('Whatsapp', 'motors'); ?></div>
<?php $author_id = get_the_author_meta('ID');
$author_badge = get_field('n_whatsapp', 'user_'. $author_id );
?>
<input class="form-control" type="text" name="stm_phone"
value="<?php echo esc_attr($author_badge); ?>"
placeholder="<?php esc_html_e('Incluir whatsapp', 'motors'); ?>"/>
</div>
<input type="text" id="id_whatsapp" name="acf[n_whatsapp]" value="acf[n_whatsapp]">
<?php acf_form(); ?>
</div>
</div>
``` | As [Jacob Peattie](https://wordpress.stackexchange.com/users/39152/jacob-peattie) mentioned, you've made custom CSS changes in a way that does not impact your theme. To expand a bit more, this is the *only* place you can make changes that will persist through a theme update or change. All other customizations get wiped.
So if you find you want to make further changes, you can create a child theme. You'll need access to the server/file system for this.
First create a new folder/directory in `wp-content/themes/`
You need to add two files to this directory: `style.css` and `functions.php`
In the `style.css` file add the following information:
```
/*
Theme Name: Edin Child
Template: edin
*/
```
Those are the only two required things in this file. Note that I have assumed that the "Template" is "edin"; make sure this is actually the parent theme directory name. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#2-create-a-stylesheet-style-css)
Next is the `functions.php` file, which is a little more involved. Here is where tell your child theme to import information from its parent as well as importing its own style info.
```
<?php
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
function my_theme_enqueue_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' ); // get_template_directory_uri() returns the URI of the current parent theme, set in "Template" in your style.css
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
); // get_stylesheet_directory_uri() returns the child theme URI
}
?>
```
Then you'll have to zip your child theme directory up and upload it via the WP admin (or upload via ftp to `/wp-content/`, no zipping required), and finally activate the child theme. [More info.](https://developer.wordpress.org/themes/advanced-topics/child-themes/#3-enqueue-stylesheet)
You can find more about creating child themes directly from the [WordPress theme development docs.](https://developer.wordpress.org/themes/advanced-topics/child-themes/) |
325,875 | <p>I've inherited a wordpress website I need to maintain. Despite having upgraded it to the latest version (5.03), and having changed the theme, there seems to be some customisations which survived. These seem to be CSS related, affecting the general page template, as well as a specific plug-in. I would like to remove these customisations. </p>
<p>I am not a wordrpess dev, any pointers as to where to look would be appreciated.</p>
| [
{
"answer_id": 325879,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": true,
"text": "<p>When you inspect elements on the affected pages, it should tell you which CSS file is enforcing the rule. If the file is somewhere inside <code>/wp-content/plugins/</code> then a plugin is adding them and you can either disable that plugin or see whether they have properly enqueued the CSS. If inside the plugin the style is added like this:</p>\n\n<p><code>wp_enqueue_style(...);</code></p>\n\n<p>and you need the plugin's functionality, just not the styles, you can create a child theme and inside its <code>functions.php</code> file add</p>\n\n<pre><code>add_action('wp_enqueue_scripts', 'wpse_325875_dequeue_plugin_css');\nfunction wpse_325875_dequeue_plugin_css() {\n wp_deregister_style(...);\n}\n</code></pre>\n\n<p>(replacing the ... with the same name the original plugin uses, so that it dequeues that particular file.)</p>\n\n<p>Another possibility is that the dev before you may have modified Core files, which would be somewhere inside <code>/wp-content/admin/</code> or <code>/wp-content/includes/</code>. Usually updating Core fixes this type of problem, but you can also manually download the .zip file from wordpress.org and overwrite your <code>wp-admin</code> and <code>wp-includes</code> folder. (Be careful not to overwrite <code>wp-content</code> as that contains all of your plugins as well as media uploads, like jpgs and pdfs.) That will ensure you're using non-modified Core files.</p>\n\n<p>As with any changes, make sure you have a complete backup of both files and database before making changes. :)</p>\n"
},
{
"answer_id": 325896,
"author": "rsigg",
"author_id": 8052,
"author_profile": "https://wordpress.stackexchange.com/users/8052",
"pm_score": -1,
"selected": false,
"text": "<p>It's hard to say more without seeing it, but you could also check in <code>Appearance > Customize > Additional CSS</code>. This is the only place you can make changes (within the WP Admin, that is) that will persist through a theme update or switch (note that these theme changes are saved per-theme and would only return when you switched back to that theme).</p>\n\n<p>Otherwise it would have to be a plugin or a core code change, as <a href=\"https://wordpress.stackexchange.com/users/102815/webelaine\">WebElaine</a> mentioned.</p>\n"
},
{
"answer_id": 325910,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 0,
"selected": false,
"text": "<p>You can verify by turning off all the plugins one by one. If issue is still present then you can comment the css file one by one from the functions.php. You can use the sign \"//\" double forward slash for commenting the php code.</p>\n"
}
] | 2019/01/17 | [
"https://wordpress.stackexchange.com/questions/325875",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68023/"
] | I've inherited a wordpress website I need to maintain. Despite having upgraded it to the latest version (5.03), and having changed the theme, there seems to be some customisations which survived. These seem to be CSS related, affecting the general page template, as well as a specific plug-in. I would like to remove these customisations.
I am not a wordrpess dev, any pointers as to where to look would be appreciated. | When you inspect elements on the affected pages, it should tell you which CSS file is enforcing the rule. If the file is somewhere inside `/wp-content/plugins/` then a plugin is adding them and you can either disable that plugin or see whether they have properly enqueued the CSS. If inside the plugin the style is added like this:
`wp_enqueue_style(...);`
and you need the plugin's functionality, just not the styles, you can create a child theme and inside its `functions.php` file add
```
add_action('wp_enqueue_scripts', 'wpse_325875_dequeue_plugin_css');
function wpse_325875_dequeue_plugin_css() {
wp_deregister_style(...);
}
```
(replacing the ... with the same name the original plugin uses, so that it dequeues that particular file.)
Another possibility is that the dev before you may have modified Core files, which would be somewhere inside `/wp-content/admin/` or `/wp-content/includes/`. Usually updating Core fixes this type of problem, but you can also manually download the .zip file from wordpress.org and overwrite your `wp-admin` and `wp-includes` folder. (Be careful not to overwrite `wp-content` as that contains all of your plugins as well as media uploads, like jpgs and pdfs.) That will ensure you're using non-modified Core files.
As with any changes, make sure you have a complete backup of both files and database before making changes. :) |
325,886 | <p>I import image to wordpress via <code>wp_insert_attachment</code>. </p>
<p>On frontend wordpress media library still don't know that image is imported. I need a way to update attachments in media library without refreshing page.</p>
<p>I found partial solution:</p>
<pre><code>wp.media.frame.on('open', function() {
if (wp.media.frame.content.get() !== null) {
wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
wp.media.frame.content.get().options.selection.reset();
} else {
wp.media.frame.library.props.set({ignore: (+ new Date())});
}
}, this);
</code></pre>
<p>Problem with this part of code is that now when I try to upload photo using Media Library uploader, image is uploaded correctly but it's not displayed. </p>
| [
{
"answer_id": 325890,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>This depends on how you use <code>wp_insert_attachment()</code>. Here is a full example copied from <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_attachment\" rel=\"nofollow noreferrer\">the codex</a>:</p>\n\n<pre><code>// $filename should be the path to a file in the upload directory.\n$filename = '/path/to/uploads/2013/03/filename.jpg';\n\n// The ID of the post this attachment is for.\n$parent_post_id = 37;\n\n// Check the type of file. We'll use this as the 'post_mime_type'.\n$filetype = wp_check_filetype( basename( $filename ), null );\n\n// Get the path to the upload directory.\n$wp_upload_dir = wp_upload_dir();\n\n// Prepare an array of post data for the attachment.\n$attachment = array(\n 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), \n 'post_mime_type' => $filetype['type'],\n 'post_title' => preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' => '',\n 'post_status' => 'inherit'\n);\n\n// Insert the attachment.\n$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );\n\n// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\nrequire_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n// Generate the metadata for the attachment, and update the database record.\n$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );\nwp_update_attachment_metadata( $attach_id, $attach_data );\n\n//If you want to set it as a thumbnail\nset_post_thumbnail( $parent_post_id, $attach_id );\n</code></pre>\n"
},
{
"answer_id": 325902,
"author": "z1ad",
"author_id": 121061,
"author_profile": "https://wordpress.stackexchange.com/users/121061",
"pm_score": 2,
"selected": true,
"text": "<p>edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset</p>\n\n<pre><code>wp.media.frame.on('open', function() {\n if (wp.media.frame.content.get() !== null) { \n // this forces a refresh of the content\n wp.media.frame.content.get().collection._requery(true);\n\n // optional: reset selection\n wp.media.frame.content.get().options.selection.reset();\n }\n}, this);\n</code></pre>\n"
}
] | 2019/01/17 | [
"https://wordpress.stackexchange.com/questions/325886",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107666/"
] | I import image to wordpress via `wp_insert_attachment`.
On frontend wordpress media library still don't know that image is imported. I need a way to update attachments in media library without refreshing page.
I found partial solution:
```
wp.media.frame.on('open', function() {
if (wp.media.frame.content.get() !== null) {
wp.media.frame.content.get().collection.props.set({ignore: (+ new Date())});
wp.media.frame.content.get().options.selection.reset();
} else {
wp.media.frame.library.props.set({ignore: (+ new Date())});
}
}, this);
```
Problem with this part of code is that now when I try to upload photo using Media Library uploader, image is uploaded correctly but it's not displayed. | edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset
```
wp.media.frame.on('open', function() {
if (wp.media.frame.content.get() !== null) {
// this forces a refresh of the content
wp.media.frame.content.get().collection._requery(true);
// optional: reset selection
wp.media.frame.content.get().options.selection.reset();
}
}, this);
``` |
325,937 | <p>I am in the process of rescuing the content from a WordPress site with a bloated/damaged database. Everything has gone according to plan except for the comments. I can see that the 4000+ comments are indeed in the database's <code>wp_comments</code> table, and I verified that the IDs of the associated posts are correct, but none of them show up in the WordPress admin area or the front-end. I haven't been able to find where the issue lies.</p>
<p>Maybe someone in the community has an idea for a possible fix? Thanks.</p>
<p>Edit: to clarify, I already moved the content to a new database, the issue happens on the new WordPress installation. The comments were imported to the database when importing the posts through the export/import tool.</p>
| [
{
"answer_id": 325890,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>This depends on how you use <code>wp_insert_attachment()</code>. Here is a full example copied from <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_attachment\" rel=\"nofollow noreferrer\">the codex</a>:</p>\n\n<pre><code>// $filename should be the path to a file in the upload directory.\n$filename = '/path/to/uploads/2013/03/filename.jpg';\n\n// The ID of the post this attachment is for.\n$parent_post_id = 37;\n\n// Check the type of file. We'll use this as the 'post_mime_type'.\n$filetype = wp_check_filetype( basename( $filename ), null );\n\n// Get the path to the upload directory.\n$wp_upload_dir = wp_upload_dir();\n\n// Prepare an array of post data for the attachment.\n$attachment = array(\n 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), \n 'post_mime_type' => $filetype['type'],\n 'post_title' => preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' => '',\n 'post_status' => 'inherit'\n);\n\n// Insert the attachment.\n$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );\n\n// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\nrequire_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n// Generate the metadata for the attachment, and update the database record.\n$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );\nwp_update_attachment_metadata( $attach_id, $attach_data );\n\n//If you want to set it as a thumbnail\nset_post_thumbnail( $parent_post_id, $attach_id );\n</code></pre>\n"
},
{
"answer_id": 325902,
"author": "z1ad",
"author_id": 121061,
"author_profile": "https://wordpress.stackexchange.com/users/121061",
"pm_score": 2,
"selected": true,
"text": "<p>edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset</p>\n\n<pre><code>wp.media.frame.on('open', function() {\n if (wp.media.frame.content.get() !== null) { \n // this forces a refresh of the content\n wp.media.frame.content.get().collection._requery(true);\n\n // optional: reset selection\n wp.media.frame.content.get().options.selection.reset();\n }\n}, this);\n</code></pre>\n"
}
] | 2019/01/18 | [
"https://wordpress.stackexchange.com/questions/325937",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159268/"
] | I am in the process of rescuing the content from a WordPress site with a bloated/damaged database. Everything has gone according to plan except for the comments. I can see that the 4000+ comments are indeed in the database's `wp_comments` table, and I verified that the IDs of the associated posts are correct, but none of them show up in the WordPress admin area or the front-end. I haven't been able to find where the issue lies.
Maybe someone in the community has an idea for a possible fix? Thanks.
Edit: to clarify, I already moved the content to a new database, the issue happens on the new WordPress installation. The comments were imported to the database when importing the posts through the export/import tool. | edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset
```
wp.media.frame.on('open', function() {
if (wp.media.frame.content.get() !== null) {
// this forces a refresh of the content
wp.media.frame.content.get().collection._requery(true);
// optional: reset selection
wp.media.frame.content.get().options.selection.reset();
}
}, this);
``` |
325,938 | <p>.htaccess:</p>
<pre><code><IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wp_test/
RewriteRule ^index\.php$ - [L]
RewriteRule ^the_image$ wp-content/uploads/2019/01/banner\.jpg [L]
RewriteRule ^the_page$ sample-page [L]
</IfModule>
</code></pre>
<p>When I go to <code>example.com/the_image</code> it shows the correct image. However, if I go to <code>example.com/the_page</code> it shows the page not found page.</p>
<p>Any work around on this?</p>
| [
{
"answer_id": 325890,
"author": "Nour Edin Al-Habal",
"author_id": 97257,
"author_profile": "https://wordpress.stackexchange.com/users/97257",
"pm_score": 0,
"selected": false,
"text": "<p>This depends on how you use <code>wp_insert_attachment()</code>. Here is a full example copied from <a href=\"https://codex.wordpress.org/Function_Reference/wp_insert_attachment\" rel=\"nofollow noreferrer\">the codex</a>:</p>\n\n<pre><code>// $filename should be the path to a file in the upload directory.\n$filename = '/path/to/uploads/2013/03/filename.jpg';\n\n// The ID of the post this attachment is for.\n$parent_post_id = 37;\n\n// Check the type of file. We'll use this as the 'post_mime_type'.\n$filetype = wp_check_filetype( basename( $filename ), null );\n\n// Get the path to the upload directory.\n$wp_upload_dir = wp_upload_dir();\n\n// Prepare an array of post data for the attachment.\n$attachment = array(\n 'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ), \n 'post_mime_type' => $filetype['type'],\n 'post_title' => preg_replace( '/\\.[^.]+$/', '', basename( $filename ) ),\n 'post_content' => '',\n 'post_status' => 'inherit'\n);\n\n// Insert the attachment.\n$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );\n\n// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.\nrequire_once( ABSPATH . 'wp-admin/includes/image.php' );\n\n// Generate the metadata for the attachment, and update the database record.\n$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );\nwp_update_attachment_metadata( $attach_id, $attach_data );\n\n//If you want to set it as a thumbnail\nset_post_thumbnail( $parent_post_id, $attach_id );\n</code></pre>\n"
},
{
"answer_id": 325902,
"author": "z1ad",
"author_id": 121061,
"author_profile": "https://wordpress.stackexchange.com/users/121061",
"pm_score": 2,
"selected": true,
"text": "<p>edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset</p>\n\n<pre><code>wp.media.frame.on('open', function() {\n if (wp.media.frame.content.get() !== null) { \n // this forces a refresh of the content\n wp.media.frame.content.get().collection._requery(true);\n\n // optional: reset selection\n wp.media.frame.content.get().options.selection.reset();\n }\n}, this);\n</code></pre>\n"
}
] | 2019/01/18 | [
"https://wordpress.stackexchange.com/questions/325938",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/154532/"
] | .htaccess:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /wp_test/
RewriteRule ^index\.php$ - [L]
RewriteRule ^the_image$ wp-content/uploads/2019/01/banner\.jpg [L]
RewriteRule ^the_page$ sample-page [L]
</IfModule>
```
When I go to `example.com/the_image` it shows the correct image. However, if I go to `example.com/the_page` it shows the page not found page.
Any work around on this? | edit: ok after working on this for the last hour ive finally found a solution that works without affecting uploading and without messing with ignore or reset
```
wp.media.frame.on('open', function() {
if (wp.media.frame.content.get() !== null) {
// this forces a refresh of the content
wp.media.frame.content.get().collection._requery(true);
// optional: reset selection
wp.media.frame.content.get().options.selection.reset();
}
}, this);
``` |
325,943 | <p>Adding images to a post with the block editor:</p>
<p><a href="https://i.stack.imgur.com/HxXQ7.png" rel="noreferrer"><img src="https://i.stack.imgur.com/HxXQ7.png" alt="enter image description here"></a></p>
<p>produces the code figure of:</p>
<pre><code><figure class="wp-block-image">
<img src="http://localhost:8888/time.png" alt="alt text" class="wp-image-1391"/>
<figcaption>This is an image test.</figcaption>
</figure>
</code></pre>
<p>but I'm using Bootstrap 4 and would like to add <a href="https://getbootstrap.com/docs/4.2/utilities/spacing/" rel="noreferrer">Spacing</a> (such as <code>mt-2</code>) and to remove the image class <code>wp-image-1391</code>, result:</p>
<pre><code><figure class="mt-2">
<img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/>
<figcaption>This is an image test.</figcaption>
</figure>
</code></pre>
<p>or be able to modify it to a div:</p>
<pre><code><div class="mt-2">
<img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/>
<figcaption>This is an image test.</figcaption>
</div>
</code></pre>
<p>Researching I've found <a href="https://developer.wordpress.org/reference/hooks/get_image_tag_class/" rel="noreferrer"><code>get_image_tag_class</code></a> but testing:</p>
<pre><code>function example_add_img_class($class) {
return $class . ' img-fluid';
}
add_filter('get_image_tag_class','example_add_img_class');
</code></pre>
<p>doesn't work. Reading "<a href="https://stackoverflow.com/questions/49779347/how-can-i-prevent-wordpress-from-adding-extra-classes-to-element-in-the-wysiwyg?rq=1">How can I prevent WordPress from adding extra classes to element in the WYSIWYG editor</a>" I tested:</p>
<pre><code>add_filter('get_image_tag_class','__return_empty_string');
</code></pre>
<p>but doesn't work. I can modify the <code><img></code> with a <code>preg_replace</code> using <code>the_content</code> add_filter:</p>
<pre><code>function add_image_fluid_class($content) {
global $post;
$pattern = "/<img(.*?)class=\"(.*?)\"(.*?)>/i";
$replacement = '<img$1class="$2 img-fluid"$3>';
$content = preg_replace($pattern,$replacement,$content);
return $content;
}
add_filter('the_content','add_image_fluid_class');
function img_responsive($content){
return str_replace('<img class="','<img class="img-responsive ',$content);
}
add_filter('the_content','img_responsive');
</code></pre>
<p>but I've read that targeting <code>the_content</code> with regex can yield mixed results. I could solve the issue with a simple CSS:</p>
<pre><code>figure img {
width:100%;
height:auto;
}
figure figcaption {
text-align:center;
font-size:80%;
}
</code></pre>
<p>but I'd like to understand more of what filters I can use to modify WordPress. How can I add and remove classes and change figure to a div?</p>
| [
{
"answer_id": 326009,
"author": "user9447",
"author_id": 25271,
"author_profile": "https://wordpress.stackexchange.com/users/25271",
"pm_score": 2,
"selected": false,
"text": "<p>The following answer is a solution for Bootstrap 4 and centering images in a <code><figure></code> tag.</p>\n\n<p>WordPress generated default:</p>\n\n<pre><code><figure class=\"wp-block-image\">\n <img src=\"http://localhost:8888/time.png\" alt=\"alt text\" class=\"wp-image-1391\"/>\n <figcaption>This is an image test.</figcaption>\n</figure>\n</code></pre>\n\n<p>Using the <a href=\"http://php.net/manual/en/function.preg-replace.php\" rel=\"nofollow noreferrer\"><code>preg_replace()</code></a> and <code>the_content</code>:</p>\n\n<pre><code>function add_image_fluid_class($content) {\n global $post;\n $pattern = \"/<figure class=\\\"[A-Za-z-]*\\\"><img (.*?)class=\\\".*?\\\"(.*?)><figcaption>(.*?)<\\/figcaption><\\/figure>/i\";\n $replacement = '<figure class=\"text-center my-3\"><img class=\"figure-img img-fluid\" $1$2><figcaption class=\"text-muted\">$3</figcaption></figure>';\n $content = preg_replace($pattern,$replacement,$content);\n return $content;\n }\n add_filter('the_content','add_image_fluid_class');\n</code></pre>\n\n<p>will produce:</p>\n\n<pre><code><figure class=\"text-center my-3\">\n <img class=\"figure-img img-fluid\" src=\"http://localhost:8888/time.png\" alt=\"alt text\" />\n <figcaption class=\"text-muted\">This is an image test.</figcaption>\n</figure>\n</code></pre>\n\n<p>The code could be shortened to:</p>\n\n<pre><code>function add_image_fluid_class($content) {\n global $post;\n $pattern = \"/<figure class=\\\"[A-Za-z-]*\\\"><img (.*?)class=\\\".*?\\\"(.*?)><figcaption>/i\";\n $replacement = '<figure class=\"text-center my-3\"><img class=\"figure-img img-fluid\" $1$2><figcaption class=\"text-muted\">';\n $content = preg_replace($pattern,$replacement,$content);\n return $content;\n }\n add_filter('the_content','add_image_fluid_class');\n</code></pre>\n\n<p>if you wanted to add <code><small></code> you could do it as:</p>\n\n<pre><code>function add_image_fluid_class($content) {\n global $post;\n $pattern = \"/<figure class=\\\"[A-Za-z-]*\\\"><img (.*?)class=\\\".*?\\\"(.*?)><figcaption>(.*?)<\\/figcaption><\\/figure>/i\";\n $replacement = '<figure class=\"text-center my-3\"><img class=\"figure-img img-fluid\" $1$2><figcaption class=\"text-muted\"><small>$3</small></figcaption></figure>';\n $content = preg_replace($pattern,$replacement,$content);\n return $content;\n }\n add_filter('the_content','add_image_fluid_class');\n</code></pre>\n\n<p>the backend result is the image block with no align selection:</p>\n\n<p><a href=\"https://i.stack.imgur.com/xxJPl.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/xxJPl.png\" alt=\"enter image description here\"></a></p>\n\n<p>post rendered:</p>\n\n<p><a href=\"https://i.stack.imgur.com/Vwc4K.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/Vwc4K.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 326024,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": 3,
"selected": false,
"text": "<p>After some digging and trial/error I have came up with a couple solutions. I was looking for a \"Gutenberg\" solution so I could avoid using <code>str_replace</code>.</p>\n\n<p>First, we need to enqueue our JS and include the wp.blocks package</p>\n\n<pre><code>// Add to functions.php\n\nfunction gutenberg_enqueue() {\n wp_enqueue_script(\n 'myguten-script',\n // get_template_directory_uri() . '/js/gutenberg.js', // For Parent Themes\n get_stylesheet_directory_uri() . '/js/gutenberg.js', // For Child Themes\n array('wp-blocks') // Include wp.blocks Package \n );\n}\n\nadd_action('enqueue_block_editor_assets', 'gutenberg_enqueue');\n</code></pre>\n\n<hr>\n\n<p>Next, I found a couple solutions, the first is probably the best for your specific use-case.</p>\n\n<p><strong>Method #1</strong></p>\n\n<p>Use a filter function to override the default class. Well, in this case we are going to keep the \"wp-block-image\" class and just add the needed bootstrap class mt-2. But you could easily add whatever class you wanted. Add the code below and create a new image block, inspect it to see the figure tag now has the new class.</p>\n\n<pre><code>// Add to your JS file\n\nfunction setBlockCustomClassName(className, blockName) {\n return blockName === 'core/image' ?\n 'wp-block-image mt-2' :\n className;\n}\n\nwp.hooks.addFilter(\n 'blocks.getBlockDefaultClassName',\n 'my-plugin/set-block-custom-class-name',\n setBlockCustomClassName\n);\n</code></pre>\n\n<hr>\n\n<p><strong>Method #2</strong></p>\n\n<p>Add a setting in the block styles settings in the sidebar to add a class to the image.</p>\n\n<pre><code>// Add to your JS file\n\nwp.blocks.registerBlockStyle('core/image', {\n name: 'test-image-class',\n label: 'Test Class'\n});\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/aIN1t.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/aIN1t.png\" alt=\"enter image description here\"></a></p>\n\n<p>This will add your class but unfortunately Gutenberg appends is-style- before the class, so it results in is-style-test-image-class. You would have to adjust your CSS accordingly.</p>\n\n<hr>\n\n<p><strong>Method #3</strong></p>\n\n<p>Manually adding the class via the Block > Advanced > Additional CSS Class option. Obviously, the class would need to be added for each image block.</p>\n\n<p><a href=\"https://i.stack.imgur.com/9DiVW.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/9DiVW.png\" alt=\"enter image description here\"></a></p>\n\n<hr>\n\n<p><strong>Note:</strong> When adding or editing any of the JS above I needed to delete the block, refresh the page and then re-add the block to avoid getting a <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/#validation\" rel=\"nofollow noreferrer\">block validation error</a>.</p>\n\n<p><strong>References:</strong></p>\n\n<p><a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#block-style-variations\" rel=\"nofollow noreferrer\">Block Style Variations</a></p>\n\n<p><a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-getblockdefaultclassname\" rel=\"nofollow noreferrer\">blocks.getBlockDefaultClassName</a></p>\n"
},
{
"answer_id": 353885,
"author": "StarSagar",
"author_id": 179286,
"author_profile": "https://wordpress.stackexchange.com/users/179286",
"pm_score": 1,
"selected": false,
"text": "<p>The best way to deal with core block frontend issues are \"override core blocks rendering\"</p>\n\n<p>example :</p>\n\n<pre><code><?php\nfunction foo_gallery_render( $attributes, $content ) {\n /**\n * Here you find an array with the ids of all \n * the images that are in your gallery.\n * \n * for example: \n * $attributes = [\n * \"ids\" => [ 12, 34, 56, 78 ]\n * ]\n *\n * Now have fun querying them,\n * arrangin them and returning your constructed markup!\n */\n return '<h1>Custom rendered gallery</h1>';\n}\nfunction foo_register_gallery() {\n register_block_type( 'core/gallery', array(\n 'render_callback' => 'foo_gallery_render',\n ) );\n}\nadd_action( 'init', 'foo_register_gallery' );\n</code></pre>\n\n<p>This works for all core gutenberg blocks, which means you can take advantage of the great blocks already developped, and arrange their output as you wish.</p>\n\n<p>Reference : <a href=\"https://antistatique.net/en/we/blog/2019/01/29/gutenberg-override-core-blocks-rendering\" rel=\"nofollow noreferrer\">https://antistatique.net/en/we/blog/2019/01/29/gutenberg-override-core-blocks-rendering</a></p>\n"
},
{
"answer_id": 373344,
"author": "Alberto",
"author_id": 193398,
"author_profile": "https://wordpress.stackexchange.com/users/193398",
"pm_score": 2,
"selected": false,
"text": "<p>Use the <code>render_block</code> filter hook:</p>\n<pre><code>add_filter( 'render_block', 'wrap_my_gallery_block', 10, 2 );\n\nfunction wrap_my_gallery_block( $block_content, $block ) {\n\n if ( 'core/gallery' !== $block['blockName'] ) {\n return $block_content;\n }\n\n $return = 'my-gallery-block<div class="my-gallery-block">';\n $return .= $block_content;\n $return .= '</div>';\n\n return $return;\n}\n</code></pre>\n<p>Works on WP 5.5.</p>\n<p>Reference: <a href=\"https://wordpress.org/support/topic/modify-gutenberg-core-block-render-result/#post-11716464\" rel=\"nofollow noreferrer\">https://wordpress.org/support/topic/modify-gutenberg-core-block-render-result/#post-11716464</a></p>\n"
}
] | 2019/01/18 | [
"https://wordpress.stackexchange.com/questions/325943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] | Adding images to a post with the block editor:
[](https://i.stack.imgur.com/HxXQ7.png)
produces the code figure of:
```
<figure class="wp-block-image">
<img src="http://localhost:8888/time.png" alt="alt text" class="wp-image-1391"/>
<figcaption>This is an image test.</figcaption>
</figure>
```
but I'm using Bootstrap 4 and would like to add [Spacing](https://getbootstrap.com/docs/4.2/utilities/spacing/) (such as `mt-2`) and to remove the image class `wp-image-1391`, result:
```
<figure class="mt-2">
<img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/>
<figcaption>This is an image test.</figcaption>
</figure>
```
or be able to modify it to a div:
```
<div class="mt-2">
<img src="http://localhost:8888/time.png" alt="alt text" class="img-fluid"/>
<figcaption>This is an image test.</figcaption>
</div>
```
Researching I've found [`get_image_tag_class`](https://developer.wordpress.org/reference/hooks/get_image_tag_class/) but testing:
```
function example_add_img_class($class) {
return $class . ' img-fluid';
}
add_filter('get_image_tag_class','example_add_img_class');
```
doesn't work. Reading "[How can I prevent WordPress from adding extra classes to element in the WYSIWYG editor](https://stackoverflow.com/questions/49779347/how-can-i-prevent-wordpress-from-adding-extra-classes-to-element-in-the-wysiwyg?rq=1)" I tested:
```
add_filter('get_image_tag_class','__return_empty_string');
```
but doesn't work. I can modify the `<img>` with a `preg_replace` using `the_content` add\_filter:
```
function add_image_fluid_class($content) {
global $post;
$pattern = "/<img(.*?)class=\"(.*?)\"(.*?)>/i";
$replacement = '<img$1class="$2 img-fluid"$3>';
$content = preg_replace($pattern,$replacement,$content);
return $content;
}
add_filter('the_content','add_image_fluid_class');
function img_responsive($content){
return str_replace('<img class="','<img class="img-responsive ',$content);
}
add_filter('the_content','img_responsive');
```
but I've read that targeting `the_content` with regex can yield mixed results. I could solve the issue with a simple CSS:
```
figure img {
width:100%;
height:auto;
}
figure figcaption {
text-align:center;
font-size:80%;
}
```
but I'd like to understand more of what filters I can use to modify WordPress. How can I add and remove classes and change figure to a div? | After some digging and trial/error I have came up with a couple solutions. I was looking for a "Gutenberg" solution so I could avoid using `str_replace`.
First, we need to enqueue our JS and include the wp.blocks package
```
// Add to functions.php
function gutenberg_enqueue() {
wp_enqueue_script(
'myguten-script',
// get_template_directory_uri() . '/js/gutenberg.js', // For Parent Themes
get_stylesheet_directory_uri() . '/js/gutenberg.js', // For Child Themes
array('wp-blocks') // Include wp.blocks Package
);
}
add_action('enqueue_block_editor_assets', 'gutenberg_enqueue');
```
---
Next, I found a couple solutions, the first is probably the best for your specific use-case.
**Method #1**
Use a filter function to override the default class. Well, in this case we are going to keep the "wp-block-image" class and just add the needed bootstrap class mt-2. But you could easily add whatever class you wanted. Add the code below and create a new image block, inspect it to see the figure tag now has the new class.
```
// Add to your JS file
function setBlockCustomClassName(className, blockName) {
return blockName === 'core/image' ?
'wp-block-image mt-2' :
className;
}
wp.hooks.addFilter(
'blocks.getBlockDefaultClassName',
'my-plugin/set-block-custom-class-name',
setBlockCustomClassName
);
```
---
**Method #2**
Add a setting in the block styles settings in the sidebar to add a class to the image.
```
// Add to your JS file
wp.blocks.registerBlockStyle('core/image', {
name: 'test-image-class',
label: 'Test Class'
});
```
[](https://i.stack.imgur.com/aIN1t.png)
This will add your class but unfortunately Gutenberg appends is-style- before the class, so it results in is-style-test-image-class. You would have to adjust your CSS accordingly.
---
**Method #3**
Manually adding the class via the Block > Advanced > Additional CSS Class option. Obviously, the class would need to be added for each image block.
[](https://i.stack.imgur.com/9DiVW.png)
---
**Note:** When adding or editing any of the JS above I needed to delete the block, refresh the page and then re-add the block to avoid getting a [block validation error](https://wordpress.org/gutenberg/handbook/designers-developers/developers/block-api/block-edit-save/#validation).
**References:**
[Block Style Variations](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#block-style-variations)
[blocks.getBlockDefaultClassName](https://wordpress.org/gutenberg/handbook/designers-developers/developers/filters/block-filters/#blocks-getblockdefaultclassname) |
325,956 | <p>I have a code that displays results for search but, I need it to include the count
not just keyword searched</p>
<pre><code><h1 class="font-thin h2 m-b">
<?php
printf( esc_html__( 'Search Results for: %s', 'musik' ), '<span class="font-bold">' . get_search_query() . '</span>' );
?>
</h1>
</code></pre>
| [
{
"answer_id": 325957,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 1,
"selected": false,
"text": "<p>If you are in the search results template then you can find out the count by using the below code.</p>\n\n<pre><code>global $wp_query;\n$count = $wp_query->found_posts\n</code></pre>\n\n<p>variable <code>$count</code> contains the count of post against the search.</p>\n"
},
{
"answer_id": 325971,
"author": "Gufran Hasan",
"author_id": 137328,
"author_profile": "https://wordpress.stackexchange.com/users/137328",
"pm_score": 0,
"selected": false,
"text": "<p>Please open and modify this line in <code>search.php</code>.</p>\n\n<pre><code><h1 class=\"font-thin h2 m-b\">\nSearch Result for <?php \n/* Search Count */ $allsearch = &new WP_Query(\"s=$s&showposts=-1\"); \n$key = wp_specialchars($s, 1); \n$count = $allsearch->post_count; _e(''); _e('<span class=\"search-terms\">'); \necho $key; _e('</span>'); _e(' &mdash; '); \necho $count . ' '; _e('articles'); \nwp_reset_query(); \n\n?>\n\n</h2>\n</code></pre>\n\n<p><a href=\"https://www.wpbeginner.com/wp-tutorials/display-search-term-and-result-count-in-wordpress/\" rel=\"nofollow noreferrer\">Reference link</a></p>\n"
}
] | 2019/01/18 | [
"https://wordpress.stackexchange.com/questions/325956",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159276/"
] | I have a code that displays results for search but, I need it to include the count
not just keyword searched
```
<h1 class="font-thin h2 m-b">
<?php
printf( esc_html__( 'Search Results for: %s', 'musik' ), '<span class="font-bold">' . get_search_query() . '</span>' );
?>
</h1>
``` | If you are in the search results template then you can find out the count by using the below code.
```
global $wp_query;
$count = $wp_query->found_posts
```
variable `$count` contains the count of post against the search. |
326,005 | <p>the answer to this one will probably be obvious to many of you, but I recently decided to make a website for my girlfriend and expand my knowledge while doing that. So here is my dilemma:</p>
<p>I am using the Blossom Mommy Blog theme, which is a child of the Blossom Feminine theme.</p>
<p>Below a single post page, there is a previous post/ next post navigation menu, that has some text in English and I want to change that to be in Bulgarian (see attached file below). I was able to see this in the browser debugger, but I can't seem to find where this comes from in the theme files themself, so any help would be really appreciated!</p>
<p><a href="https://i.stack.imgur.com/vbgFU.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/vbgFU.png" alt="Here's what I want to change"></a></p>
<p>With many thanks,
Dobri</p>
| [
{
"answer_id": 325957,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 1,
"selected": false,
"text": "<p>If you are in the search results template then you can find out the count by using the below code.</p>\n\n<pre><code>global $wp_query;\n$count = $wp_query->found_posts\n</code></pre>\n\n<p>variable <code>$count</code> contains the count of post against the search.</p>\n"
},
{
"answer_id": 325971,
"author": "Gufran Hasan",
"author_id": 137328,
"author_profile": "https://wordpress.stackexchange.com/users/137328",
"pm_score": 0,
"selected": false,
"text": "<p>Please open and modify this line in <code>search.php</code>.</p>\n\n<pre><code><h1 class=\"font-thin h2 m-b\">\nSearch Result for <?php \n/* Search Count */ $allsearch = &new WP_Query(\"s=$s&showposts=-1\"); \n$key = wp_specialchars($s, 1); \n$count = $allsearch->post_count; _e(''); _e('<span class=\"search-terms\">'); \necho $key; _e('</span>'); _e(' &mdash; '); \necho $count . ' '; _e('articles'); \nwp_reset_query(); \n\n?>\n\n</h2>\n</code></pre>\n\n<p><a href=\"https://www.wpbeginner.com/wp-tutorials/display-search-term-and-result-count-in-wordpress/\" rel=\"nofollow noreferrer\">Reference link</a></p>\n"
}
] | 2019/01/18 | [
"https://wordpress.stackexchange.com/questions/326005",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159310/"
] | the answer to this one will probably be obvious to many of you, but I recently decided to make a website for my girlfriend and expand my knowledge while doing that. So here is my dilemma:
I am using the Blossom Mommy Blog theme, which is a child of the Blossom Feminine theme.
Below a single post page, there is a previous post/ next post navigation menu, that has some text in English and I want to change that to be in Bulgarian (see attached file below). I was able to see this in the browser debugger, but I can't seem to find where this comes from in the theme files themself, so any help would be really appreciated!
[](https://i.stack.imgur.com/vbgFU.png)
With many thanks,
Dobri | If you are in the search results template then you can find out the count by using the below code.
```
global $wp_query;
$count = $wp_query->found_posts
```
variable `$count` contains the count of post against the search. |
326,013 | <p>I'm loading some third party CSS with the help of wp_enqueue_style. I would like this CSS to be loaded in the footer, so it does not block rendering of the page. This would be fine, since this CSS is related to some chat functionality which is loaded on the page right away anyway. For JS, there is an option for adding right before the end of the body tag, instead of at the top of the page, but no such thing seem to exist for CSS. So, I'm wondering if there is some smart solution for this?</p>
<p>-- <strong>Edit</strong></p>
<p>I know that strictly speaking, style and link tags are not allowed anywhere but in the head, but I think it's a debatable question. Browsers do not complain about this and why would Google recommend this practice if it was so bad?</p>
| [
{
"answer_id": 326019,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code><head></code> are considered invalid.</p>\n\n<p>A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a <a href=\"https://en.wikipedia.org/wiki/Flash_of_unstyled_content\" rel=\"nofollow noreferrer\">FOUC</a>)</p>\n\n<p>Here's a technique as suggested by <a href=\"https://www.giftofspeed.com/defer-loading-css/\" rel=\"nofollow noreferrer\">GiftOfSpeed</a></p>\n\n<h3>This JS will create your css-link elements dynamically.</h3>\n\n<pre><code><script type=\"text/javascript\">\n /* First CSS File */\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n\n /* Second CSS File */\n var wpse326013_2 = document.createElement('link');\n wpse326013_2.rel = 'stylesheet';\n wpse326013_2.href = '../css/yourcssfile2.css';\n wpse326013_2.type = 'text/css';\n var godefer2 = document.getElementsByTagName('link')[0];\n godefer2.parentNode.insertBefore(wpse326013_2, godefer2);\n</script>\n</code></pre>\n\n<h3>& for graceful degradation, we also include the following inside of the head element</h3>\n\n<pre><code><noscript>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile2.css\" />\n</noscript>\n</code></pre>\n\n<blockquote>\n <p>You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.</p>\n</blockquote>\n\n<pre><code>setTimeout(function(){\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n}, 2000);\n</code></pre>\n"
},
{
"answer_id": 326036,
"author": "Keith Tysinger",
"author_id": 159326,
"author_profile": "https://wordpress.stackexchange.com/users/159326",
"pm_score": 0,
"selected": false,
"text": "<p>Modern web browsers don't seem to have a problem with that. You could do it that way and use inline CSS for any critical sections of the webpage. </p>\n\n<p>However, that does not mean that you should put the CSS in the body of the document. It was designed to be included only in the header. That is correct Html syntax. I hate to watch websites elements rearrange themselves because the css was inserted in the footer. </p>\n\n<p>I suggest that you instead run your CSS through a minimizer and/or add it to a CDN. You can also add some gzip compression via the .htaccess file, if applicable. Lastly, you can combine all of the site's css into one big file to speed up load time. </p>\n"
},
{
"answer_id": 326039,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>function 326013_add_footer_styles() {\n wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );\n};\nadd_action( 'get_footer', '326013_add_footer_styles' );\n</code></pre>\n\n<p>From this answer: <a href=\"https://wordpress.stackexchange.com/a/186066/121955\">https://wordpress.stackexchange.com/a/186066/121955</a></p>\n"
}
] | 2019/01/18 | [
"https://wordpress.stackexchange.com/questions/326013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5079/"
] | I'm loading some third party CSS with the help of wp\_enqueue\_style. I would like this CSS to be loaded in the footer, so it does not block rendering of the page. This would be fine, since this CSS is related to some chat functionality which is loaded on the page right away anyway. For JS, there is an option for adding right before the end of the body tag, instead of at the top of the page, but no such thing seem to exist for CSS. So, I'm wondering if there is some smart solution for this?
-- **Edit**
I know that strictly speaking, style and link tags are not allowed anywhere but in the head, but I think it's a debatable question. Browsers do not complain about this and why would Google recommend this practice if it was so bad? | Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid.
A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content))
Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/)
### This JS will create your css-link elements dynamically.
```
<script type="text/javascript">
/* First CSS File */
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
/* Second CSS File */
var wpse326013_2 = document.createElement('link');
wpse326013_2.rel = 'stylesheet';
wpse326013_2.href = '../css/yourcssfile2.css';
wpse326013_2.type = 'text/css';
var godefer2 = document.getElementsByTagName('link')[0];
godefer2.parentNode.insertBefore(wpse326013_2, godefer2);
</script>
```
### & for graceful degradation, we also include the following inside of the head element
```
<noscript>
<link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" />
<link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" />
</noscript>
```
>
> You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.
>
>
>
```
setTimeout(function(){
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
}, 2000);
``` |
326,055 | <p>I'm interested in creating a filter for pages with password protection and that have a certain category. I've placed this code in my theme's child folder in functions.php since I didn't want to edit the wp-includes files.</p>
<pre><code>/**
* Retrieve v1-i1 protected post password form content.
*
* @since 1.0.0
*
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
* @return string HTML content for password form for password protected post.
*/
function get_the_v1i1_password_form( $post = 0 ) {
$post = get_post( $post );
$label = 'pwbox-' . ( empty($post->ID) ? rand() : $post->ID );
$output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post">
<p>' . __( 'This is exclusive content from v1:i1. Please enter password below:' ) . '</p>
<p><label for="' . $label . '">' . __( 'Password:' ) . ' <input name="post_password" id="' . $label . '" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . esc_attr_x( 'Enter', 'post password form' ) . '" /></p></form>
';
/**
* Filters the HTML output for the protected post password form.
*
* If modifying the password field, please note that the core database schema
* limits the password field to 20 characters regardless of the value of the
* size attribute in the form input.
*
* @since 2.7.0
*
* @param string $output The password form HTML output.
*/
return apply_filters( 'the_password_form', $output );
}
// If post password required and it doesn't match the cookie.
if (post_password_required( $post ) && in_category( 'v1-i1' )) {
return get_the_v1i1_password_form( $post );
} else {
return get_the_password_form( $post );
}
`
</code></pre>
<p>I can't seem to get this to work. Am I missing something?</p>
| [
{
"answer_id": 326019,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code><head></code> are considered invalid.</p>\n\n<p>A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a <a href=\"https://en.wikipedia.org/wiki/Flash_of_unstyled_content\" rel=\"nofollow noreferrer\">FOUC</a>)</p>\n\n<p>Here's a technique as suggested by <a href=\"https://www.giftofspeed.com/defer-loading-css/\" rel=\"nofollow noreferrer\">GiftOfSpeed</a></p>\n\n<h3>This JS will create your css-link elements dynamically.</h3>\n\n<pre><code><script type=\"text/javascript\">\n /* First CSS File */\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n\n /* Second CSS File */\n var wpse326013_2 = document.createElement('link');\n wpse326013_2.rel = 'stylesheet';\n wpse326013_2.href = '../css/yourcssfile2.css';\n wpse326013_2.type = 'text/css';\n var godefer2 = document.getElementsByTagName('link')[0];\n godefer2.parentNode.insertBefore(wpse326013_2, godefer2);\n</script>\n</code></pre>\n\n<h3>& for graceful degradation, we also include the following inside of the head element</h3>\n\n<pre><code><noscript>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile2.css\" />\n</noscript>\n</code></pre>\n\n<blockquote>\n <p>You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.</p>\n</blockquote>\n\n<pre><code>setTimeout(function(){\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n}, 2000);\n</code></pre>\n"
},
{
"answer_id": 326036,
"author": "Keith Tysinger",
"author_id": 159326,
"author_profile": "https://wordpress.stackexchange.com/users/159326",
"pm_score": 0,
"selected": false,
"text": "<p>Modern web browsers don't seem to have a problem with that. You could do it that way and use inline CSS for any critical sections of the webpage. </p>\n\n<p>However, that does not mean that you should put the CSS in the body of the document. It was designed to be included only in the header. That is correct Html syntax. I hate to watch websites elements rearrange themselves because the css was inserted in the footer. </p>\n\n<p>I suggest that you instead run your CSS through a minimizer and/or add it to a CDN. You can also add some gzip compression via the .htaccess file, if applicable. Lastly, you can combine all of the site's css into one big file to speed up load time. </p>\n"
},
{
"answer_id": 326039,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>function 326013_add_footer_styles() {\n wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );\n};\nadd_action( 'get_footer', '326013_add_footer_styles' );\n</code></pre>\n\n<p>From this answer: <a href=\"https://wordpress.stackexchange.com/a/186066/121955\">https://wordpress.stackexchange.com/a/186066/121955</a></p>\n"
}
] | 2019/01/19 | [
"https://wordpress.stackexchange.com/questions/326055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159342/"
] | I'm interested in creating a filter for pages with password protection and that have a certain category. I've placed this code in my theme's child folder in functions.php since I didn't want to edit the wp-includes files.
```
/**
* Retrieve v1-i1 protected post password form content.
*
* @since 1.0.0
*
* @param int|WP_Post $post Optional. Post ID or WP_Post object. Default is global $post.
* @return string HTML content for password form for password protected post.
*/
function get_the_v1i1_password_form( $post = 0 ) {
$post = get_post( $post );
$label = 'pwbox-' . ( empty($post->ID) ? rand() : $post->ID );
$output = '<form action="' . esc_url( site_url( 'wp-login.php?action=postpass', 'login_post' ) ) . '" class="post-password-form" method="post">
<p>' . __( 'This is exclusive content from v1:i1. Please enter password below:' ) . '</p>
<p><label for="' . $label . '">' . __( 'Password:' ) . ' <input name="post_password" id="' . $label . '" type="password" size="20" /></label> <input type="submit" name="Submit" value="' . esc_attr_x( 'Enter', 'post password form' ) . '" /></p></form>
';
/**
* Filters the HTML output for the protected post password form.
*
* If modifying the password field, please note that the core database schema
* limits the password field to 20 characters regardless of the value of the
* size attribute in the form input.
*
* @since 2.7.0
*
* @param string $output The password form HTML output.
*/
return apply_filters( 'the_password_form', $output );
}
// If post password required and it doesn't match the cookie.
if (post_password_required( $post ) && in_category( 'v1-i1' )) {
return get_the_v1i1_password_form( $post );
} else {
return get_the_password_form( $post );
}
`
```
I can't seem to get this to work. Am I missing something? | Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid.
A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content))
Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/)
### This JS will create your css-link elements dynamically.
```
<script type="text/javascript">
/* First CSS File */
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
/* Second CSS File */
var wpse326013_2 = document.createElement('link');
wpse326013_2.rel = 'stylesheet';
wpse326013_2.href = '../css/yourcssfile2.css';
wpse326013_2.type = 'text/css';
var godefer2 = document.getElementsByTagName('link')[0];
godefer2.parentNode.insertBefore(wpse326013_2, godefer2);
</script>
```
### & for graceful degradation, we also include the following inside of the head element
```
<noscript>
<link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" />
<link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" />
</noscript>
```
>
> You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.
>
>
>
```
setTimeout(function(){
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
}, 2000);
``` |
326,066 | <p>I did a small adjustment in the 'custom css' in my theme settings, and now I broke my theme. Whenever I select a page as the home page, it says 'Nothing found'. Whenever I visit a page thats not a home page, it works perfectly fine. </p>
<p>Been looking for hours now. Any help appreciated. </p>
<p>Edit: The change in the CSS I made was temporary putting a piece of CSS within a comment (/* foo */) for testing purposes. </p>
| [
{
"answer_id": 326019,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code><head></code> are considered invalid.</p>\n\n<p>A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a <a href=\"https://en.wikipedia.org/wiki/Flash_of_unstyled_content\" rel=\"nofollow noreferrer\">FOUC</a>)</p>\n\n<p>Here's a technique as suggested by <a href=\"https://www.giftofspeed.com/defer-loading-css/\" rel=\"nofollow noreferrer\">GiftOfSpeed</a></p>\n\n<h3>This JS will create your css-link elements dynamically.</h3>\n\n<pre><code><script type=\"text/javascript\">\n /* First CSS File */\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n\n /* Second CSS File */\n var wpse326013_2 = document.createElement('link');\n wpse326013_2.rel = 'stylesheet';\n wpse326013_2.href = '../css/yourcssfile2.css';\n wpse326013_2.type = 'text/css';\n var godefer2 = document.getElementsByTagName('link')[0];\n godefer2.parentNode.insertBefore(wpse326013_2, godefer2);\n</script>\n</code></pre>\n\n<h3>& for graceful degradation, we also include the following inside of the head element</h3>\n\n<pre><code><noscript>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile2.css\" />\n</noscript>\n</code></pre>\n\n<blockquote>\n <p>You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.</p>\n</blockquote>\n\n<pre><code>setTimeout(function(){\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n}, 2000);\n</code></pre>\n"
},
{
"answer_id": 326036,
"author": "Keith Tysinger",
"author_id": 159326,
"author_profile": "https://wordpress.stackexchange.com/users/159326",
"pm_score": 0,
"selected": false,
"text": "<p>Modern web browsers don't seem to have a problem with that. You could do it that way and use inline CSS for any critical sections of the webpage. </p>\n\n<p>However, that does not mean that you should put the CSS in the body of the document. It was designed to be included only in the header. That is correct Html syntax. I hate to watch websites elements rearrange themselves because the css was inserted in the footer. </p>\n\n<p>I suggest that you instead run your CSS through a minimizer and/or add it to a CDN. You can also add some gzip compression via the .htaccess file, if applicable. Lastly, you can combine all of the site's css into one big file to speed up load time. </p>\n"
},
{
"answer_id": 326039,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>function 326013_add_footer_styles() {\n wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );\n};\nadd_action( 'get_footer', '326013_add_footer_styles' );\n</code></pre>\n\n<p>From this answer: <a href=\"https://wordpress.stackexchange.com/a/186066/121955\">https://wordpress.stackexchange.com/a/186066/121955</a></p>\n"
}
] | 2019/01/19 | [
"https://wordpress.stackexchange.com/questions/326066",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159369/"
] | I did a small adjustment in the 'custom css' in my theme settings, and now I broke my theme. Whenever I select a page as the home page, it says 'Nothing found'. Whenever I visit a page thats not a home page, it works perfectly fine.
Been looking for hours now. Any help appreciated.
Edit: The change in the CSS I made was temporary putting a piece of CSS within a comment (/\* foo \*/) for testing purposes. | Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid.
A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content))
Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/)
### This JS will create your css-link elements dynamically.
```
<script type="text/javascript">
/* First CSS File */
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
/* Second CSS File */
var wpse326013_2 = document.createElement('link');
wpse326013_2.rel = 'stylesheet';
wpse326013_2.href = '../css/yourcssfile2.css';
wpse326013_2.type = 'text/css';
var godefer2 = document.getElementsByTagName('link')[0];
godefer2.parentNode.insertBefore(wpse326013_2, godefer2);
</script>
```
### & for graceful degradation, we also include the following inside of the head element
```
<noscript>
<link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" />
<link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" />
</noscript>
```
>
> You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.
>
>
>
```
setTimeout(function(){
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
}, 2000);
``` |
326,088 | <p>Here is a test fiddle: my fiddle: <a href="https://jsfiddle.net/blogob/qtou84Lj/23/" rel="nofollow noreferrer">https://jsfiddle.net/blogob/qtou84Lj/23/</a></p>
<p>I'm trying to build a full width map in a wordpress site with leaflet.</p>
<p>My goal is to dsplay all post with markers on the map. When i click on the marker, a sidebar appear with the corresponding content in it. It's working.</p>
<p>But i have a problem that i can't solve. we can see it in the fiddle, when i move the map, i can see "the content" behind the map. so i have it in the sidebar and also on the page, behind the map.
In my wordpress site it's the same : my post contain a title, a video and a description. When i hover the map, in some place i can click on the video that is behind the map and it redirects me to youtube..
so it's a huge problem for me. Is it better to display content via data attributes, i tryed but without success. if i put the content in a data attribute, the map doen't appear in the page.
i don't understand why the post are duplicated..</p>
| [
{
"answer_id": 326019,
"author": "admcfajn",
"author_id": 123674,
"author_profile": "https://wordpress.stackexchange.com/users/123674",
"pm_score": 3,
"selected": true,
"text": "<p>Yes, technically you can. But you shouldn't load css in the footer, css links outside of the <code><head></code> are considered invalid.</p>\n\n<p>A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a <a href=\"https://en.wikipedia.org/wiki/Flash_of_unstyled_content\" rel=\"nofollow noreferrer\">FOUC</a>)</p>\n\n<p>Here's a technique as suggested by <a href=\"https://www.giftofspeed.com/defer-loading-css/\" rel=\"nofollow noreferrer\">GiftOfSpeed</a></p>\n\n<h3>This JS will create your css-link elements dynamically.</h3>\n\n<pre><code><script type=\"text/javascript\">\n /* First CSS File */\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n\n /* Second CSS File */\n var wpse326013_2 = document.createElement('link');\n wpse326013_2.rel = 'stylesheet';\n wpse326013_2.href = '../css/yourcssfile2.css';\n wpse326013_2.type = 'text/css';\n var godefer2 = document.getElementsByTagName('link')[0];\n godefer2.parentNode.insertBefore(wpse326013_2, godefer2);\n</script>\n</code></pre>\n\n<h3>& for graceful degradation, we also include the following inside of the head element</h3>\n\n<pre><code><noscript>\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile.css\" />\n <link rel=\"stylesheet\" type=\"text/css\" href=\"../css/yourcssfile2.css\" />\n</noscript>\n</code></pre>\n\n<blockquote>\n <p>You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.</p>\n</blockquote>\n\n<pre><code>setTimeout(function(){\n var wpse326013 = document.createElement('link');\n wpse326013.rel = 'stylesheet';\n wpse326013.href = '../css/yourcssfile.css';\n wpse326013.type = 'text/css';\n var godefer = document.getElementsByTagName('link')[0];\n godefer.parentNode.insertBefore(wpse326013, godefer);\n}, 2000);\n</code></pre>\n"
},
{
"answer_id": 326036,
"author": "Keith Tysinger",
"author_id": 159326,
"author_profile": "https://wordpress.stackexchange.com/users/159326",
"pm_score": 0,
"selected": false,
"text": "<p>Modern web browsers don't seem to have a problem with that. You could do it that way and use inline CSS for any critical sections of the webpage. </p>\n\n<p>However, that does not mean that you should put the CSS in the body of the document. It was designed to be included only in the header. That is correct Html syntax. I hate to watch websites elements rearrange themselves because the css was inserted in the footer. </p>\n\n<p>I suggest that you instead run your CSS through a minimizer and/or add it to a CDN. You can also add some gzip compression via the .htaccess file, if applicable. Lastly, you can combine all of the site's css into one big file to speed up load time. </p>\n"
},
{
"answer_id": 326039,
"author": "Liam Stewart",
"author_id": 121955,
"author_profile": "https://wordpress.stackexchange.com/users/121955",
"pm_score": 2,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code>function 326013_add_footer_styles() {\n wp_enqueue_style( 'your-style-id', get_template_directory_uri() . '/stylesheets/somestyle.css' );\n};\nadd_action( 'get_footer', '326013_add_footer_styles' );\n</code></pre>\n\n<p>From this answer: <a href=\"https://wordpress.stackexchange.com/a/186066/121955\">https://wordpress.stackexchange.com/a/186066/121955</a></p>\n"
}
] | 2019/01/19 | [
"https://wordpress.stackexchange.com/questions/326088",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159378/"
] | Here is a test fiddle: my fiddle: <https://jsfiddle.net/blogob/qtou84Lj/23/>
I'm trying to build a full width map in a wordpress site with leaflet.
My goal is to dsplay all post with markers on the map. When i click on the marker, a sidebar appear with the corresponding content in it. It's working.
But i have a problem that i can't solve. we can see it in the fiddle, when i move the map, i can see "the content" behind the map. so i have it in the sidebar and also on the page, behind the map.
In my wordpress site it's the same : my post contain a title, a video and a description. When i hover the map, in some place i can click on the video that is behind the map and it redirects me to youtube..
so it's a huge problem for me. Is it better to display content via data attributes, i tryed but without success. if i put the content in a data attribute, the map doen't appear in the page.
i don't understand why the post are duplicated.. | Yes, technically you can. But you shouldn't load css in the footer, css links outside of the `<head>` are considered invalid.
A better technique would be to add the css-links to the dom with javaScript. You may even want to split out the css so that critical portions are loaded inline (so you avoid a [FOUC](https://en.wikipedia.org/wiki/Flash_of_unstyled_content))
Here's a technique as suggested by [GiftOfSpeed](https://www.giftofspeed.com/defer-loading-css/)
### This JS will create your css-link elements dynamically.
```
<script type="text/javascript">
/* First CSS File */
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
/* Second CSS File */
var wpse326013_2 = document.createElement('link');
wpse326013_2.rel = 'stylesheet';
wpse326013_2.href = '../css/yourcssfile2.css';
wpse326013_2.type = 'text/css';
var godefer2 = document.getElementsByTagName('link')[0];
godefer2.parentNode.insertBefore(wpse326013_2, godefer2);
</script>
```
### & for graceful degradation, we also include the following inside of the head element
```
<noscript>
<link rel="stylesheet" type="text/css" href="../css/yourcssfile.css" />
<link rel="stylesheet" type="text/css" href="../css/yourcssfile2.css" />
</noscript>
```
>
> You could also wrap the execution of the javaScript in a timeout, the following example would delay execution by 2 seconds.
>
>
>
```
setTimeout(function(){
var wpse326013 = document.createElement('link');
wpse326013.rel = 'stylesheet';
wpse326013.href = '../css/yourcssfile.css';
wpse326013.type = 'text/css';
var godefer = document.getElementsByTagName('link')[0];
godefer.parentNode.insertBefore(wpse326013, godefer);
}, 2000);
``` |
326,109 | <p>I Need to build an interface with a filter set (a list of checkboxes) that the user can check and click 'filter' to search with in 1 custom post-type for posts with matching terms (there are 3 custom taxonomies with each an unlimited amount of terms).</p>
<p><em>How to go about this? I am thinking to code the following:</em></p>
<p>I displayed the GUI filterlist like this (x3 because there are 3 taxonomies):</p>
<pre><code><form action="/filter-result" method="get">
<?php $terms = get_terms( array(
'taxonomy' => 'taxonomy-name',
'hide_empty' => false,
) );
foreach($terms as $term) {
echo '<label><input type="checkbox" name="taxonomy-name" value="' . $term->name .'">' . $term->name . '</label>';
} ?>
<input type="submit" value="Filter">
</form>
</code></pre>
<p>I end up on the <code>/filter-result</code> page with an URL with more than one parameter that all have the same name:
<code>filter-result/?taxonomya=term1&taxonomya=term2&taxonomyb=term9</code></p>
<p>My plan is to GET all the parameters- I don't know how because there are parameters with the same name- and then build an SQL out of the filtered data.</p>
| [
{
"answer_id": 326111,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>Add brackets to the input names:</p>\n\n<pre><code><label><input type=\"checkbox\" name=\"taxonomy-name[]\" value=\"term\">term</label>\n</code></pre>\n\n<p>It will be automatically converted to an array:</p>\n\n<pre><code>if( isset( $_GET['taxonomy-name'] ) ){\n foreach( $_GET['taxonomy-name'] as $term ){\n echo $term;\n }\n}\n</code></pre>\n"
},
{
"answer_id": 326187,
"author": "Ludo",
"author_id": 108754,
"author_profile": "https://wordpress.stackexchange.com/users/108754",
"pm_score": 0,
"selected": false,
"text": "<p>As an addition to Milo's answer for the sake of completeness, this is how I formed the args for the sql using the URL parameters:</p>\n\n<pre><code>$query = new WP_Query( array(\n 'posts_per_page' => -1,\n 'post_type' => 'mycustomposttype',\n 'orderby' => 'title',\n 'order' => 'ASC',\n 'tax_query' => array(\n 'relationship' => 'AND',\n array(\n 'taxonomy' => 'mytaxonomy1',\n 'field' => 'slug',\n 'terms' => $_GET['mytaxonomy1'],\n 'operator' => 'AND',\n ),\n array(\n 'taxonomy' => 'mytaxonomy2',\n 'field' => 'slug',\n 'terms' => $_GET['mytaxonomy2'],\n 'operator' => 'AND',\n ),\n array(\n 'taxonomy' => 'mytaxonomy3',\n 'field' => 'slug',\n 'terms' => $_GET['mytaxonomy3'],\n 'operator' => 'AND',\n ),\n ),\n) );\n\nif ( $query->have_posts() ) {\n while ( $query->have_posts() ) {\n }\n}\n</code></pre>\n\n<p>See for more elaboration <a href=\"https://stackoverflow.com/a/54280549/3065848\">this question</a>.\nI also found this a great resource for making the WP_Query: <a href=\"https://code.tutsplus.com/tutorials/wp_query-arguments-taxonomies--cms-23090\" rel=\"nofollow noreferrer\">WP_Query Arguments: Taxonomies</a></p>\n"
}
] | 2019/01/19 | [
"https://wordpress.stackexchange.com/questions/326109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108754/"
] | I Need to build an interface with a filter set (a list of checkboxes) that the user can check and click 'filter' to search with in 1 custom post-type for posts with matching terms (there are 3 custom taxonomies with each an unlimited amount of terms).
*How to go about this? I am thinking to code the following:*
I displayed the GUI filterlist like this (x3 because there are 3 taxonomies):
```
<form action="/filter-result" method="get">
<?php $terms = get_terms( array(
'taxonomy' => 'taxonomy-name',
'hide_empty' => false,
) );
foreach($terms as $term) {
echo '<label><input type="checkbox" name="taxonomy-name" value="' . $term->name .'">' . $term->name . '</label>';
} ?>
<input type="submit" value="Filter">
</form>
```
I end up on the `/filter-result` page with an URL with more than one parameter that all have the same name:
`filter-result/?taxonomya=term1&taxonomya=term2&taxonomyb=term9`
My plan is to GET all the parameters- I don't know how because there are parameters with the same name- and then build an SQL out of the filtered data. | Add brackets to the input names:
```
<label><input type="checkbox" name="taxonomy-name[]" value="term">term</label>
```
It will be automatically converted to an array:
```
if( isset( $_GET['taxonomy-name'] ) ){
foreach( $_GET['taxonomy-name'] as $term ){
echo $term;
}
}
``` |
326,143 | <p>I got this code:</p>
<pre><code>function ntt_movie_shortcode($atts, $content = null)
{
return 'TEST';
}
add_shortcode('ntt_movie', 'ntt_movie_shortcode');
</code></pre>
<p>The shortcode works perfectly on a single page, but on the Home Page / in excerpts the shortcodes are rendered as an empty string. So, the shortcode gets recognized but it seems, that the function doesn't get processed.</p>
<p>Any hints or approaches?</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 326126,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 1,
"selected": false,
"text": "<p>You can test the site back up by creating a staging site or uploading the backup on your localhost to verify how much work you have done.</p>\n"
},
{
"answer_id": 326152,
"author": "Inarvo Solutions",
"author_id": 159428,
"author_profile": "https://wordpress.stackexchange.com/users/159428",
"pm_score": 0,
"selected": false,
"text": "<p>If you do not want to disturb your live version, then what @Mohsin Ghouri has suggested is best option. Installing the backup version on your desktop would be simpler and faster. </p>\n"
},
{
"answer_id": 326153,
"author": "Bram",
"author_id": 60517,
"author_profile": "https://wordpress.stackexchange.com/users/60517",
"pm_score": 0,
"selected": false,
"text": "<p>You can't: you either restore a back-up or you don't. In the process of restoring a back-up, current files and database entries are moved/edited/deleted in order to go back to the previous set of files and database entries.</p>\n\n<p>The easiest thing to do (rough translation of Mohsin's answer) is to create a separate website (\"staging site\") where you upload the backup. This way, you still have the current live site (\"production\") and have the staging area running in parallel - so you can make a side-by-side comparison. You can use an external web server for this staging area, or run it on a local web server that is running on your computer (\"localhost\"). <a href=\"https://www.maketecheasier.com/setup-local-web-server-all-platforms/\" rel=\"nofollow noreferrer\">Here</a> is a tutorial on how you can do that.</p>\n\n<p>Please keep in mind that your database is filled with links to the domain (www.website.com) and that you have to search and replace these domains throughout the database. <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">This</a> is a good tool for that, although (as the site also stipulates) you have to be cautious when using it, as it can mess up your database pretty bad. </p>\n\n<p>Another option that is somewhat easier to newcomers is to use the <a href=\"https://wordpress.org/plugins/all-in-one-wp-migration/\" rel=\"nofollow noreferrer\">All-in-One WP Migration</a>-plugin to make a back-up of your current (production site), then restore the old version on your web-server (overwriting the current site) and then make a back-up using that same plugin of this old version. This will still require you to switch back and forth, but as this plugin saves your files and database in one file, it is much easier to make and restore a back-up. Also, it provides a database search-and-replace option (which is a little more foolproof than the one I linked to earlier), in case you still decide on migrating any version to another domain/server or your localhost.</p>\n"
}
] | 2019/01/20 | [
"https://wordpress.stackexchange.com/questions/326143",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33303/"
] | I got this code:
```
function ntt_movie_shortcode($atts, $content = null)
{
return 'TEST';
}
add_shortcode('ntt_movie', 'ntt_movie_shortcode');
```
The shortcode works perfectly on a single page, but on the Home Page / in excerpts the shortcodes are rendered as an empty string. So, the shortcode gets recognized but it seems, that the function doesn't get processed.
Any hints or approaches?
Thanks in advance. | You can test the site back up by creating a staging site or uploading the backup on your localhost to verify how much work you have done. |
326,172 | <p>I have a simple code where I am attaching existing in the library image to a post:</p>
<pre><code>function attachToPost($attachmentId, $postId){
return wp_update_post(array(
'ID' => (int)$attachmentId,
'post_parent' => (int)$postId
));
}
</code></pre>
<p>The problem is that I can't attach it to a second post.
I read in the internet that this is the way that WordPress works, but is there some kind of solution ?</p>
<p>I don't prefer plugins.</p>
| [
{
"answer_id": 326174,
"author": "Mohsin Ghouri",
"author_id": 159253,
"author_profile": "https://wordpress.stackexchange.com/users/159253",
"pm_score": 1,
"selected": false,
"text": "<p>It is not possible to assign multiple parents to the attachment. However, there is an alternative solution. You can use <code>update_post_meta</code>. to store the attachment id to the post and similarly, you can use function <code>get_post_meta</code>. for getting the attachment id.</p>\n"
},
{
"answer_id": 326572,
"author": "gdfgdfg",
"author_id": 152132,
"author_profile": "https://wordpress.stackexchange.com/users/152132",
"pm_score": 0,
"selected": false,
"text": "<p>What I did was to use <code>set_post_thumbnail( $postId, $attachmentId );</code>. With it, I can have one image attached to many posts.</p>\n"
}
] | 2019/01/20 | [
"https://wordpress.stackexchange.com/questions/326172",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/152132/"
] | I have a simple code where I am attaching existing in the library image to a post:
```
function attachToPost($attachmentId, $postId){
return wp_update_post(array(
'ID' => (int)$attachmentId,
'post_parent' => (int)$postId
));
}
```
The problem is that I can't attach it to a second post.
I read in the internet that this is the way that WordPress works, but is there some kind of solution ?
I don't prefer plugins. | It is not possible to assign multiple parents to the attachment. However, there is an alternative solution. You can use `update_post_meta`. to store the attachment id to the post and similarly, you can use function `get_post_meta`. for getting the attachment id. |
326,211 | <p>How can I show a post featured image by post id in gutenberg editor? I have a slider with latest posts and when I iterate through over posts I would like to show the post featured image as well. Here is my example snippet</p>
<pre><code> const cards = displayPosts.map( ( post, i ) => {
console.log(post.featured_media)
return(<div className="card" key={i}>
<div className="card-image">
<div className="image is-4by3">
<PostFeaturedImage
currentPostId = {post.id}
featuredImageId = {post.featured_media}
/>
<div className="news__post-title">
<div className="title is-5">
<a href={ post.link } target="_blank">{ decodeEntities( post.title.rendered.trim() ) || __( '(Untitled)' ) }</a>
{ displayPostDate && post.date_gmt &&
<time dateTime={ format( 'c', post.date_gmt ) } className="wp-block-latest-posts__post-date">
{ dateI18n( dateFormat, post.date_gmt ) }
</time>
}
</div>
</div>
<div className="card-content">
<div className="content">
<p dangerouslySetInnerHTML={ { __html: post.excerpt.rendered } }></p>
</div>
</div>
</div>
</div>
</div>)
})
</code></pre>
| [
{
"answer_id": 327360,
"author": "moped",
"author_id": 160324,
"author_profile": "https://wordpress.stackexchange.com/users/160324",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same question and tried some ways to get the attachment ID and URL.\nIn fact I got it, but I can't use it, because it's a JSON response and I can't save it in a variable.\nYou can call the API wheter with the parent_post ID with \n<code>{Your-WP-Baseurl}/wp-json/wp/v2/media?parent={Your-Post-ID}</code> \nor by media ID <code>{Your-WP-Baseurl}/wp-json/wp/v2/media/{Yout-Attachment-ID}</code>.</p>\n\n<p>I also tried the wp.data.select('core').getEntityRecord(), but it seems it doesn't work with postType 'attachment', but all other kind of post_type, even custom.\nSo I have no idea what to try next.</p>\n"
},
{
"answer_id": 330779,
"author": "Dror",
"author_id": 162564,
"author_profile": "https://wordpress.stackexchange.com/users/162564",
"pm_score": 1,
"selected": false,
"text": "<p>After facing the same issue, I figured I need a way to fetch the json data and parse it.</p>\n\n<p>Thanks to <a href=\"https://www.robinwieruch.de/react-fetching-data/\" rel=\"nofollow noreferrer\">https://www.robinwieruch.de/react-fetching-data/</a> I figured there is already a fetch() function which I can use.</p>\n\n<p>I guess you would want to fetch the json of the media id, parse it and get the featured image url. you can get additional information of that media (check options by logging the data):</p>\n\n<pre><code> edit: withSelect(function(select) \n {\n return {\n pages: select('core' ).getEntityRecords( 'postType', 'page', { per_page: -1 } )\n };\n })(function(props)\n {\n var featuredmedia = props.pages[0]._links[\"wp:featuredmedia\"][\"0\"].href;\n fetch(featuredmedia)\n .then(response => response.json())\n .then(data => console.log(data.source_url));\n</code></pre>\n\n<p>at the last \"then\", you can set the source_url to some variable instead of logging it to console.</p>\n"
},
{
"answer_id": 339553,
"author": "Jide Arowofela",
"author_id": 169407,
"author_profile": "https://wordpress.stackexchange.com/users/169407",
"pm_score": 3,
"selected": false,
"text": "<p>A simple and effective approach </p>\n\n<pre><code>const editor = wp.data.select('core/editor');\nconst imageId = editor.getEditedPostAttribute('featured_media');\nconst imageObj = wp.data.select('core').getMedia(imageId);\n</code></pre>\n\n<p>ImageObj gives you a reasonable amount of image data to work with. </p>\n"
}
] | 2019/01/21 | [
"https://wordpress.stackexchange.com/questions/326211",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23759/"
] | How can I show a post featured image by post id in gutenberg editor? I have a slider with latest posts and when I iterate through over posts I would like to show the post featured image as well. Here is my example snippet
```
const cards = displayPosts.map( ( post, i ) => {
console.log(post.featured_media)
return(<div className="card" key={i}>
<div className="card-image">
<div className="image is-4by3">
<PostFeaturedImage
currentPostId = {post.id}
featuredImageId = {post.featured_media}
/>
<div className="news__post-title">
<div className="title is-5">
<a href={ post.link } target="_blank">{ decodeEntities( post.title.rendered.trim() ) || __( '(Untitled)' ) }</a>
{ displayPostDate && post.date_gmt &&
<time dateTime={ format( 'c', post.date_gmt ) } className="wp-block-latest-posts__post-date">
{ dateI18n( dateFormat, post.date_gmt ) }
</time>
}
</div>
</div>
<div className="card-content">
<div className="content">
<p dangerouslySetInnerHTML={ { __html: post.excerpt.rendered } }></p>
</div>
</div>
</div>
</div>
</div>)
})
``` | A simple and effective approach
```
const editor = wp.data.select('core/editor');
const imageId = editor.getEditedPostAttribute('featured_media');
const imageObj = wp.data.select('core').getMedia(imageId);
```
ImageObj gives you a reasonable amount of image data to work with. |
326,269 | <pre><code><ul class="nav navbar-nav" id="hover_slip">
<li><a href="index.html">Home</a></li>
<li class="arrow_down"><a href="about.html">About Us</a>
<div class="sub-menu">
<ul>
<li><a href="advisor.html">Advisor</a></li>
<li><a href="single-advisor.html">Single Advisor</a></li>
<li><a href="career.html">Career</a></li>
<li><a href="testimonial.html">Testimonaials</a></li>
<li><a href="partners.html">partners</a></li>
</ul>
</div>
</li>
<li class="arrow_down"><a href="service.html">Services</a>
<div class="sub-menu">
<ul>
<li><a href="service2.html">Service Two</a></li>
<li><a href="pricing-page.html">Pricing Page</a></li>
</ul>
</div>
</li>
</code></pre>
<p></p>
| [
{
"answer_id": 327360,
"author": "moped",
"author_id": 160324,
"author_profile": "https://wordpress.stackexchange.com/users/160324",
"pm_score": 0,
"selected": false,
"text": "<p>I have the same question and tried some ways to get the attachment ID and URL.\nIn fact I got it, but I can't use it, because it's a JSON response and I can't save it in a variable.\nYou can call the API wheter with the parent_post ID with \n<code>{Your-WP-Baseurl}/wp-json/wp/v2/media?parent={Your-Post-ID}</code> \nor by media ID <code>{Your-WP-Baseurl}/wp-json/wp/v2/media/{Yout-Attachment-ID}</code>.</p>\n\n<p>I also tried the wp.data.select('core').getEntityRecord(), but it seems it doesn't work with postType 'attachment', but all other kind of post_type, even custom.\nSo I have no idea what to try next.</p>\n"
},
{
"answer_id": 330779,
"author": "Dror",
"author_id": 162564,
"author_profile": "https://wordpress.stackexchange.com/users/162564",
"pm_score": 1,
"selected": false,
"text": "<p>After facing the same issue, I figured I need a way to fetch the json data and parse it.</p>\n\n<p>Thanks to <a href=\"https://www.robinwieruch.de/react-fetching-data/\" rel=\"nofollow noreferrer\">https://www.robinwieruch.de/react-fetching-data/</a> I figured there is already a fetch() function which I can use.</p>\n\n<p>I guess you would want to fetch the json of the media id, parse it and get the featured image url. you can get additional information of that media (check options by logging the data):</p>\n\n<pre><code> edit: withSelect(function(select) \n {\n return {\n pages: select('core' ).getEntityRecords( 'postType', 'page', { per_page: -1 } )\n };\n })(function(props)\n {\n var featuredmedia = props.pages[0]._links[\"wp:featuredmedia\"][\"0\"].href;\n fetch(featuredmedia)\n .then(response => response.json())\n .then(data => console.log(data.source_url));\n</code></pre>\n\n<p>at the last \"then\", you can set the source_url to some variable instead of logging it to console.</p>\n"
},
{
"answer_id": 339553,
"author": "Jide Arowofela",
"author_id": 169407,
"author_profile": "https://wordpress.stackexchange.com/users/169407",
"pm_score": 3,
"selected": false,
"text": "<p>A simple and effective approach </p>\n\n<pre><code>const editor = wp.data.select('core/editor');\nconst imageId = editor.getEditedPostAttribute('featured_media');\nconst imageObj = wp.data.select('core').getMedia(imageId);\n</code></pre>\n\n<p>ImageObj gives you a reasonable amount of image data to work with. </p>\n"
}
] | 2019/01/21 | [
"https://wordpress.stackexchange.com/questions/326269",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159534/"
] | ```
<ul class="nav navbar-nav" id="hover_slip">
<li><a href="index.html">Home</a></li>
<li class="arrow_down"><a href="about.html">About Us</a>
<div class="sub-menu">
<ul>
<li><a href="advisor.html">Advisor</a></li>
<li><a href="single-advisor.html">Single Advisor</a></li>
<li><a href="career.html">Career</a></li>
<li><a href="testimonial.html">Testimonaials</a></li>
<li><a href="partners.html">partners</a></li>
</ul>
</div>
</li>
<li class="arrow_down"><a href="service.html">Services</a>
<div class="sub-menu">
<ul>
<li><a href="service2.html">Service Two</a></li>
<li><a href="pricing-page.html">Pricing Page</a></li>
</ul>
</div>
</li>
``` | A simple and effective approach
```
const editor = wp.data.select('core/editor');
const imageId = editor.getEditedPostAttribute('featured_media');
const imageObj = wp.data.select('core').getMedia(imageId);
```
ImageObj gives you a reasonable amount of image data to work with. |
326,276 | <p>Many times I have code and I want to make sure it only runs in a rest api context, or it never runs in a rest context.</p>
<p>I know there are some hooks, but is there a function similar to <code>wp_is_doing_cron</code>?</p>
| [
{
"answer_id": 326277,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, <code>wp_is_json_request()</code> can be used to determine if the current request is a REST API request</p>\n\n<blockquote>\n <p>Checks whether current request is a JSON request, or is expecting a JSON response.</p>\n \n <p><em>Official docs: <a href=\"https://developer.wordpress.org/reference/functions/wp_is_json_request/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/wp_is_json_request/</a></em></p>\n</blockquote>\n"
},
{
"answer_id": 326947,
"author": "Pabamato",
"author_id": 60079,
"author_profile": "https://wordpress.stackexchange.com/users/60079",
"pm_score": 3,
"selected": true,
"text": "<p>I would use :</p>\n<pre><code>if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {...}\n</code></pre>\n<p>Source: <a href=\"https://github.com/WP-API/WP-API/issues/926#issuecomment-162920686\" rel=\"nofollow noreferrer\">https://github.com/WP-API/WP-API/issues/926#issuecomment-162920686</a></p>\n<p>If you take a look to <a href=\"https://github.com/WordPress/WordPress/blob/5f62cd1566d27be22d961c2a9af31f077efdecf7/wp-includes/rest-api.php#L329\" rel=\"nofollow noreferrer\">this source code</a> on you will notice the constant is defined before processing anything, I would check for it instead of calling the mentioned function <code>wp_is_json_request()</code></p>\n<p>Why?<br />\nif headers were not set when you do the check, it will return false, here is a real example reported for a GET request: <a href=\"https://github.com/WordPress/gutenberg/issues/11327\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/issues/11327</a></p>\n"
}
] | 2019/01/21 | [
"https://wordpress.stackexchange.com/questions/326276",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/736/"
] | Many times I have code and I want to make sure it only runs in a rest api context, or it never runs in a rest context.
I know there are some hooks, but is there a function similar to `wp_is_doing_cron`? | I would use :
```
if ( defined( 'REST_REQUEST' ) && REST_REQUEST ) {...}
```
Source: <https://github.com/WP-API/WP-API/issues/926#issuecomment-162920686>
If you take a look to [this source code](https://github.com/WordPress/WordPress/blob/5f62cd1566d27be22d961c2a9af31f077efdecf7/wp-includes/rest-api.php#L329) on you will notice the constant is defined before processing anything, I would check for it instead of calling the mentioned function `wp_is_json_request()`
Why?
if headers were not set when you do the check, it will return false, here is a real example reported for a GET request: <https://github.com/WordPress/gutenberg/issues/11327> |
326,335 | <p>I'm trying to figure out a way, to create a Gutenberg sidebar that is only visible on a custom post type.</p>
<p>For instance, I'd like my sidebar with settings, like a custom checkbox, only related to pages, to be inaccessible on my custom post types.</p>
<p>Instead of creating a sidebar for a specific post type, it would also be great to remove a sidebar from a specific post type.</p>
<p>I couldn't yet find any way to accomplish that, any ideas?</p>
| [
{
"answer_id": 336444,
"author": "Ahrengot",
"author_id": 23829,
"author_profile": "https://wordpress.stackexchange.com/users/23829",
"pm_score": 4,
"selected": true,
"text": "<p>I know this question is a few months old by now, but I got around this issue using the following code and thought it might be helpful for others. There might be a better way, but this works:</p>\n\n<pre><code>import ColorSchemeSelect from \"./components/color-scheme-select\";\nimport includes from \"lodash/includes\";\n\nconst { select } = wp.data;\nconst { registerPlugin } = wp.plugins;\nconst { PluginSidebar } = wp.editPost;\n\nregisterPlugin('ahr-sidebar-post-options', {\n render() {\n const postType = select(\"core/editor\").getCurrentPostType();\n if ( !includes([\"post\", \"page\"], postType) ) {\n return null;\n }\n\n return (\n <PluginSidebar name=\"ahr-sidebar-post-options\" icon=\"admin-customizer\" title=\"Color settings\">\n <div style={{ padding: 16 }}>\n <ColorSchemeSelect />\n </div>\n </PluginSidebar>\n );\n },\n});\n</code></pre>\n\n<p>In my example I only wanted to show a certain sidebar for posts and pages, so I'm using <code>!includes([\"post\", \"page\"], postType)</code> to test wheter or not the sidebar should be shown. If you only want it for one specific post type you'd just go <code>postType === \"my-post-type\"</code> instead.</p>\n"
},
{
"answer_id": 351784,
"author": "a_zero",
"author_id": 177774,
"author_profile": "https://wordpress.stackexchange.com/users/177774",
"pm_score": 0,
"selected": false,
"text": "<p>To add a sidebar to a custom post type, just add the sidebar after the condition:</p>\n\n<pre><code>class SidebarRender extends Component {\n [...]\n}\n\nvar postType = select(\"core/editor\").getCurrentPostType();\nif (postType === \"my_post_type\")\n registerPlugin(\"my-sidebar\", {\n icon: \"excerpt-view\",\n render: SidebarRender\n});\n</code></pre>\n"
},
{
"answer_id": 357326,
"author": "Kuuak",
"author_id": 86838,
"author_profile": "https://wordpress.stackexchange.com/users/86838",
"pm_score": 0,
"selected": false,
"text": "<p>The solution is to wait until dom is ready before to get the current post type. \nIf you don't wait, the selector will return <code>null</code></p>\n\n<pre><code>import domReady from '@wordpress/dom-ready';\nimport { Component } from '@wordpress/element';\nimport { select } from '@wordpress/data';\n\nclass MySidebarPlugin extends Component {\n [...]\n}\n\ndomReady(() => {\n if (select('core/editor').getCurrentPostType() !== 'post') return;\n\n registerPlugin('my-sidebar-plugin', {\n icon: 'admin-plugins',\n render: MySidebarPlugin,\n });\n});\n</code></pre>\n"
}
] | 2019/01/22 | [
"https://wordpress.stackexchange.com/questions/326335",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/151781/"
] | I'm trying to figure out a way, to create a Gutenberg sidebar that is only visible on a custom post type.
For instance, I'd like my sidebar with settings, like a custom checkbox, only related to pages, to be inaccessible on my custom post types.
Instead of creating a sidebar for a specific post type, it would also be great to remove a sidebar from a specific post type.
I couldn't yet find any way to accomplish that, any ideas? | I know this question is a few months old by now, but I got around this issue using the following code and thought it might be helpful for others. There might be a better way, but this works:
```
import ColorSchemeSelect from "./components/color-scheme-select";
import includes from "lodash/includes";
const { select } = wp.data;
const { registerPlugin } = wp.plugins;
const { PluginSidebar } = wp.editPost;
registerPlugin('ahr-sidebar-post-options', {
render() {
const postType = select("core/editor").getCurrentPostType();
if ( !includes(["post", "page"], postType) ) {
return null;
}
return (
<PluginSidebar name="ahr-sidebar-post-options" icon="admin-customizer" title="Color settings">
<div style={{ padding: 16 }}>
<ColorSchemeSelect />
</div>
</PluginSidebar>
);
},
});
```
In my example I only wanted to show a certain sidebar for posts and pages, so I'm using `!includes(["post", "page"], postType)` to test wheter or not the sidebar should be shown. If you only want it for one specific post type you'd just go `postType === "my-post-type"` instead. |
326,345 | <p>I just have installed xampp with php 7.3.1 on mac with OS El capitan. </p>
<p>The problem that when i run a WordPress project will show:</p>
<blockquote>
<p>Warning: preg_replace(): JIT compilation failed: no more memory in
/Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/formatting.php
on line 2110 Warning: preg_match(): JIT compilation failed: no more
memory in
/Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
on line 4947 Warning: preg_replace(): JIT compilation failed: no more
memory in
/Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
on line 4843 Warning: preg_match(): JIT compilation failed: no more
memory in
/Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
on line 4947 Warning: preg_match(): JIT compilation failed: no more
memory in
/Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
on line 4947</p>
</blockquote>
| [
{
"answer_id": 327568,
"author": "Michael Parkinson",
"author_id": 145000,
"author_profile": "https://wordpress.stackexchange.com/users/145000",
"pm_score": 3,
"selected": false,
"text": "<p>I added the following line to the <code>php.ini</code> and restarted Apache and it worked (Xampp on macOS):</p>\n\n<pre><code>pcre.jit=0\n</code></pre>\n\n<p>This disables PCRE's just-in-time compilation.</p>\n\n<p>Further information:</p>\n\n<ul>\n<li><a href=\"http://php.net/manual/en/pcre.configuration.php#ini.pcre.jit\" rel=\"noreferrer\">http://php.net/manual/en/pcre.configuration.php#ini.pcre.jit</a> </li>\n</ul>\n\n<p>If you can't find the location of <code>php.ini</code> and are using Xampp, go to localhost and select the PHP information link and it is displayed there.</p>\n"
},
{
"answer_id": 345487,
"author": "Oleksandr",
"author_id": 173805,
"author_profile": "https://wordpress.stackexchange.com/users/173805",
"pm_score": 0,
"selected": false,
"text": "<p>You need downgrade your php7.3 to php7.1 version. I have the same problem when trying to change php version to the upper. </p>\n"
}
] | 2019/01/22 | [
"https://wordpress.stackexchange.com/questions/326345",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/158614/"
] | I just have installed xampp with php 7.3.1 on mac with OS El capitan.
The problem that when i run a WordPress project will show:
>
> Warning: preg\_replace(): JIT compilation failed: no more memory in
> /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/formatting.php
> on line 2110 Warning: preg\_match(): JIT compilation failed: no more
> memory in
> /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
> on line 4947 Warning: preg\_replace(): JIT compilation failed: no more
> memory in
> /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
> on line 4843 Warning: preg\_match(): JIT compilation failed: no more
> memory in
> /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
> on line 4947 Warning: preg\_match(): JIT compilation failed: no more
> memory in
> /Applications/XAMPP/xamppfiles/htdocs/wordpress/wp-includes/functions.php
> on line 4947
>
>
> | I added the following line to the `php.ini` and restarted Apache and it worked (Xampp on macOS):
```
pcre.jit=0
```
This disables PCRE's just-in-time compilation.
Further information:
* <http://php.net/manual/en/pcre.configuration.php#ini.pcre.jit>
If you can't find the location of `php.ini` and are using Xampp, go to localhost and select the PHP information link and it is displayed there. |
326,375 | <p>My website:<a href="http://up8.431.myftpupload.com/" rel="nofollow noreferrer">http://up8.431.myftpupload.com/</a></p>
<p>I recently changed the words under We Serve under the main image to links. After I did that, when I hovered over them they changed to the background color that they are in. I would like them to change to blue when I hover over them.</p>
<p>In the scrrenshot I have up the styling of the links but am hovered over the title, which happens to be an H2 tag. I used some custom css to get them to change to blue when I hover over them . Problem is, the whole page gets that same styling applied and it makes no sense to me. I put the custom css specifically just for that section of text. </p>
<p>Feel free to go to the page as well and see how everything on the page gets the same :hover effect applied. I suspect it's because I used just :hover with nothing before it so therefore it get's applied to everything.</p>
<p>Other things I've tried:
1. Using this:hover - did nothing
2. Using a:hover - made all links on the page have same hover effect
3. Giving that section of text a CSSID and class and applying styling thru the customizer Custom CSS/JS - did nothing... didn't even work</p>
<p><a href="https://i.stack.imgur.com/rGsBx.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/rGsBx.png" alt="enter image description here"></a></p>
<p>Any help would be appreciated. I think I understand what's going on. I just don't know how to fix it. Thx in advance </p>
| [
{
"answer_id": 326379,
"author": "RiddleMeThis",
"author_id": 86845,
"author_profile": "https://wordpress.stackexchange.com/users/86845",
"pm_score": -1,
"selected": true,
"text": "<p>Replace the style you added with the following.</p>\n\n<pre><code>.elementor-element-1fc9820 a:hover {\n color:blue !important;\n}\n</code></pre>\n\n<p>You needed to be more specific with your rule. Since there is a elementor class around those links I just used that class.</p>\n\n<p>Note: Your #3 solution should have worked so apparently you made a mistake when you attempted it.</p>\n"
},
{
"answer_id": 358561,
"author": "gromek",
"author_id": 182657,
"author_profile": "https://wordpress.stackexchange.com/users/182657",
"pm_score": 0,
"selected": false,
"text": "<p>I actually don't think you should need to specify an added rule with something like \".elementor-element-1fc9820\" to limit it to the very element you're editing (although it won't hurt, I guess).</p>\n\n<p>The custom css that Elementor Pro is offering you to add when editing a certain element on the page should already be targeted at just that element (or a child element therein). It just doesn't make any sense otherwise, I'd say.</p>\n\n<p>However, I think it's just the \"a\" before the colon that was missing so that actually anything – a, h2, h3, p, whatever – within that element got highlighted when you hovered over it. The hover property is not restricted to just anchors/links as far as I know.</p>\n\n<p>a:hover {\n color:blue !important;\n}</p>\n\n<p>should do the trick without the \".elementor-element-1fc9820\".</p>\n"
}
] | 2019/01/22 | [
"https://wordpress.stackexchange.com/questions/326375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159272/"
] | My website:<http://up8.431.myftpupload.com/>
I recently changed the words under We Serve under the main image to links. After I did that, when I hovered over them they changed to the background color that they are in. I would like them to change to blue when I hover over them.
In the scrrenshot I have up the styling of the links but am hovered over the title, which happens to be an H2 tag. I used some custom css to get them to change to blue when I hover over them . Problem is, the whole page gets that same styling applied and it makes no sense to me. I put the custom css specifically just for that section of text.
Feel free to go to the page as well and see how everything on the page gets the same :hover effect applied. I suspect it's because I used just :hover with nothing before it so therefore it get's applied to everything.
Other things I've tried:
1. Using this:hover - did nothing
2. Using a:hover - made all links on the page have same hover effect
3. Giving that section of text a CSSID and class and applying styling thru the customizer Custom CSS/JS - did nothing... didn't even work
[](https://i.stack.imgur.com/rGsBx.png)
Any help would be appreciated. I think I understand what's going on. I just don't know how to fix it. Thx in advance | Replace the style you added with the following.
```
.elementor-element-1fc9820 a:hover {
color:blue !important;
}
```
You needed to be more specific with your rule. Since there is a elementor class around those links I just used that class.
Note: Your #3 solution should have worked so apparently you made a mistake when you attempted it. |
326,387 | <p>Basically what I'm asking is, is <code>wp_ajax_nopriv</code> exclusive to non-logged-in users?</p>
<p>Will a <code>wp_ajax_nopriv</code> action fire if a user is logged in?</p>
| [
{
"answer_id": 326389,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 4,
"selected": true,
"text": "<p>Looking at <a href=\"https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-admin/admin-ajax.php#L114\" rel=\"noreferrer\">the WordPress source code</a>, I'd say that <code>wp_ajax_nopriv_*</code> fires <em>only</em> if you're not logged in, and <code>wp_ajax_*</code> fires otherwise.</p>\n\n<p>Here's the relevant bit, in <code>admin-ajax.php</code>, lines 85-115 in version 5.0.3:</p>\n\n<pre><code>if ( is_user_logged_in() ) {\n // If no action is registered, return a Bad Request response.\n if ( ! has_action( 'wp_ajax_' . $_REQUEST['action'] ) ) {\n wp_die( '0', 400 );\n }\n\n /**\n * Fires authenticated Ajax actions for logged-in users.\n *\n * The dynamic portion of the hook name, `$_REQUEST['action']`,\n * refers to the name of the Ajax action callback being fired.\n *\n * @since 2.1.0\n */\n do_action( 'wp_ajax_' . $_REQUEST['action'] );\n} else {\n // If no action is registered, return a Bad Request response.\n if ( ! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ) ) {\n wp_die( '0', 400 );\n }\n\n /**\n * Fires non-authenticated Ajax actions for logged-out users.\n *\n * The dynamic portion of the hook name, `$_REQUEST['action']`,\n * refers to the name of the Ajax action callback being fired.\n *\n * @since 2.8.0\n */\n do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );\n}\n</code></pre>\n\n<p>So, if you're logged in (ie, <code>is_user_logged_in()</code> is <code>true</code>), it runs the <code>wp_ajax_*</code> action(s), otherwise it runs the <code>wp_ajax_nopriv_*</code> actions.</p>\n\n<p>If you want the same action run regardless whether your user is logged in or not, I'd recommend you hook to <strong>both</strong> <code>wp_ajax_*</code> and <code>wp_ajax_nopriv_*</code>.</p>\n"
},
{
"answer_id": 326390,
"author": "Kashif Rafique",
"author_id": 60139,
"author_profile": "https://wordpress.stackexchange.com/users/60139",
"pm_score": 2,
"selected": false,
"text": "<p>As per <code>wp_ajax_(action)</code> <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_nopriv_(action)\" rel=\"nofollow noreferrer\">codex</a>:</p>\n\n<blockquote>\n <p>This hook is functionally the same as <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_ajax_(action)\" rel=\"nofollow noreferrer\"><code>wp_ajax_(action)</code></a>, except the\n \"nopriv\" variant is used for handling AJAX requests from\n unauthenticated users, i.e. when <a href=\"https://codex.wordpress.org/Function_Reference/is_user_logged_in\" rel=\"nofollow noreferrer\"><code>is_user_logged_in()</code></a> returns false.</p>\n</blockquote>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/is_user_logged_in/\" rel=\"nofollow noreferrer\"><code>is_user_logged_in()</code></a> determines whether the current visitor is a logged in user. It will return <code>true</code> if user is logged in, <code>false</code> if not logged in.</p>\n"
}
] | 2019/01/22 | [
"https://wordpress.stackexchange.com/questions/326387",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22588/"
] | Basically what I'm asking is, is `wp_ajax_nopriv` exclusive to non-logged-in users?
Will a `wp_ajax_nopriv` action fire if a user is logged in? | Looking at [the WordPress source code](https://core.trac.wordpress.org/browser/tags/5.0.3/src/wp-admin/admin-ajax.php#L114), I'd say that `wp_ajax_nopriv_*` fires *only* if you're not logged in, and `wp_ajax_*` fires otherwise.
Here's the relevant bit, in `admin-ajax.php`, lines 85-115 in version 5.0.3:
```
if ( is_user_logged_in() ) {
// If no action is registered, return a Bad Request response.
if ( ! has_action( 'wp_ajax_' . $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
/**
* Fires authenticated Ajax actions for logged-in users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the Ajax action callback being fired.
*
* @since 2.1.0
*/
do_action( 'wp_ajax_' . $_REQUEST['action'] );
} else {
// If no action is registered, return a Bad Request response.
if ( ! has_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] ) ) {
wp_die( '0', 400 );
}
/**
* Fires non-authenticated Ajax actions for logged-out users.
*
* The dynamic portion of the hook name, `$_REQUEST['action']`,
* refers to the name of the Ajax action callback being fired.
*
* @since 2.8.0
*/
do_action( 'wp_ajax_nopriv_' . $_REQUEST['action'] );
}
```
So, if you're logged in (ie, `is_user_logged_in()` is `true`), it runs the `wp_ajax_*` action(s), otherwise it runs the `wp_ajax_nopriv_*` actions.
If you want the same action run regardless whether your user is logged in or not, I'd recommend you hook to **both** `wp_ajax_*` and `wp_ajax_nopriv_*`. |
326,399 | <p>I am working with the onClick action on a custom IconButton like so:</p>
<pre><code>const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { BlockControls } = wp.editor;
const { Toolbar } = wp.components;
const { IconButton } = wp.components;
const withCollapseControl = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) =>
{
props.toggleBlockCollapse = (event) => {
props.setAttributes({
collapsed:!props.attributes.collapsed,
}
let iconProps = {
onClick: props.toggleBlockCollapse.bind(props),
class: "components-icon-button components-toolbar__control",
label: props.attributes.collapsed ? 'Collapse' : 'Expand',
icon: props.attributes.collapsed ? 'arrow-down' : 'arrow-up'
}
return (
<Fragment>
<BlockEdit { ...props } className='collapsed'/>
<BlockControls>
<Toolbar>
<IconButton { ...iconProps } />
</Toolbar>
</BlockControls>
</Fragment>
);
};
}, "withCollapseControl" );
wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withCollapseControl );
</code></pre>
<p>I seem to be unable to add/ remove an HTML/ CSS class to the BlockEdit component. I am able to toggle the icon button, and my call to setAttributes triggers re-render...</p>
<p>I was hoping I could mimic the example in the accepted answer here, but on my BlockEdit component: <a href="https://wordpress.stackexchange.com/questions/324091/add-classname-to-gutenberg-block-wrapper-in-the-editor">Add classname to Gutenberg block wrapper in the editor?</a></p>
<p>After taking a deeper look, it appears that className may not be overrideable on the BlockEdit component the way it is on the BlockListBlock component.</p>
<p>Perhaps the best approach would be to try to modify the class of the BlockListBlock component, but I am not certain how I would go about linking those together, so possibly looking for a solution in that vein.</p>
<p>Thanks!</p>
<p>Edit: Please note I have hardcoded in a value for the className in the example BlockEdit component, to demonstrate where things fail ( adding classname ) independent of the other logic in the code. The entirety of the code is shared to help provide answerers with some broader context and my intent :)</p>
| [
{
"answer_id": 326465,
"author": "criticalWP",
"author_id": 159617,
"author_profile": "https://wordpress.stackexchange.com/users/159617",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to solve this by wrapping the BlockEdit component in my own markup:</p>\n\n<pre><code> <Fragment>\n <div className=\"customClass\">\n <BlockEdit { ...props }/>\n <div>\n <BlockControls>\n <Toolbar>\n <IconButton { ...iconProps } />\n </Toolbar>\n </BlockControls>\n </Fragment>\n</code></pre>\n"
},
{
"answer_id": 334364,
"author": "Félicette",
"author_id": 165066,
"author_profile": "https://wordpress.stackexchange.com/users/165066",
"pm_score": 2,
"selected": false,
"text": "<p>In this specific situation (using the editor.BlockEdit filter), the className is actually an attribute. So right after you set your 'collapsed' attribute, you can also set the className:</p>\n\n<pre><code> props.setAttributes({\n collapsed:!props.attributes.collapsed,\n className: 'myClass'\n });\n</code></pre>\n\n<p>This originally surprised me, but here is how it's used in the source:</p>\n\n<pre><code>// Generate a class name for the block's editable form\nconst generatedClassName = hasBlockSupport( blockType, 'className', true ) ?\n getBlockDefaultClassName( name ) : null;\nconst className = classnames( generatedClassName, attributes.className );\n</code></pre>\n\n<p>from <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/block-edit/edit.js\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/block-edit/edit.js</a></p>\n"
},
{
"answer_id": 404080,
"author": "Steve de Niese",
"author_id": 26743,
"author_profile": "https://wordpress.stackexchange.com/users/26743",
"pm_score": 0,
"selected": false,
"text": "<p>Spent a few hours today trying to crack this one. The solution is to use the filter: <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blocklistblock\" rel=\"nofollow noreferrer\">editor.BlockListBlock</a>.</p>\n<p>The usage example from the docs:</p>\n<pre><code>const { createHigherOrderComponent } = wp.compose;\n \nconst withClientIdClassName = createHigherOrderComponent(\n ( BlockListBlock ) => {\n return ( props ) => {\n return (\n <BlockListBlock\n { ...props }\n className={ 'block-' + props.clientId }\n />\n );\n };\n },\n 'withClientIdClassName'\n);\n \nwp.hooks.addFilter(\n 'editor.BlockListBlock',\n 'my-plugin/with-client-id-class-name',\n withClientIdClassName\n);\n</code></pre>\n<p>I believe the problem with <code>editor.BlockEdit</code> is that it gets overriden by <a href=\"https://github.com/WordPress/gutenberg/blob/trunk/packages/block-editor/src/components/block-edit/edit.js\" rel=\"nofollow noreferrer\">this component</a>. There's a <a href=\"https://github.com/WordPress/gutenberg/issues/20849\" rel=\"nofollow noreferrer\">github issue addresing this problem here</a>.</p>\n"
}
] | 2019/01/23 | [
"https://wordpress.stackexchange.com/questions/326399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159617/"
] | I am working with the onClick action on a custom IconButton like so:
```
const { createHigherOrderComponent } = wp.compose;
const { Fragment } = wp.element;
const { BlockControls } = wp.editor;
const { Toolbar } = wp.components;
const { IconButton } = wp.components;
const withCollapseControl = createHigherOrderComponent( ( BlockEdit ) => {
return ( props ) =>
{
props.toggleBlockCollapse = (event) => {
props.setAttributes({
collapsed:!props.attributes.collapsed,
}
let iconProps = {
onClick: props.toggleBlockCollapse.bind(props),
class: "components-icon-button components-toolbar__control",
label: props.attributes.collapsed ? 'Collapse' : 'Expand',
icon: props.attributes.collapsed ? 'arrow-down' : 'arrow-up'
}
return (
<Fragment>
<BlockEdit { ...props } className='collapsed'/>
<BlockControls>
<Toolbar>
<IconButton { ...iconProps } />
</Toolbar>
</BlockControls>
</Fragment>
);
};
}, "withCollapseControl" );
wp.hooks.addFilter( 'editor.BlockEdit', 'my-plugin/with-inspector-controls', withCollapseControl );
```
I seem to be unable to add/ remove an HTML/ CSS class to the BlockEdit component. I am able to toggle the icon button, and my call to setAttributes triggers re-render...
I was hoping I could mimic the example in the accepted answer here, but on my BlockEdit component: [Add classname to Gutenberg block wrapper in the editor?](https://wordpress.stackexchange.com/questions/324091/add-classname-to-gutenberg-block-wrapper-in-the-editor)
After taking a deeper look, it appears that className may not be overrideable on the BlockEdit component the way it is on the BlockListBlock component.
Perhaps the best approach would be to try to modify the class of the BlockListBlock component, but I am not certain how I would go about linking those together, so possibly looking for a solution in that vein.
Thanks!
Edit: Please note I have hardcoded in a value for the className in the example BlockEdit component, to demonstrate where things fail ( adding classname ) independent of the other logic in the code. The entirety of the code is shared to help provide answerers with some broader context and my intent :) | I was able to solve this by wrapping the BlockEdit component in my own markup:
```
<Fragment>
<div className="customClass">
<BlockEdit { ...props }/>
<div>
<BlockControls>
<Toolbar>
<IconButton { ...iconProps } />
</Toolbar>
</BlockControls>
</Fragment>
``` |
326,417 | <p>On a virtual private server machine (Ubuntu 16.04) which I self-host on DigitalOcean I use an all-default and latest <em>Debian</em> stable with all-default and latest <em>Apache</em>, <em>MySQL</em> and <em>PHP</em> to host my WordPress websites.</p>
<p>Port 25 is unfiltered.</p>
<p>None of the WordPresses is on debug mode.</p>
<p>Each Wordpress website contains one simple contact form (CF7) with <em>name</em>, <em>email</em>, <em>phone</em> and <em>body</em> fields. All latest.</p>
<h2>My problem</h2>
<p>I declared my personal email account for all websites contact-form <strong>plugin</strong> and ought to test the forms but in testing them with some input and clicking <em>submit</em> I got this general error:</p>
<blockquote>
<p>Failed to send your message</p>
</blockquote>
<p>I didn't manage to find further data as to why I had this error - any log I checked showed nothing on this.</p>
<p>Reading on this I concluded I need an <strong>email proxy</strong> by a <strong>second email account</strong>, but this approach requires me to manage another email account with username and password which I don't want if I don't have to.</p>
<h2>My need</h2>
<p>I desire to transfer all contact-form inputs <em>from my machine → into my personal email account</em>, but without using an email-proxy like a third email account that will mediate between each CMS and my personal email account.</p>
<p>How can I transfer contact-form inputs into my personal email account <strong>without using an email-proxy</strong>, in the above stack?</p>
| [
{
"answer_id": 326465,
"author": "criticalWP",
"author_id": 159617,
"author_profile": "https://wordpress.stackexchange.com/users/159617",
"pm_score": 2,
"selected": false,
"text": "<p>I was able to solve this by wrapping the BlockEdit component in my own markup:</p>\n\n<pre><code> <Fragment>\n <div className=\"customClass\">\n <BlockEdit { ...props }/>\n <div>\n <BlockControls>\n <Toolbar>\n <IconButton { ...iconProps } />\n </Toolbar>\n </BlockControls>\n </Fragment>\n</code></pre>\n"
},
{
"answer_id": 334364,
"author": "Félicette",
"author_id": 165066,
"author_profile": "https://wordpress.stackexchange.com/users/165066",
"pm_score": 2,
"selected": false,
"text": "<p>In this specific situation (using the editor.BlockEdit filter), the className is actually an attribute. So right after you set your 'collapsed' attribute, you can also set the className:</p>\n\n<pre><code> props.setAttributes({\n collapsed:!props.attributes.collapsed,\n className: 'myClass'\n });\n</code></pre>\n\n<p>This originally surprised me, but here is how it's used in the source:</p>\n\n<pre><code>// Generate a class name for the block's editable form\nconst generatedClassName = hasBlockSupport( blockType, 'className', true ) ?\n getBlockDefaultClassName( name ) : null;\nconst className = classnames( generatedClassName, attributes.className );\n</code></pre>\n\n<p>from <a href=\"https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/block-edit/edit.js\" rel=\"nofollow noreferrer\">https://github.com/WordPress/gutenberg/blob/master/packages/block-editor/src/components/block-edit/edit.js</a></p>\n"
},
{
"answer_id": 404080,
"author": "Steve de Niese",
"author_id": 26743,
"author_profile": "https://wordpress.stackexchange.com/users/26743",
"pm_score": 0,
"selected": false,
"text": "<p>Spent a few hours today trying to crack this one. The solution is to use the filter: <a href=\"https://developer.wordpress.org/block-editor/reference-guides/filters/block-filters/#editor-blocklistblock\" rel=\"nofollow noreferrer\">editor.BlockListBlock</a>.</p>\n<p>The usage example from the docs:</p>\n<pre><code>const { createHigherOrderComponent } = wp.compose;\n \nconst withClientIdClassName = createHigherOrderComponent(\n ( BlockListBlock ) => {\n return ( props ) => {\n return (\n <BlockListBlock\n { ...props }\n className={ 'block-' + props.clientId }\n />\n );\n };\n },\n 'withClientIdClassName'\n);\n \nwp.hooks.addFilter(\n 'editor.BlockListBlock',\n 'my-plugin/with-client-id-class-name',\n withClientIdClassName\n);\n</code></pre>\n<p>I believe the problem with <code>editor.BlockEdit</code> is that it gets overriden by <a href=\"https://github.com/WordPress/gutenberg/blob/trunk/packages/block-editor/src/components/block-edit/edit.js\" rel=\"nofollow noreferrer\">this component</a>. There's a <a href=\"https://github.com/WordPress/gutenberg/issues/20849\" rel=\"nofollow noreferrer\">github issue addresing this problem here</a>.</p>\n"
}
] | 2019/01/23 | [
"https://wordpress.stackexchange.com/questions/326417",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] | On a virtual private server machine (Ubuntu 16.04) which I self-host on DigitalOcean I use an all-default and latest *Debian* stable with all-default and latest *Apache*, *MySQL* and *PHP* to host my WordPress websites.
Port 25 is unfiltered.
None of the WordPresses is on debug mode.
Each Wordpress website contains one simple contact form (CF7) with *name*, *email*, *phone* and *body* fields. All latest.
My problem
----------
I declared my personal email account for all websites contact-form **plugin** and ought to test the forms but in testing them with some input and clicking *submit* I got this general error:
>
> Failed to send your message
>
>
>
I didn't manage to find further data as to why I had this error - any log I checked showed nothing on this.
Reading on this I concluded I need an **email proxy** by a **second email account**, but this approach requires me to manage another email account with username and password which I don't want if I don't have to.
My need
-------
I desire to transfer all contact-form inputs *from my machine → into my personal email account*, but without using an email-proxy like a third email account that will mediate between each CMS and my personal email account.
How can I transfer contact-form inputs into my personal email account **without using an email-proxy**, in the above stack? | I was able to solve this by wrapping the BlockEdit component in my own markup:
```
<Fragment>
<div className="customClass">
<BlockEdit { ...props }/>
<div>
<BlockControls>
<Toolbar>
<IconButton { ...iconProps } />
</Toolbar>
</BlockControls>
</Fragment>
``` |
326,461 | <p>I am creating a plugin with custom gutenberg blocks.</p>
<p>Each block has a styles.scss file. If I add code to this file, the block is styled in both the back end and front end, as expected per the docs.</p>
<p>For example, in a block "section" I want to style the background color only on the back end:</p>
<pre><code>.wp-block-pbdsblocks-section {
background-color: #e0e0e0;
padding: 10px;
}
</code></pre>
<p>But this affects both front and back end. The articles I've been reading say to apply the style by creating an "editor.scss" file in the block directory.</p>
<p>I import the editor.scss file into the block's index.js.</p>
<p>I can see my code in this file being compiled and added to <code>/assets/css/blocks.style.css</code></p>
<p>I have the plugins' php file set to enqueue it:</p>
<pre><code>/**
* Enqueue block editor only JavaScript and CSS
*/
function pbdsblocks_editor_scripts()
{
// Make paths variables so we don't write em twice ;)
$blockPath = '/assets/js/editor.blocks.js';
$editorStylePath = '/assets/css/blocks.editor.css';
// Enqueue the bundled block JS file
wp_enqueue_script(
'pbdsblocks-blocks-js',
plugins_url( $blockPath, __FILE__ ),
[ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-api', 'wp-editor' ],
filemtime( plugin_dir_path(__FILE__) . $blockPath )
);
// Enqueue optional editor only styles
wp_enqueue_style(
'pbdsblocks-blocks-editor-css',
plugins_url( $editorStylePath, __FILE__),
[ 'wp-blocks' ],
filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )
);
}
// Hook scripts function into block editor hook
add_action( 'enqueue_block_editor_assets', 'pbdsblocks_editor_scripts' );
</code></pre>
<p>But the styles only take affect if they're in the <code>style.scss</code> file. Which affects front end and back end.</p>
| [
{
"answer_id": 326477,
"author": "Steve",
"author_id": 23610,
"author_profile": "https://wordpress.stackexchange.com/users/23610",
"pm_score": 1,
"selected": false,
"text": "<p>FWIW, there was an error in the <code>wp_enqueue_style</code> function I received. This one works fine:</p>\n\n<pre><code> // Enqueue optional editor only styles\n wp_enqueue_style(\n 'pbdsblocks-blocks-editor-css',\n plugins_url( $editorStylePath, __FILE__),\n [ ],\n filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )\n );\n</code></pre>\n\n<p>Note the third argument has changed to <code>[ ]</code> from <code>['wp-blocks']</code></p>\n"
},
{
"answer_id": 326520,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 0,
"selected": false,
"text": "<p>You need two different stylesheet for a block. One for front end and one for back end.\nHere's what I suggest you to follow. I've taken this code from <a href=\"https://github.com/ahmadawais/create-guten-block/blob/master/examples/01-single-block/src/init.php\" rel=\"nofollow noreferrer\">create-guten-block</a></p>\n\n<pre><code> /**\n * Enqueue Gutenberg block assets for both frontend + backend.\n *\n * @uses {wp-editor} for WP editor styles.\n * @since 1.0.0\n */\nfunction single_block_cgb_block_assets() {\n // Styles.\n wp_enqueue_style(\n 'single_block-cgb-style-css', // Handle.\n plugins_url( 'dist/blocks.style.build.css', dirname( __FILE__ ) ), // Block style CSS.\n array( 'wp-editor' ) // Dependency to include the CSS after it.\n // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.style.build.css' ) // Version: File modification time.\n );\n}\n// Hook: Frontend assets.\nadd_action( 'enqueue_block_assets', 'single_block_cgb_block_assets' );\n/**\n * Enqueue Gutenberg block assets for backend editor.\n *\n * @uses {wp-blocks} for block type registration & related functions.\n * @uses {wp-element} for WP Element abstraction — structure of blocks.\n * @uses {wp-i18n} to internationalize the block's text.\n * @uses {wp-editor} for WP editor styles.\n * @since 1.0.0\n */\nfunction single_block_cgb_editor_assets() {\n // Scripts.\n wp_enqueue_script(\n 'single_block-cgb-block-js', // Handle.\n plugins_url( '/dist/blocks.build.js', dirname( __FILE__ ) ), // Block.build.js: We register the block here. Built with Webpack.\n array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ) // Dependencies, defined above.\n // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.build.js' ) // Version: File modification time.\n );\n // Styles.\n wp_enqueue_style(\n 'single_block-cgb-block-editor-css', // Handle.\n plugins_url( 'dist/blocks.editor.build.css', dirname( __FILE__ ) ), // Block editor CSS.\n array( 'wp-edit-blocks' ) // Dependency to include the CSS after it.\n // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.editor.build.css' ) // Version: File modification time.\n );\n}\n// Hook: Editor assets.\nadd_action( 'enqueue_block_editor_assets', 'single_block_cgb_editor_assets' );\n</code></pre>\n"
}
] | 2019/01/23 | [
"https://wordpress.stackexchange.com/questions/326461",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23610/"
] | I am creating a plugin with custom gutenberg blocks.
Each block has a styles.scss file. If I add code to this file, the block is styled in both the back end and front end, as expected per the docs.
For example, in a block "section" I want to style the background color only on the back end:
```
.wp-block-pbdsblocks-section {
background-color: #e0e0e0;
padding: 10px;
}
```
But this affects both front and back end. The articles I've been reading say to apply the style by creating an "editor.scss" file in the block directory.
I import the editor.scss file into the block's index.js.
I can see my code in this file being compiled and added to `/assets/css/blocks.style.css`
I have the plugins' php file set to enqueue it:
```
/**
* Enqueue block editor only JavaScript and CSS
*/
function pbdsblocks_editor_scripts()
{
// Make paths variables so we don't write em twice ;)
$blockPath = '/assets/js/editor.blocks.js';
$editorStylePath = '/assets/css/blocks.editor.css';
// Enqueue the bundled block JS file
wp_enqueue_script(
'pbdsblocks-blocks-js',
plugins_url( $blockPath, __FILE__ ),
[ 'wp-i18n', 'wp-element', 'wp-blocks', 'wp-components', 'wp-api', 'wp-editor' ],
filemtime( plugin_dir_path(__FILE__) . $blockPath )
);
// Enqueue optional editor only styles
wp_enqueue_style(
'pbdsblocks-blocks-editor-css',
plugins_url( $editorStylePath, __FILE__),
[ 'wp-blocks' ],
filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )
);
}
// Hook scripts function into block editor hook
add_action( 'enqueue_block_editor_assets', 'pbdsblocks_editor_scripts' );
```
But the styles only take affect if they're in the `style.scss` file. Which affects front end and back end. | FWIW, there was an error in the `wp_enqueue_style` function I received. This one works fine:
```
// Enqueue optional editor only styles
wp_enqueue_style(
'pbdsblocks-blocks-editor-css',
plugins_url( $editorStylePath, __FILE__),
[ ],
filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )
);
```
Note the third argument has changed to `[ ]` from `['wp-blocks']` |
326,462 | <p>Is it possible to limit the categories so that user in a list of groups does not see these posts at all? Not even in a list of posts?</p>
<p>I'm using the answer from here:</p>
<p><a href="https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin">Only show category to certain user levels without plugin</a></p>
<p>My Code:</p>
<pre><code>###########
// restrikcija posameznih kategorij za grupo ki je subscriber
// source: https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin
add_filter('template_include', 'restict_by_category');
function check_user() {
$user = wp_get_current_user();
$restricted_groups = array( 'company1', 'company2', 'company3', 'subscriber' ); // categories subscribers cannot see
if ( ! $user->ID || array_intersect( $restricted_groups, $user->roles ) ) {
// user is not logged or is a subscriber
return false;
}
return true;
}
function restict_by_category( $template ) {
if ( ! is_main_query() ) {
return $template; // only affect main query.
}
$allow = true;
$private_categories = array( 'podjetje', 'personal', 'nekategorizirano', 'razno', 'sola-2' ); // categories subscribers cannot see
if ( is_single() ) {
$cats = wp_get_object_terms( get_queried_object()->ID, 'category', array('fields' => 'slugs') ); // get the categories associated to the required post
if ( array_intersect( $private_categories, $cats ) ) {
// post has a reserved category, let's check user
$allow = check_user();
}
} elseif ( is_tax('category', $private_categories) ) {
// the archive for one of private categories is required, let's check user
$allow = check_user();
}
// if allowed include the required template, otherwise include the 'not-allowed' one
return $allow ? $template : get_home_url(); //get_template_directory() . '/not-allowed.php';
}
###########
</code></pre>
<p>The problem is that user still sees post in a list of posts, but when clicked upon it's content is empty (which is OK, but even better would be that it doesnt sees posts at all).</p>
<p>And also if I have a master category with lots of sub-categorys, is it possible to also limit all these child categories?</p>
| [
{
"answer_id": 326477,
"author": "Steve",
"author_id": 23610,
"author_profile": "https://wordpress.stackexchange.com/users/23610",
"pm_score": 1,
"selected": false,
"text": "<p>FWIW, there was an error in the <code>wp_enqueue_style</code> function I received. This one works fine:</p>\n\n<pre><code> // Enqueue optional editor only styles\n wp_enqueue_style(\n 'pbdsblocks-blocks-editor-css',\n plugins_url( $editorStylePath, __FILE__),\n [ ],\n filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )\n );\n</code></pre>\n\n<p>Note the third argument has changed to <code>[ ]</code> from <code>['wp-blocks']</code></p>\n"
},
{
"answer_id": 326520,
"author": "Ashiquzzaman Kiron",
"author_id": 78505,
"author_profile": "https://wordpress.stackexchange.com/users/78505",
"pm_score": 0,
"selected": false,
"text": "<p>You need two different stylesheet for a block. One for front end and one for back end.\nHere's what I suggest you to follow. I've taken this code from <a href=\"https://github.com/ahmadawais/create-guten-block/blob/master/examples/01-single-block/src/init.php\" rel=\"nofollow noreferrer\">create-guten-block</a></p>\n\n<pre><code> /**\n * Enqueue Gutenberg block assets for both frontend + backend.\n *\n * @uses {wp-editor} for WP editor styles.\n * @since 1.0.0\n */\nfunction single_block_cgb_block_assets() {\n // Styles.\n wp_enqueue_style(\n 'single_block-cgb-style-css', // Handle.\n plugins_url( 'dist/blocks.style.build.css', dirname( __FILE__ ) ), // Block style CSS.\n array( 'wp-editor' ) // Dependency to include the CSS after it.\n // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.style.build.css' ) // Version: File modification time.\n );\n}\n// Hook: Frontend assets.\nadd_action( 'enqueue_block_assets', 'single_block_cgb_block_assets' );\n/**\n * Enqueue Gutenberg block assets for backend editor.\n *\n * @uses {wp-blocks} for block type registration & related functions.\n * @uses {wp-element} for WP Element abstraction — structure of blocks.\n * @uses {wp-i18n} to internationalize the block's text.\n * @uses {wp-editor} for WP editor styles.\n * @since 1.0.0\n */\nfunction single_block_cgb_editor_assets() {\n // Scripts.\n wp_enqueue_script(\n 'single_block-cgb-block-js', // Handle.\n plugins_url( '/dist/blocks.build.js', dirname( __FILE__ ) ), // Block.build.js: We register the block here. Built with Webpack.\n array( 'wp-blocks', 'wp-i18n', 'wp-element', 'wp-editor' ) // Dependencies, defined above.\n // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.build.js' ) // Version: File modification time.\n );\n // Styles.\n wp_enqueue_style(\n 'single_block-cgb-block-editor-css', // Handle.\n plugins_url( 'dist/blocks.editor.build.css', dirname( __FILE__ ) ), // Block editor CSS.\n array( 'wp-edit-blocks' ) // Dependency to include the CSS after it.\n // filemtime( plugin_dir_path( __DIR__ ) . 'dist/blocks.editor.build.css' ) // Version: File modification time.\n );\n}\n// Hook: Editor assets.\nadd_action( 'enqueue_block_editor_assets', 'single_block_cgb_editor_assets' );\n</code></pre>\n"
}
] | 2019/01/23 | [
"https://wordpress.stackexchange.com/questions/326462",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159653/"
] | Is it possible to limit the categories so that user in a list of groups does not see these posts at all? Not even in a list of posts?
I'm using the answer from here:
[Only show category to certain user levels without plugin](https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin)
My Code:
```
###########
// restrikcija posameznih kategorij za grupo ki je subscriber
// source: https://wordpress.stackexchange.com/questions/113500/only-show-category-to-certain-user-levels-without-plugin
add_filter('template_include', 'restict_by_category');
function check_user() {
$user = wp_get_current_user();
$restricted_groups = array( 'company1', 'company2', 'company3', 'subscriber' ); // categories subscribers cannot see
if ( ! $user->ID || array_intersect( $restricted_groups, $user->roles ) ) {
// user is not logged or is a subscriber
return false;
}
return true;
}
function restict_by_category( $template ) {
if ( ! is_main_query() ) {
return $template; // only affect main query.
}
$allow = true;
$private_categories = array( 'podjetje', 'personal', 'nekategorizirano', 'razno', 'sola-2' ); // categories subscribers cannot see
if ( is_single() ) {
$cats = wp_get_object_terms( get_queried_object()->ID, 'category', array('fields' => 'slugs') ); // get the categories associated to the required post
if ( array_intersect( $private_categories, $cats ) ) {
// post has a reserved category, let's check user
$allow = check_user();
}
} elseif ( is_tax('category', $private_categories) ) {
// the archive for one of private categories is required, let's check user
$allow = check_user();
}
// if allowed include the required template, otherwise include the 'not-allowed' one
return $allow ? $template : get_home_url(); //get_template_directory() . '/not-allowed.php';
}
###########
```
The problem is that user still sees post in a list of posts, but when clicked upon it's content is empty (which is OK, but even better would be that it doesnt sees posts at all).
And also if I have a master category with lots of sub-categorys, is it possible to also limit all these child categories? | FWIW, there was an error in the `wp_enqueue_style` function I received. This one works fine:
```
// Enqueue optional editor only styles
wp_enqueue_style(
'pbdsblocks-blocks-editor-css',
plugins_url( $editorStylePath, __FILE__),
[ ],
filemtime( plugin_dir_path( __FILE__ ) . $editorStylePath )
);
```
Note the third argument has changed to `[ ]` from `['wp-blocks']` |
326,497 | <p>I have a custom post-type 'News' which has multiple custom taxonomies 'news-category', 'news-tags'. Each post contains between 4-8 'news-tags' and 1 'news-category'.</p>
<p>For my current post, I'd like to display related posts based on common 'news-tags' terms added to my current post, while also matching the 'news-category' term. </p>
<p>So, I'd like the related posts to look for posts of the same 'news-category' with the most number of 'news-tags' terms in common and display them in descending order.</p>
<p>If I were to display 4 related posts:</p>
<ul>
<li>the first post might have 5 'news-tags' terms in common,</li>
<li>the second post might have 3 'news-tags' terms in common,</li>
<li>the third post might have 2 'news-tags' terms in common,</li>
<li>and the last post might have 'news-tags' 1 term in common.</li>
</ul>
<p>and they'd all belong to the same 'news-category'.</p>
<p>Would it be possible to do this? I've really been struggling with this so I'll appreciate any help.</p>
| [
{
"answer_id": 326648,
"author": "Bram",
"author_id": 60517,
"author_profile": "https://wordpress.stackexchange.com/users/60517",
"pm_score": 4,
"selected": true,
"text": "<p>Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displaying the result.</p>\n\n<h2>Post retrieval</h2>\n\n<p>This is possible using the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"noreferrer\">taxonomy parameters</a> offered in <code>WP_Query</code>.</p>\n\n<p>Let's first retrieve the category of the current post and find their IDs:</p>\n\n<pre><code>$categories = get_the_terms( get_the_ID(), 'news-category' );\n\nforeach ( $categories as $category ) {\n $category_ids[] = $category->term_id;\n }\n</code></pre>\n\n<p>We do the same for the tags:</p>\n\n<pre><code>$tags = get_the_terms( get_the_ID(), 'news-tags' );\n\nforeach ( $tags as $tag) {\n $tag_ids[] = $tag->term_id;\n }\n</code></pre>\n\n<p>Then, we build a set of query arguments (we later feed to a <code>WP_Query</code>-call):</p>\n\n<pre><code>$related_args = array(\n 'post_type' => array(\n 'news',\n ),\n 'post_status' => 'publish',\n 'posts_per_page' => -1, // Get all posts\n 'post__not_in' => array( get_the_ID() ), // Hide current post in list of related content\n 'tax_query' => array(\n 'relation' => 'AND', // Make sure to mach both category and term\n array(\n 'taxonomy' => 'news-category',\n 'field' => 'term_id',\n 'terms' => $category_ids,\n ),\n array(\n 'taxonomy' => 'news-tags',\n 'field' => 'term_id',\n 'terms' => $tag_ids,\n ),\n ),\n);\n</code></pre>\n\n<p>Finally, we run the query that gives us an array of </p>\n\n<pre><code>$related_all = new WP_Query( $related_args );\n</code></pre>\n\n<p>Please note this query retrieves all posts that match the 'filter', as we're doing the ordering later on. If we'd now only query 4 posts, those might not be the most relevant. </p>\n\n<p><em>Sidenote: the above query is quite heavy, in the sense that it (potentially) retrieves a large number of posts. When I've created a related posts section for a client project (also a news section), I ordered by date rather than relevance. That allows you to set a limit to the number of posts you retrieve from the database (change the <code>-1</code> to <code>4</code> in your case, and add <code>'orderby' => array( 'date' => 'DESC' )</code> to the <code>$related_args</code>-array). If you want to stick with ordering on the overlap, I suggest you add a date filter in the query arguments, or limit the number of results to some finite value, from which set you then retrieve the most relevant posts.</em></p>\n\n<h2>Post ordering</h2>\n\n<p>Following the previous step, <code>$related_all</code> is a <code>WP_Query</code>-object. We access the actual posts as follows, and store them in <code>$related_all_posts</code>:</p>\n\n<pre><code>$related_all_posts = $related_all->posts;\n</code></pre>\n\n<p>That gives us an array we can more easily work with. We then loop through all the results in that array. Per the comments in the code, when looping through the results, we find the tags associated to the (related) post, find their IDs, compare that with the <code>$tag_ids</code> (of the main post) found earlier and see how much overlap there is using <a href=\"https://secure.php.net/manual/en/function.array-intersect.php\" rel=\"noreferrer\"><code>array_intersect()</code></a>:</p>\n\n<pre><code>foreach($related_all_posts as $related_post){\n // Find all tags of the related post under consideration\n $related_post_tags = get_the_terms( $related_post->ID, 'news-tags' );\n foreach ( $related_post_tags as $related_post_tag ) {\n $related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query\n }\n\n // Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in\n // an array that has the ID of the related post as array key.\n $related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids));\n}\n</code></pre>\n\n<p>We then sort that latest array by value, from high to low, using <a href=\"https://secure.php.net/manual/en/function.arsort.php\" rel=\"noreferrer\"><code>arsort()</code></a>.</p>\n\n<pre><code>arsort($related_posts_commonality);\n</code></pre>\n\n<p>Finally, we limit it to only four posts using <a href=\"https://secure.php.net/manual/en/function.array-slice.php\" rel=\"noreferrer\"><code>array_slice()</code></a>:</p>\n\n<pre><code>$related_posts_commonality = array_slice($related_posts_commonality, 0, 4);\n</code></pre>\n\n<p>You can find the IDs of the related posts using <a href=\"https://secure.php.net/manual/en/function.array-keys.php\" rel=\"noreferrer\"><code>array_keys</code></a>, e.g.:</p>\n\n<pre><code>$related_posts_IDs = array_keys($related_posts_commonality);\n</code></pre>\n\n<h2>Post display</h2>\n\n<p>To actually display the posts, there's two routes you can take. You can either use the <code>$related_posts_commonality</code> array to loop through the results of <code>WP_Query</code> (i.e., <code>$related_all</code>), save the matching posts (in their right order) in a new array or object and loop through these once again for display. As this doesn't require additional queries, it's probably the most efficient one. However, it's also a pain.</p>\n\n<p>As such, you can also use simply use the IDs we've just found (<code>$related_posts_IDs</code>) to run another query.</p>\n\n<pre><code>$related_sorted = WP_query(array('post__in' => $related_posts_IDs));\n</code></pre>\n\n<p>Then, you can use a regular <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Usage\" rel=\"noreferrer\">loop</a> (<code>while ($related_sorted->have_posts())</code> and so on) to go through and display the results using functions as <code>the_title()</code> and <code>the_content()</code>.</p>\n"
},
{
"answer_id": 387094,
"author": "abgregs",
"author_id": 149347,
"author_profile": "https://wordpress.stackexchange.com/users/149347",
"pm_score": 1,
"selected": false,
"text": "<p>Since a given post type shares the same taxonomies and a common scenario might be to find related posts based on the number of matching terms across all taxonomies (no matter how many or what they are called), I created a snippet for this. This approach doesn't require explicitly defining your custom taxonomies to check against (although you can if you want) and also gets a total count of all matching terms in order to sort the related posts from highest to lowest. You can modify the snippet in order to specify only certain taxonomies or change the limit of up to how many related posts should be returned.</p>\n<p>The snippet has comments for explanation, but essentially in your template this function will take in the current post ID and return an array of post IDs for the related posts. From there, you can check the result and, assuming at least some other posts with matching terms are found, you can loop over the related post IDs returned and then use the ID to display whatever information about each post (title, link to the post etc).</p>\n<p>Based on the title of the OP's question, I figured others might find this useful.</p>\n<p>Here is a link to the snippet.</p>\n<p><a href=\"https://gist.github.com/abgregs/2d440edb0c56845b3e3e1a9f4ef26f44\" rel=\"nofollow noreferrer\">Get Recent Posts</a></p>\n<p>To use this in your single post template, you'd do something like:</p>\n<pre><code>$current_post_id = get_the_id();\n$related_post_ids = get_related_posts($current_post_id);\n// if we have related posts...\nif ( !empty($related_post_ids) ) {\n foreach ( $related_post_ids as $post_id ) {\n echo '<h2>' . get_the_title($post_id) . '</h2>';\n }\n} else {\n // No related posts found\n}\n</code></pre>\n<p>The snippet for the helper function:</p>\n<pre><code>/**\n * A WordPress helper function that takes the ID of the current post\n * and returns the top three related posts ranked by highest number of taxonomy\n * terms in common with the current post. Alternately, you can modify lines 26-33\n * to exclude certain taxonomies so that we only check for terms in specific taxonomies \n * to determine the related posts. To include up to the top X related posts instead of\n * up to three, you can modify lines 148-149.\n *\n * In your template to make use of this function you would do something like...\n *\n * $current_post_id = get_the_id();\n * $related_post_ids = get_related_posts($current_post_id);\n * \n */\n\nfunction get_related_posts($current_post_id)\n { \n // Get the post type we're dealing with based on the current post ID.\n $post_type = get_post_type($current_post_id);\n\n // Get all taxonomies of the specified post type of the current post.\n $taxonomies = [];\n $taxonomy_objects = get_object_taxonomies( $post_type, 'objects' );\n foreach($taxonomy_objects as $taxonomy) {\n // If you want to only check against certain taxonomies, modify this section as needed\n // to set conditions for which taxonomies should be excluded or included. Below is just an example.\n // if ($taxonomy->name !== 'post_format' && $taxonomy->name !== 'post_tag') {\n // array_push($taxonomies, $taxonomy);\n // }\n \n // By default, we will check against all taxonomies.\n array_push($taxonomies, $taxonomy);\n }\n\n // Get all the posts of the specified post type,\n // excluding the current post, so that we can compare these\n // against the current post.\n $other_posts_args = array(\n 'post_type' => $post_type,\n 'post__not_in' => array($current_post_id),\n );\n $other_posts = new WP_Query( $other_posts_args );\n\n wp_reset_postdata();\n\n // We will create an object for each matching post that will include\n // the ID and count of the number of times it matches any taxonomy term with the current post.\n // Later, when we create those, they will get pushed to this $matching_posts array.\n $matching_posts = array();\n\n // If we have other posts, loop through them and\n // count matches for any taxonomy terms in common.\n if($other_posts->have_posts()) {\n\n foreach($taxonomies as $taxonomy) {\n\n // Get the term IDs of terms for the current post\n // (the post presumably displaying as a single post\n // back in our template, for which were finding related posts).\n $current_post_terms = get_the_terms($current_post_id, $taxonomy->name);\n\n\n // Only continue if the current post actually has some terms for this taxonomy.\n if($current_post_terms !== false) {\n\n foreach($other_posts->posts as $post) {\n\n // Get the term IDs of terms for this taxonomy\n // for the other post we are currently looping over.\n $other_post_terms = get_the_terms($post->ID, $taxonomy->name);\n\n // Check that other post has terms and only continue if there\n // are terms to compare.\n if($other_post_terms !== false) {\n\n $other_post_term_IDs = array();\n $current_post_term_IDs = array();\n\n // Get term IDs from each term in the current post.\n foreach($current_post_terms as $term) {\n array_push($current_post_term_IDs, $term->term_id);\n }\n\n // Get term IDs from each term in the other post.\n foreach($other_post_terms as $term) {\n array_push($other_post_term_IDs, $term->term_id);\n }\n\n if( !empty($other_post_term_IDs) && !empty($current_post_term_IDs) ) {\n \n // Collect the matching term IDs for the terms the posts have in common.\n $match_count = sizeof(array_intersect($other_post_term_IDs, $current_post_term_IDs));\n \n // Get the ID of the other post to use to identify and store this post\n // in our results.\n $post_ID = $post->ID;\n\n if ($match_count > 0) {\n\n // Assume post not added previously.\n $post_already_added = false;\n\n // If posts have already been added to our matches\n // then check to see if we already added this post.\n if(!empty($matching_posts)) {\n \n foreach($matching_posts as $post) {\n // If this post was added previously then let's increment the count\n // for our new matching terms.\n if (isset($post->ID) && $post->ID == $post_ID) {\n $post->count += $match_count;\n // Switch this to true for the check we perform below.\n $post_already_added = true;\n }\n }\n \n // If never found a post with same ID in our $matching_posts\n // list then create a new entry associated with this post and add it.\n if ($post_already_added === false) {\n $new_matching_post = new stdClass();\n $new_matching_post->ID = $post_ID;\n $new_matching_post->count = $match_count;\n array_push($matching_posts, $new_matching_post);\n }\n } else {\n // If no posts have been added yet to $matching_posts then this will be the first.\n $new_matching_post = new stdClass();\n $new_matching_post->ID = $post_ID;\n $new_matching_post->count = $match_count;\n array_push($matching_posts, $new_matching_post);\n }\n }\n }\n }\n }\n }\n }\n\n \n if(!empty($matching_posts)) {\n // Sort the array in order of highest count for total terms in common\n // (most related to least).\n usort($matching_posts, function($a, $b) {\n return strcmp($b->count, $a->count);\n });\n\n // Just take the top 3 most related\n $most_related = array_slice($matching_posts, 0, 3);\n \n // Get the IDs of most related posts.\n $matching_posts = array_map(function($obj) {\n return $obj->ID;\n }, $most_related);\n }\n \n } \n\n return $matching_posts;\n\n\n }\n</code></pre>\n"
},
{
"answer_id": 408877,
"author": "DAU",
"author_id": 225165,
"author_profile": "https://wordpress.stackexchange.com/users/225165",
"pm_score": 0,
"selected": false,
"text": "<p>I followed Brams example but needed to tweak the code at two points for me to run it as expected</p>\n<p><strong>1) clear array $related_tag_ids for each related_post</strong></p>\n<pre><code>foreach($related_all_posts as $related_post){\n // Find all tags of the related post under consideration\n $related_post_tags = get_the_terms( $related_post->ID, 'news-tags' );\n $related_tag_ids = array();\n foreach ( $related_post_tags as $related_post_tag ) {\n $related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query\n }\n\n // Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in\n // an array that has the ID of the related post as array key.\n $related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids));\n}\n</code></pre>\n<p><strong>2) array slice with $preserve_keys set to true</strong></p>\n<pre><code>$related_posts_commonality = array_slice($related_posts_commonality, 0, true);\n</code></pre>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326497",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159719/"
] | I have a custom post-type 'News' which has multiple custom taxonomies 'news-category', 'news-tags'. Each post contains between 4-8 'news-tags' and 1 'news-category'.
For my current post, I'd like to display related posts based on common 'news-tags' terms added to my current post, while also matching the 'news-category' term.
So, I'd like the related posts to look for posts of the same 'news-category' with the most number of 'news-tags' terms in common and display them in descending order.
If I were to display 4 related posts:
* the first post might have 5 'news-tags' terms in common,
* the second post might have 3 'news-tags' terms in common,
* the third post might have 2 'news-tags' terms in common,
* and the last post might have 'news-tags' 1 term in common.
and they'd all belong to the same 'news-category'.
Would it be possible to do this? I've really been struggling with this so I'll appreciate any help. | Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displaying the result.
Post retrieval
--------------
This is possible using the [taxonomy parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) offered in `WP_Query`.
Let's first retrieve the category of the current post and find their IDs:
```
$categories = get_the_terms( get_the_ID(), 'news-category' );
foreach ( $categories as $category ) {
$category_ids[] = $category->term_id;
}
```
We do the same for the tags:
```
$tags = get_the_terms( get_the_ID(), 'news-tags' );
foreach ( $tags as $tag) {
$tag_ids[] = $tag->term_id;
}
```
Then, we build a set of query arguments (we later feed to a `WP_Query`-call):
```
$related_args = array(
'post_type' => array(
'news',
),
'post_status' => 'publish',
'posts_per_page' => -1, // Get all posts
'post__not_in' => array( get_the_ID() ), // Hide current post in list of related content
'tax_query' => array(
'relation' => 'AND', // Make sure to mach both category and term
array(
'taxonomy' => 'news-category',
'field' => 'term_id',
'terms' => $category_ids,
),
array(
'taxonomy' => 'news-tags',
'field' => 'term_id',
'terms' => $tag_ids,
),
),
);
```
Finally, we run the query that gives us an array of
```
$related_all = new WP_Query( $related_args );
```
Please note this query retrieves all posts that match the 'filter', as we're doing the ordering later on. If we'd now only query 4 posts, those might not be the most relevant.
*Sidenote: the above query is quite heavy, in the sense that it (potentially) retrieves a large number of posts. When I've created a related posts section for a client project (also a news section), I ordered by date rather than relevance. That allows you to set a limit to the number of posts you retrieve from the database (change the `-1` to `4` in your case, and add `'orderby' => array( 'date' => 'DESC' )` to the `$related_args`-array). If you want to stick with ordering on the overlap, I suggest you add a date filter in the query arguments, or limit the number of results to some finite value, from which set you then retrieve the most relevant posts.*
Post ordering
-------------
Following the previous step, `$related_all` is a `WP_Query`-object. We access the actual posts as follows, and store them in `$related_all_posts`:
```
$related_all_posts = $related_all->posts;
```
That gives us an array we can more easily work with. We then loop through all the results in that array. Per the comments in the code, when looping through the results, we find the tags associated to the (related) post, find their IDs, compare that with the `$tag_ids` (of the main post) found earlier and see how much overlap there is using [`array_intersect()`](https://secure.php.net/manual/en/function.array-intersect.php):
```
foreach($related_all_posts as $related_post){
// Find all tags of the related post under consideration
$related_post_tags = get_the_terms( $related_post->ID, 'news-tags' );
foreach ( $related_post_tags as $related_post_tag ) {
$related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query
}
// Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in
// an array that has the ID of the related post as array key.
$related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids));
}
```
We then sort that latest array by value, from high to low, using [`arsort()`](https://secure.php.net/manual/en/function.arsort.php).
```
arsort($related_posts_commonality);
```
Finally, we limit it to only four posts using [`array_slice()`](https://secure.php.net/manual/en/function.array-slice.php):
```
$related_posts_commonality = array_slice($related_posts_commonality, 0, 4);
```
You can find the IDs of the related posts using [`array_keys`](https://secure.php.net/manual/en/function.array-keys.php), e.g.:
```
$related_posts_IDs = array_keys($related_posts_commonality);
```
Post display
------------
To actually display the posts, there's two routes you can take. You can either use the `$related_posts_commonality` array to loop through the results of `WP_Query` (i.e., `$related_all`), save the matching posts (in their right order) in a new array or object and loop through these once again for display. As this doesn't require additional queries, it's probably the most efficient one. However, it's also a pain.
As such, you can also use simply use the IDs we've just found (`$related_posts_IDs`) to run another query.
```
$related_sorted = WP_query(array('post__in' => $related_posts_IDs));
```
Then, you can use a regular [loop](https://codex.wordpress.org/Class_Reference/WP_Query#Usage) (`while ($related_sorted->have_posts())` and so on) to go through and display the results using functions as `the_title()` and `the_content()`. |
326,503 | <p>I am trying to write a <code>.htaccess</code> rule to redirect the URL to a subdomain.</p>
<p>Example: <code>example.com/pagecategory/page-single</code> → <code>pagecategory.example.com/page-single</code></p>
<p>I've added wildcard subdomain on my hosting.</p>
<p>Can anyone help me write the <code>.htaccess</code> code?</p>
| [
{
"answer_id": 326648,
"author": "Bram",
"author_id": 60517,
"author_profile": "https://wordpress.stackexchange.com/users/60517",
"pm_score": 4,
"selected": true,
"text": "<p>Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displaying the result.</p>\n\n<h2>Post retrieval</h2>\n\n<p>This is possible using the <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters\" rel=\"noreferrer\">taxonomy parameters</a> offered in <code>WP_Query</code>.</p>\n\n<p>Let's first retrieve the category of the current post and find their IDs:</p>\n\n<pre><code>$categories = get_the_terms( get_the_ID(), 'news-category' );\n\nforeach ( $categories as $category ) {\n $category_ids[] = $category->term_id;\n }\n</code></pre>\n\n<p>We do the same for the tags:</p>\n\n<pre><code>$tags = get_the_terms( get_the_ID(), 'news-tags' );\n\nforeach ( $tags as $tag) {\n $tag_ids[] = $tag->term_id;\n }\n</code></pre>\n\n<p>Then, we build a set of query arguments (we later feed to a <code>WP_Query</code>-call):</p>\n\n<pre><code>$related_args = array(\n 'post_type' => array(\n 'news',\n ),\n 'post_status' => 'publish',\n 'posts_per_page' => -1, // Get all posts\n 'post__not_in' => array( get_the_ID() ), // Hide current post in list of related content\n 'tax_query' => array(\n 'relation' => 'AND', // Make sure to mach both category and term\n array(\n 'taxonomy' => 'news-category',\n 'field' => 'term_id',\n 'terms' => $category_ids,\n ),\n array(\n 'taxonomy' => 'news-tags',\n 'field' => 'term_id',\n 'terms' => $tag_ids,\n ),\n ),\n);\n</code></pre>\n\n<p>Finally, we run the query that gives us an array of </p>\n\n<pre><code>$related_all = new WP_Query( $related_args );\n</code></pre>\n\n<p>Please note this query retrieves all posts that match the 'filter', as we're doing the ordering later on. If we'd now only query 4 posts, those might not be the most relevant. </p>\n\n<p><em>Sidenote: the above query is quite heavy, in the sense that it (potentially) retrieves a large number of posts. When I've created a related posts section for a client project (also a news section), I ordered by date rather than relevance. That allows you to set a limit to the number of posts you retrieve from the database (change the <code>-1</code> to <code>4</code> in your case, and add <code>'orderby' => array( 'date' => 'DESC' )</code> to the <code>$related_args</code>-array). If you want to stick with ordering on the overlap, I suggest you add a date filter in the query arguments, or limit the number of results to some finite value, from which set you then retrieve the most relevant posts.</em></p>\n\n<h2>Post ordering</h2>\n\n<p>Following the previous step, <code>$related_all</code> is a <code>WP_Query</code>-object. We access the actual posts as follows, and store them in <code>$related_all_posts</code>:</p>\n\n<pre><code>$related_all_posts = $related_all->posts;\n</code></pre>\n\n<p>That gives us an array we can more easily work with. We then loop through all the results in that array. Per the comments in the code, when looping through the results, we find the tags associated to the (related) post, find their IDs, compare that with the <code>$tag_ids</code> (of the main post) found earlier and see how much overlap there is using <a href=\"https://secure.php.net/manual/en/function.array-intersect.php\" rel=\"noreferrer\"><code>array_intersect()</code></a>:</p>\n\n<pre><code>foreach($related_all_posts as $related_post){\n // Find all tags of the related post under consideration\n $related_post_tags = get_the_terms( $related_post->ID, 'news-tags' );\n foreach ( $related_post_tags as $related_post_tag ) {\n $related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query\n }\n\n // Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in\n // an array that has the ID of the related post as array key.\n $related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids));\n}\n</code></pre>\n\n<p>We then sort that latest array by value, from high to low, using <a href=\"https://secure.php.net/manual/en/function.arsort.php\" rel=\"noreferrer\"><code>arsort()</code></a>.</p>\n\n<pre><code>arsort($related_posts_commonality);\n</code></pre>\n\n<p>Finally, we limit it to only four posts using <a href=\"https://secure.php.net/manual/en/function.array-slice.php\" rel=\"noreferrer\"><code>array_slice()</code></a>:</p>\n\n<pre><code>$related_posts_commonality = array_slice($related_posts_commonality, 0, 4);\n</code></pre>\n\n<p>You can find the IDs of the related posts using <a href=\"https://secure.php.net/manual/en/function.array-keys.php\" rel=\"noreferrer\"><code>array_keys</code></a>, e.g.:</p>\n\n<pre><code>$related_posts_IDs = array_keys($related_posts_commonality);\n</code></pre>\n\n<h2>Post display</h2>\n\n<p>To actually display the posts, there's two routes you can take. You can either use the <code>$related_posts_commonality</code> array to loop through the results of <code>WP_Query</code> (i.e., <code>$related_all</code>), save the matching posts (in their right order) in a new array or object and loop through these once again for display. As this doesn't require additional queries, it's probably the most efficient one. However, it's also a pain.</p>\n\n<p>As such, you can also use simply use the IDs we've just found (<code>$related_posts_IDs</code>) to run another query.</p>\n\n<pre><code>$related_sorted = WP_query(array('post__in' => $related_posts_IDs));\n</code></pre>\n\n<p>Then, you can use a regular <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Usage\" rel=\"noreferrer\">loop</a> (<code>while ($related_sorted->have_posts())</code> and so on) to go through and display the results using functions as <code>the_title()</code> and <code>the_content()</code>.</p>\n"
},
{
"answer_id": 387094,
"author": "abgregs",
"author_id": 149347,
"author_profile": "https://wordpress.stackexchange.com/users/149347",
"pm_score": 1,
"selected": false,
"text": "<p>Since a given post type shares the same taxonomies and a common scenario might be to find related posts based on the number of matching terms across all taxonomies (no matter how many or what they are called), I created a snippet for this. This approach doesn't require explicitly defining your custom taxonomies to check against (although you can if you want) and also gets a total count of all matching terms in order to sort the related posts from highest to lowest. You can modify the snippet in order to specify only certain taxonomies or change the limit of up to how many related posts should be returned.</p>\n<p>The snippet has comments for explanation, but essentially in your template this function will take in the current post ID and return an array of post IDs for the related posts. From there, you can check the result and, assuming at least some other posts with matching terms are found, you can loop over the related post IDs returned and then use the ID to display whatever information about each post (title, link to the post etc).</p>\n<p>Based on the title of the OP's question, I figured others might find this useful.</p>\n<p>Here is a link to the snippet.</p>\n<p><a href=\"https://gist.github.com/abgregs/2d440edb0c56845b3e3e1a9f4ef26f44\" rel=\"nofollow noreferrer\">Get Recent Posts</a></p>\n<p>To use this in your single post template, you'd do something like:</p>\n<pre><code>$current_post_id = get_the_id();\n$related_post_ids = get_related_posts($current_post_id);\n// if we have related posts...\nif ( !empty($related_post_ids) ) {\n foreach ( $related_post_ids as $post_id ) {\n echo '<h2>' . get_the_title($post_id) . '</h2>';\n }\n} else {\n // No related posts found\n}\n</code></pre>\n<p>The snippet for the helper function:</p>\n<pre><code>/**\n * A WordPress helper function that takes the ID of the current post\n * and returns the top three related posts ranked by highest number of taxonomy\n * terms in common with the current post. Alternately, you can modify lines 26-33\n * to exclude certain taxonomies so that we only check for terms in specific taxonomies \n * to determine the related posts. To include up to the top X related posts instead of\n * up to three, you can modify lines 148-149.\n *\n * In your template to make use of this function you would do something like...\n *\n * $current_post_id = get_the_id();\n * $related_post_ids = get_related_posts($current_post_id);\n * \n */\n\nfunction get_related_posts($current_post_id)\n { \n // Get the post type we're dealing with based on the current post ID.\n $post_type = get_post_type($current_post_id);\n\n // Get all taxonomies of the specified post type of the current post.\n $taxonomies = [];\n $taxonomy_objects = get_object_taxonomies( $post_type, 'objects' );\n foreach($taxonomy_objects as $taxonomy) {\n // If you want to only check against certain taxonomies, modify this section as needed\n // to set conditions for which taxonomies should be excluded or included. Below is just an example.\n // if ($taxonomy->name !== 'post_format' && $taxonomy->name !== 'post_tag') {\n // array_push($taxonomies, $taxonomy);\n // }\n \n // By default, we will check against all taxonomies.\n array_push($taxonomies, $taxonomy);\n }\n\n // Get all the posts of the specified post type,\n // excluding the current post, so that we can compare these\n // against the current post.\n $other_posts_args = array(\n 'post_type' => $post_type,\n 'post__not_in' => array($current_post_id),\n );\n $other_posts = new WP_Query( $other_posts_args );\n\n wp_reset_postdata();\n\n // We will create an object for each matching post that will include\n // the ID and count of the number of times it matches any taxonomy term with the current post.\n // Later, when we create those, they will get pushed to this $matching_posts array.\n $matching_posts = array();\n\n // If we have other posts, loop through them and\n // count matches for any taxonomy terms in common.\n if($other_posts->have_posts()) {\n\n foreach($taxonomies as $taxonomy) {\n\n // Get the term IDs of terms for the current post\n // (the post presumably displaying as a single post\n // back in our template, for which were finding related posts).\n $current_post_terms = get_the_terms($current_post_id, $taxonomy->name);\n\n\n // Only continue if the current post actually has some terms for this taxonomy.\n if($current_post_terms !== false) {\n\n foreach($other_posts->posts as $post) {\n\n // Get the term IDs of terms for this taxonomy\n // for the other post we are currently looping over.\n $other_post_terms = get_the_terms($post->ID, $taxonomy->name);\n\n // Check that other post has terms and only continue if there\n // are terms to compare.\n if($other_post_terms !== false) {\n\n $other_post_term_IDs = array();\n $current_post_term_IDs = array();\n\n // Get term IDs from each term in the current post.\n foreach($current_post_terms as $term) {\n array_push($current_post_term_IDs, $term->term_id);\n }\n\n // Get term IDs from each term in the other post.\n foreach($other_post_terms as $term) {\n array_push($other_post_term_IDs, $term->term_id);\n }\n\n if( !empty($other_post_term_IDs) && !empty($current_post_term_IDs) ) {\n \n // Collect the matching term IDs for the terms the posts have in common.\n $match_count = sizeof(array_intersect($other_post_term_IDs, $current_post_term_IDs));\n \n // Get the ID of the other post to use to identify and store this post\n // in our results.\n $post_ID = $post->ID;\n\n if ($match_count > 0) {\n\n // Assume post not added previously.\n $post_already_added = false;\n\n // If posts have already been added to our matches\n // then check to see if we already added this post.\n if(!empty($matching_posts)) {\n \n foreach($matching_posts as $post) {\n // If this post was added previously then let's increment the count\n // for our new matching terms.\n if (isset($post->ID) && $post->ID == $post_ID) {\n $post->count += $match_count;\n // Switch this to true for the check we perform below.\n $post_already_added = true;\n }\n }\n \n // If never found a post with same ID in our $matching_posts\n // list then create a new entry associated with this post and add it.\n if ($post_already_added === false) {\n $new_matching_post = new stdClass();\n $new_matching_post->ID = $post_ID;\n $new_matching_post->count = $match_count;\n array_push($matching_posts, $new_matching_post);\n }\n } else {\n // If no posts have been added yet to $matching_posts then this will be the first.\n $new_matching_post = new stdClass();\n $new_matching_post->ID = $post_ID;\n $new_matching_post->count = $match_count;\n array_push($matching_posts, $new_matching_post);\n }\n }\n }\n }\n }\n }\n }\n\n \n if(!empty($matching_posts)) {\n // Sort the array in order of highest count for total terms in common\n // (most related to least).\n usort($matching_posts, function($a, $b) {\n return strcmp($b->count, $a->count);\n });\n\n // Just take the top 3 most related\n $most_related = array_slice($matching_posts, 0, 3);\n \n // Get the IDs of most related posts.\n $matching_posts = array_map(function($obj) {\n return $obj->ID;\n }, $most_related);\n }\n \n } \n\n return $matching_posts;\n\n\n }\n</code></pre>\n"
},
{
"answer_id": 408877,
"author": "DAU",
"author_id": 225165,
"author_profile": "https://wordpress.stackexchange.com/users/225165",
"pm_score": 0,
"selected": false,
"text": "<p>I followed Brams example but needed to tweak the code at two points for me to run it as expected</p>\n<p><strong>1) clear array $related_tag_ids for each related_post</strong></p>\n<pre><code>foreach($related_all_posts as $related_post){\n // Find all tags of the related post under consideration\n $related_post_tags = get_the_terms( $related_post->ID, 'news-tags' );\n $related_tag_ids = array();\n foreach ( $related_post_tags as $related_post_tag ) {\n $related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query\n }\n\n // Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in\n // an array that has the ID of the related post as array key.\n $related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids));\n}\n</code></pre>\n<p><strong>2) array slice with $preserve_keys set to true</strong></p>\n<pre><code>$related_posts_commonality = array_slice($related_posts_commonality, 0, true);\n</code></pre>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326503",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/159725/"
] | I am trying to write a `.htaccess` rule to redirect the URL to a subdomain.
Example: `example.com/pagecategory/page-single` → `pagecategory.example.com/page-single`
I've added wildcard subdomain on my hosting.
Can anyone help me write the `.htaccess` code? | Let's split the problem up in three bits: retrieving the related posts from the database, sorting them and displaying the result.
Post retrieval
--------------
This is possible using the [taxonomy parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Taxonomy_Parameters) offered in `WP_Query`.
Let's first retrieve the category of the current post and find their IDs:
```
$categories = get_the_terms( get_the_ID(), 'news-category' );
foreach ( $categories as $category ) {
$category_ids[] = $category->term_id;
}
```
We do the same for the tags:
```
$tags = get_the_terms( get_the_ID(), 'news-tags' );
foreach ( $tags as $tag) {
$tag_ids[] = $tag->term_id;
}
```
Then, we build a set of query arguments (we later feed to a `WP_Query`-call):
```
$related_args = array(
'post_type' => array(
'news',
),
'post_status' => 'publish',
'posts_per_page' => -1, // Get all posts
'post__not_in' => array( get_the_ID() ), // Hide current post in list of related content
'tax_query' => array(
'relation' => 'AND', // Make sure to mach both category and term
array(
'taxonomy' => 'news-category',
'field' => 'term_id',
'terms' => $category_ids,
),
array(
'taxonomy' => 'news-tags',
'field' => 'term_id',
'terms' => $tag_ids,
),
),
);
```
Finally, we run the query that gives us an array of
```
$related_all = new WP_Query( $related_args );
```
Please note this query retrieves all posts that match the 'filter', as we're doing the ordering later on. If we'd now only query 4 posts, those might not be the most relevant.
*Sidenote: the above query is quite heavy, in the sense that it (potentially) retrieves a large number of posts. When I've created a related posts section for a client project (also a news section), I ordered by date rather than relevance. That allows you to set a limit to the number of posts you retrieve from the database (change the `-1` to `4` in your case, and add `'orderby' => array( 'date' => 'DESC' )` to the `$related_args`-array). If you want to stick with ordering on the overlap, I suggest you add a date filter in the query arguments, or limit the number of results to some finite value, from which set you then retrieve the most relevant posts.*
Post ordering
-------------
Following the previous step, `$related_all` is a `WP_Query`-object. We access the actual posts as follows, and store them in `$related_all_posts`:
```
$related_all_posts = $related_all->posts;
```
That gives us an array we can more easily work with. We then loop through all the results in that array. Per the comments in the code, when looping through the results, we find the tags associated to the (related) post, find their IDs, compare that with the `$tag_ids` (of the main post) found earlier and see how much overlap there is using [`array_intersect()`](https://secure.php.net/manual/en/function.array-intersect.php):
```
foreach($related_all_posts as $related_post){
// Find all tags of the related post under consideration
$related_post_tags = get_the_terms( $related_post->ID, 'news-tags' );
foreach ( $related_post_tags as $related_post_tag ) {
$related_tag_ids[] = $related_post_tag->term_id; // Save their IDs in a query
}
// Find overlap with tags of main post (in $tag_ids) using array_intersect, and save that number in
// an array that has the ID of the related post as array key.
$related_posts_commonality[$related_post->ID] = count(array_intersect($related_tag_ids, $tag_ids));
}
```
We then sort that latest array by value, from high to low, using [`arsort()`](https://secure.php.net/manual/en/function.arsort.php).
```
arsort($related_posts_commonality);
```
Finally, we limit it to only four posts using [`array_slice()`](https://secure.php.net/manual/en/function.array-slice.php):
```
$related_posts_commonality = array_slice($related_posts_commonality, 0, 4);
```
You can find the IDs of the related posts using [`array_keys`](https://secure.php.net/manual/en/function.array-keys.php), e.g.:
```
$related_posts_IDs = array_keys($related_posts_commonality);
```
Post display
------------
To actually display the posts, there's two routes you can take. You can either use the `$related_posts_commonality` array to loop through the results of `WP_Query` (i.e., `$related_all`), save the matching posts (in their right order) in a new array or object and loop through these once again for display. As this doesn't require additional queries, it's probably the most efficient one. However, it's also a pain.
As such, you can also use simply use the IDs we've just found (`$related_posts_IDs`) to run another query.
```
$related_sorted = WP_query(array('post__in' => $related_posts_IDs));
```
Then, you can use a regular [loop](https://codex.wordpress.org/Class_Reference/WP_Query#Usage) (`while ($related_sorted->have_posts())` and so on) to go through and display the results using functions as `the_title()` and `the_content()`. |
326,530 | <p>I need to disable the Gutenberg text-settings tab in all Blocks. Is this possible with a funtion in funtions.php?</p>
<p>I could disable the colors tab, but found no solution for the text-settings:</p>
<pre><code>function disable_tabs() {
add_theme_support( 'editor-color-palette' );
add_theme_support( 'disable-custom-colors' );
}
add_action( 'after_setup_theme', 'disable_tabs' );
</code></pre>
<p><a href="https://i.stack.imgur.com/QlcmX.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/QlcmX.jpg" alt="The text-settings tab"></a></p>
| [
{
"answer_id": 332375,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 3,
"selected": false,
"text": "<p>The closest I can find in <a href=\"https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/\" rel=\"noreferrer\">the documentation</a> is disabling custom font size (the text input) and forcing the dropdown font size to only contain \"Normal\".</p>\n\n<pre><code>add_action('after_setup_theme', 'wpse_remove_custom_colors');\nfunction wpse_remove_custom_colors() {\n // removes the text box where users can enter custom pixel sizes\n add_theme_support('disable-custom-font-sizes');\n // forces the dropdown for font sizes to only contain \"normal\"\n add_theme_support('editor-font-sizes', array(\n array(\n 'name' => 'Normal',\n 'size' => 16,\n 'slug' => 'normal'\n )\n ) );\n}\n</code></pre>\n\n<p>Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme_support. Hoping someone else from the community knows how to disable the drop caps as well.</p>\n\n<p><strong>Update: a way to remove Drop Caps</strong></p>\n\n<p>This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:</p>\n\n<p>There is a <code>render_block()</code> hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.</p>\n\n<pre><code>add_filter('render_block', function($block_content, $block) {\n // only affect the Core Paragraph block\n if('core/paragraph' === $block['blockName']) {\n // remove the class that creates the drop cap\n $block_content = str_replace('class=\"has-drop-cap\"', '', $block_content);\n }\n // always return the content, whether we changed it or not\n return $block_content;\n}, 10, 2);\n</code></pre>\n\n<p>This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear.</p>\n"
},
{
"answer_id": 386595,
"author": "jg314",
"author_id": 26202,
"author_profile": "https://wordpress.stackexchange.com/users/26202",
"pm_score": 0,
"selected": false,
"text": "<p>As <a href=\"https://wordpress.stackexchange.com/users/172662/jim-rhoades\">Jim Rhoades</a> noted in one of the comments, you can declare support for custom font sizes, but leave out the array of font size options. This removes the "Typography" section entirely so there is no way to choose a font size. The code looks like this:</p>\n<pre><code>add_theme_support( 'editor-font-sizes' );\n</code></pre>\n<p>For those looking for all the code needed to make it work, you would call this from the <code>after_setup_theme</code> hook inside the functions.php file within your theme:</p>\n<pre><code>function theme_setup() {\n add_theme_support( 'editor-font-sizes' );\n}\nadd_action( 'after_setup_theme', 'theme_setup' );\n</code></pre>\n<p>I've tested this in WordPress 5.7, but it's possible it's supported before this version.</p>\n"
},
{
"answer_id": 387087,
"author": "fairport",
"author_id": 202135,
"author_profile": "https://wordpress.stackexchange.com/users/202135",
"pm_score": 3,
"selected": false,
"text": "<p>There's good answers about disabling the font styles but not about disabling the drop cap.</p>\n<p>In WordPress 5.8, you can you the new <code>theme.json</code> feature to disable drop caps in your theme. You need to add a file with name <code>theme.json</code> in the root of your theme. It should have the following content:</p>\n<pre class=\"lang-json prettyprint-override\"><code>{\n "version": 1,\n "settings": {\n "typography": {\n "dropCap": false\n }\n }\n}\n</code></pre>\n<p>If you want to use a filter instead, you can use the following code in WordPress 5.8:</p>\n<pre><code>function disable_drop_cap_ editor_settings_5_8(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_ editor_settings_5_8');\n</code></pre>\n<p>In WordPress 5.7, the drop cap can be disabled with the following code:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_7(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['defaults']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_7');\n</code></pre>\n<p>In WordPress 5.6, the following code works:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_editor_settings_5_6(array $editor_settings): array {\n $editor_settings['__experimentalFeatures']['global']['typography']['dropCap'] = false;\n return $editor_settings;\n}\nadd_filter('block_editor_settings', 'disable_drop_cap_editor_settings_5_6');\n</code></pre>\n<p>In WordPress 5.5, you will have to use JavaScript to accomplish the same thing:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function disable_drop_cap_admin_footer() {\n echo <<<HTML\n<script>\ndocument.addEventListener("DOMContentLoaded", function () {\n var removeDropCap = function(settings, name) {\n \n if (name !== "core/paragraph") {\n return settings;\n }\n var newSettings = Object.assign({}, settings);\n if (\n newSettings.supports &&\n newSettings.supports.__experimentalFeatures &&\n newSettings.supports.__experimentalFeatures.typography &&\n newSettings.supports.__experimentalFeatures.typography.dropCap\n ) {\n newSettings.supports.__experimentalFeatures.typography.dropCap = false;\n }\n return newSettings;\n };\n wp.hooks.addFilter(\n "blocks.registerBlockType",\n "sc/gb/remove-drop-cap",\n removeDropCap,\n );\n});\n</script>\nHTML;\n}\nadd_action('admin_footer', 'disable_drop_cap_admin_footer');\n</code></pre>\n<p>If you want the functionality as a plugin, you can use the <a href=\"https://wordpress.org/plugins/disable-drop-cap/\" rel=\"nofollow noreferrer\">Disable Drop Cap</a> plugin. Full disclosure, I'm the author of the said plugin.</p>\n"
},
{
"answer_id": 395438,
"author": "Kevinleary.net",
"author_id": 1495,
"author_profile": "https://wordpress.stackexchange.com/users/1495",
"pm_score": 1,
"selected": false,
"text": "<p>This was the true, final answer that solved for the exact scenario described in the original question:</p>\n<pre><code>/**\n * Disable Native Gutenberg Features\n */\nfunction gutenberg_removals()\n{\n add_theme_support('disable-custom-font-sizes');\n add_theme_support('editor-font-sizes', []);\n}\nadd_action('after_setup_theme', 'gutenberg_removals');\n</code></pre>\n<p>Passing an empty array to the <code>editor-font-sizes</code> avoid a PHP notice for an invalid argument.</p>\n"
}
] | 2019/01/24 | [
"https://wordpress.stackexchange.com/questions/326530",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81609/"
] | I need to disable the Gutenberg text-settings tab in all Blocks. Is this possible with a funtion in funtions.php?
I could disable the colors tab, but found no solution for the text-settings:
```
function disable_tabs() {
add_theme_support( 'editor-color-palette' );
add_theme_support( 'disable-custom-colors' );
}
add_action( 'after_setup_theme', 'disable_tabs' );
```
[](https://i.stack.imgur.com/QlcmX.jpg) | The closest I can find in [the documentation](https://wordpress.org/gutenberg/handbook/designers-developers/developers/themes/theme-support/) is disabling custom font size (the text input) and forcing the dropdown font size to only contain "Normal".
```
add_action('after_setup_theme', 'wpse_remove_custom_colors');
function wpse_remove_custom_colors() {
// removes the text box where users can enter custom pixel sizes
add_theme_support('disable-custom-font-sizes');
// forces the dropdown for font sizes to only contain "normal"
add_theme_support('editor-font-sizes', array(
array(
'name' => 'Normal',
'size' => 16,
'slug' => 'normal'
)
) );
}
```
Note this may not work for non-Core blocks - they may have their own way of registering font size etc. that isn't affected by theme\_support. Hoping someone else from the community knows how to disable the drop caps as well.
**Update: a way to remove Drop Caps**
This wouldn't be my preferred method, because you can still add a Drop Cap in the editor and it just doesn't render in the front end, but it's all I have been able to achieve so far:
There is a `render_block()` hook where you can change what renders on the front end without changing what shows in the editor or gets saved to the database.
```
add_filter('render_block', function($block_content, $block) {
// only affect the Core Paragraph block
if('core/paragraph' === $block['blockName']) {
// remove the class that creates the drop cap
$block_content = str_replace('class="has-drop-cap"', '', $block_content);
}
// always return the content, whether we changed it or not
return $block_content;
}, 10, 2);
```
This method changes the outer appearance rather than the actual content, so that if you ever wanted to allow drop caps, you could just remove the filter and all the ones that people had added in the editor would suddenly appear. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.