qid
int64 4
8.14M
| question
stringlengths 20
48.3k
| answers
list | date
stringlengths 10
10
| metadata
list | input
stringlengths 12
45k
| output
stringlengths 2
31.8k
|
---|---|---|---|---|---|---|
259,657 | <p>I'm building a plugin using the <a href="https://github.com/DevinVinson/WordPress-Plugin-Boilerplate" rel="nofollow noreferrer">WordPress Plugin Boilerplate by DevinVinson</a>.</p>
<p>Everything works fine, except one thing:</p>
<p>I'm trying to enqueue scripts and css only when a shortcode is present in the page. </p>
<p>In <code>define_public_hooks</code> function, I added a call to the loader to register scripts instead of enqueuing them:</p>
<pre><code>private function define_public_hooks() {
// ...
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_styles' );
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_scripts' );
// ...
}
</code></pre>
<p>Then in <code>class-my-plugin-public.php</code> file I created two public functions <code>register_styles()</code> and <code>register_scripts()</code>. Inside these functions, I just register scripts and styles, instead of enqueuing them. It's something basic, like this:</p>
<pre><code>public function register_scripts() {
wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key .'&amp;v=3&amp;libraries=places', array( 'jquery' ), '3', true );
}
</code></pre>
<p>Then I would like to enqueue them in the shortcode return function, but they do not get registered at all.</p>
<p>I checked with <code>wp_script_is( $this->plugin_name . '_google_maps_api', 'registered' )</code>, and it returns <code>false</code>.</p>
<p>If I make the very same stuff, but with <code>enqueue</code> instead of <code>register</code> everything works fine.</p>
<p>Any idea why?</p>
| [
{
"answer_id": 259662,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 0,
"selected": false,
"text": "<p>So the problem is that the first argument to the <code>add_action</code> call needs to be a <em>WordPress</em> action name... So \"wp_register_script\", not being a WP action, is never called.</p>\n\n<p>I'd suggest all you need to do, really, is add your registering calls to your plugin's enqueue_scripts function - no need to fuss with the define_public_hooks, or create a new register_scripts function. Simply go with the existing enqueue_scripts function, but add your registrations there:</p>\n\n<pre><code>public function enqueue_scripts() {\n wp_enqueue_script( $this->plugin_name, plugin_dir_url( __FILE__ ) . 'js/plugin-name-public.js', array( 'jquery' ), $this->version, false );\n\n // NOTICE this is a *registration* only:\n wp_register_script( $this->plugin_name.'_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key.'&amp;v=3&amp;libraries=places', array( 'jquery' ), '3', true ); \n}\n</code></pre>\n\n<p>Then when your short code, your script should be registered, ready to be enqueued.</p>\n\n<p>Hope this helps!</p>\n"
},
{
"answer_id": 259671,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h1>Why it's not working:</h1>\n\n<p>You need to use the <a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"noreferrer\"><code>wp_enqueue_scripts</code></a> action hook. You've used <code>wp_register_script</code> as an action hook, however, there is no action hook named <code>wp_register_script</code> in WordPress core.</p>\n\n<p>If this was just a silly mistake, then you already have the answer. Read on if you need more information regarding the topic:</p>\n\n<hr>\n\n<p>Attaching a callback function to <a href=\"https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/\" rel=\"noreferrer\"><code>wp_enqueue_scripts</code></a> <a href=\"https://developer.wordpress.org/plugins/hooks/actions/\" rel=\"noreferrer\">action hook</a> doesn't mean your scripts and styles will be enqueued, it simply means when you want to execute that <a href=\"http://php.net/manual/en/language.types.callable.php\" rel=\"noreferrer\">callback function</a>.</p>\n\n<p>The original registering and enqueuing is done by functions such as: <code>wp_register_script()</code>, <code>wp_register_style</code>, <code>wp_enqueue_script()</code>, <code>wp_enqueue_style()</code> etc., not by any <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"noreferrer\">hook</a>.</p>\n\n<blockquote>\n <p>Note the difference between the role of functions and hooks:</p>\n \n <ul>\n <li><p>A <a href=\"http://php.net/manual/en/functions.user-defined.php\" rel=\"noreferrer\"><strong>function</strong></a> executes some CODE to accomplish predefined tasks when called.</p>\n \n <p>Example: these all are WordPress core functions: <code>wp_register_script()</code>, <code>wp_register_style</code>, <code>wp_enqueue_script()</code>, <code>wp_enqueue_style()</code>. </p></li>\n <li><p>A <a href=\"https://developer.wordpress.org/plugins/hooks/\" rel=\"noreferrer\"><strong>hook</strong></a> only attaches a <a href=\"http://php.net/manual/en/function.is-callable.php\" rel=\"noreferrer\">callable</a> function (to be executed later) at a predefined point of CODE execution.</p>\n \n <p>Example: this is a WordPress core (action) hook: <code>wp_enqueue_scripts</code> - notice the <code>s</code> (plural) at the end.</p>\n \n <p><strong><em>Double check:</em></strong> <code>wp_enqueue_script()</code> is a function and <code>wp_enqueue_scripts</code> is an action hook.</p></li>\n </ul>\n</blockquote>\n\n<h1>The correct CODE:</h1>\n\n<p>So your corrected CODE should be like:</p>\n\n<pre><code>private function define_public_hooks() {\n // ...\n $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_styles' );\n $this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_scripts' );\n // ...\n}\n</code></pre>\n\n<p>Then,</p>\n\n<pre><code>public function register_scripts() {\n wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key.'&amp;v=3&amp;libraries=places', array( 'jquery' ), '3', true );\n}\n</code></pre>\n\n<p>After that, you enqueue the script (& style) from within you shortcode handler function:</p>\n\n<pre><code>public function your_shortcode_handler( $atts ) {\n // shortcode related CODE\n wp_enqueue_script( $this->plugin_name . '_google_maps_api' );\n // more shortcode related CODE\n}\n</code></pre>\n\n<p>With this CODE, your scripts / styles enqueued from <code>your_shortcode_handler</code> function will only be added to your site when there is a shortcode in that particular URL.</p>\n\n<h2>Further Reading:</h2>\n\n<p><a href=\"https://wordpress.stackexchange.com/a/165759/110572\">This answer</a> has an interesting discussion on enqueuing scripts & styles only when shortcode is present. </p>\n"
}
]
| 2017/03/10 | [
"https://wordpress.stackexchange.com/questions/259657",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4155/"
]
| I'm building a plugin using the [WordPress Plugin Boilerplate by DevinVinson](https://github.com/DevinVinson/WordPress-Plugin-Boilerplate).
Everything works fine, except one thing:
I'm trying to enqueue scripts and css only when a shortcode is present in the page.
In `define_public_hooks` function, I added a call to the loader to register scripts instead of enqueuing them:
```
private function define_public_hooks() {
// ...
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_styles' );
$this->loader->add_action( 'wp_register_script', $plugin_public, 'register_scripts' );
// ...
}
```
Then in `class-my-plugin-public.php` file I created two public functions `register_styles()` and `register_scripts()`. Inside these functions, I just register scripts and styles, instead of enqueuing them. It's something basic, like this:
```
public function register_scripts() {
wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key .'&v=3&libraries=places', array( 'jquery' ), '3', true );
}
```
Then I would like to enqueue them in the shortcode return function, but they do not get registered at all.
I checked with `wp_script_is( $this->plugin_name . '_google_maps_api', 'registered' )`, and it returns `false`.
If I make the very same stuff, but with `enqueue` instead of `register` everything works fine.
Any idea why? | Why it's not working:
=====================
You need to use the [`wp_enqueue_scripts`](https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/) action hook. You've used `wp_register_script` as an action hook, however, there is no action hook named `wp_register_script` in WordPress core.
If this was just a silly mistake, then you already have the answer. Read on if you need more information regarding the topic:
---
Attaching a callback function to [`wp_enqueue_scripts`](https://developer.wordpress.org/reference/hooks/wp_enqueue_scripts/) [action hook](https://developer.wordpress.org/plugins/hooks/actions/) doesn't mean your scripts and styles will be enqueued, it simply means when you want to execute that [callback function](http://php.net/manual/en/language.types.callable.php).
The original registering and enqueuing is done by functions such as: `wp_register_script()`, `wp_register_style`, `wp_enqueue_script()`, `wp_enqueue_style()` etc., not by any [hook](https://developer.wordpress.org/plugins/hooks/).
>
> Note the difference between the role of functions and hooks:
>
>
> * A [**function**](http://php.net/manual/en/functions.user-defined.php) executes some CODE to accomplish predefined tasks when called.
>
>
> Example: these all are WordPress core functions: `wp_register_script()`, `wp_register_style`, `wp_enqueue_script()`, `wp_enqueue_style()`.
> * A [**hook**](https://developer.wordpress.org/plugins/hooks/) only attaches a [callable](http://php.net/manual/en/function.is-callable.php) function (to be executed later) at a predefined point of CODE execution.
>
>
> Example: this is a WordPress core (action) hook: `wp_enqueue_scripts` - notice the `s` (plural) at the end.
>
>
> ***Double check:*** `wp_enqueue_script()` is a function and `wp_enqueue_scripts` is an action hook.
>
>
>
The correct CODE:
=================
So your corrected CODE should be like:
```
private function define_public_hooks() {
// ...
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_styles' );
$this->loader->add_action( 'wp_enqueue_scripts', $plugin_public, 'register_scripts' );
// ...
}
```
Then,
```
public function register_scripts() {
wp_register_script( $this->plugin_name . '_google_maps_api', '//maps.googleapis.com/maps/api/js?key='. $gmap_key.'&v=3&libraries=places', array( 'jquery' ), '3', true );
}
```
After that, you enqueue the script (& style) from within you shortcode handler function:
```
public function your_shortcode_handler( $atts ) {
// shortcode related CODE
wp_enqueue_script( $this->plugin_name . '_google_maps_api' );
// more shortcode related CODE
}
```
With this CODE, your scripts / styles enqueued from `your_shortcode_handler` function will only be added to your site when there is a shortcode in that particular URL.
Further Reading:
----------------
[This answer](https://wordpress.stackexchange.com/a/165759/110572) has an interesting discussion on enqueuing scripts & styles only when shortcode is present. |
259,677 | <p>I am a WP beginner and am trying to upload a web module to a wordpress site. The site is a landing page, and a link on the landing page leads to a demoable web app. The web app was custom written in HTML and JS and I need to upload those files to this route in the WP site.</p>
<p>Does anyone have any suggestions/insight/advice?</p>
<p>Thank you!</p>
| [
{
"answer_id": 259684,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 0,
"selected": false,
"text": "<p>Welcome to WordPress!</p>\n\n<p>Your best bet would be to setup a localhost server <a href=\"http://www.wampserver.com/en/\" rel=\"nofollow noreferrer\">Windows</a> or <a href=\"https://www.mamp.info/en/\" rel=\"nofollow noreferrer\">Mac</a> </p>\n\n<p>The install a copy of WordPress, and study how the default themes are put together, start looking at how <a href=\"https://codex.wordpress.org/Template_Tags\" rel=\"nofollow noreferrer\">template tags</a> work, and how the structure of the themes works.</p>\n\n<p>After that you can start putting your HTML web pages into WordPress by <a href=\"https://codex.wordpress.org/Theme_Development\" rel=\"nofollow noreferrer\">building your own theme</a>.</p>\n\n<p>A word for the wise, don't go buying a \"premium\" theme to study and learn from, they are more often than not overly complicated, bloated with useless features and very hard to work with.</p>\n"
},
{
"answer_id": 259685,
"author": "RiotAct",
"author_id": 40891,
"author_profile": "https://wordpress.stackexchange.com/users/40891",
"pm_score": 1,
"selected": false,
"text": "<p>All you need to do is create a custom page for your theme. Here is a very brief example:</p>\n\n<p>Create a file called: page-example.php</p>\n\n<pre><code><?php \n/* \nTemplate Name: Example Page\n*/\n?>\n\n<?php get_header(); ?>\n\nThe html code will go here. Don't add the <head> or <body> info. \n\n<?php get_footer(); ?>\n</code></pre>\n\n<p>The next thing to do is add the following to your functions.php file:</p>\n\n<pre><code>function load_example_scripts() {\nwp_enqueue_script('moment', get_stylesheet_directory_uri() . '/js/example.js'); \n}\n\nadd_action( 'wp_enqueue_scripts', 'load_example_scripts' );\n</code></pre>\n\n<p>Now upload the page-example.php to your main template folder (where header.php, footer.php, functions.php are)</p>\n\n<p>I usually add a folder to my themes named \"JS\" and put all jquery scripts there. So upload the example.js file to the \"JS\" folder of your theme.</p>\n\n<p>Finally, go to the wordpress admin, and edit the page where you want this to appear and on the side menu under \"templates\", select \"example\".</p>\n\n<p>I would have to see the exact code to give you more help, but that is the basic idea.</p>\n"
}
]
| 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115201/"
]
| I am a WP beginner and am trying to upload a web module to a wordpress site. The site is a landing page, and a link on the landing page leads to a demoable web app. The web app was custom written in HTML and JS and I need to upload those files to this route in the WP site.
Does anyone have any suggestions/insight/advice?
Thank you! | All you need to do is create a custom page for your theme. Here is a very brief example:
Create a file called: page-example.php
```
<?php
/*
Template Name: Example Page
*/
?>
<?php get_header(); ?>
The html code will go here. Don't add the <head> or <body> info.
<?php get_footer(); ?>
```
The next thing to do is add the following to your functions.php file:
```
function load_example_scripts() {
wp_enqueue_script('moment', get_stylesheet_directory_uri() . '/js/example.js');
}
add_action( 'wp_enqueue_scripts', 'load_example_scripts' );
```
Now upload the page-example.php to your main template folder (where header.php, footer.php, functions.php are)
I usually add a folder to my themes named "JS" and put all jquery scripts there. So upload the example.js file to the "JS" folder of your theme.
Finally, go to the wordpress admin, and edit the page where you want this to appear and on the side menu under "templates", select "example".
I would have to see the exact code to give you more help, but that is the basic idea. |
259,707 | <p>I want to add image from post content in my rss feed but all the tutorials that I find are only for featured image. I want image from post content and not featured image. How can I do this?</p>
| [
{
"answer_id": 259708,
"author": "shpwebhost",
"author_id": 114992,
"author_profile": "https://wordpress.stackexchange.com/users/114992",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to use content images on other website or pages you may use WordPress REST API. This will help your access all data of the content.</p>\n"
},
{
"answer_id": 259724,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 1,
"selected": true,
"text": "<p>Here is the <a href=\"http://wpcodesnippet.com/display-featured-post-thumbnails-wordpress-feeds/\" rel=\"nofollow noreferrer\">link</a> I found a solution. How to display featured post thumbnails in WordPress feeds</p>\n\n<p>paste this code snippet in your theme functions.php file</p>\n\n<pre><code>// display featured post thumbnails in WordPress feeds\n function wcs_post_thumbnails_in_feeds( $content ) {\n global $post;\n if( has_post_thumbnail( $post->ID ) ) {\n\n//if you want to show thumbnail image\n $content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;\n\n// if you want to show full image\n//$content = '<p>' . get_the_post_thumbnail( $post->ID,'full' ) . '</p>' . $content;\n\n//if you want to custom image using add_image_size()\n //$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'custom-image-size' ) . '</figure>' . $content;\n }\n return $content;\n }\n add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );\n add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );\n</code></pre>\n\n<p>This is the concepts how to you show external link image. How you fetch the external image, it upon you.</p>\n\n<p>it's showing all the post same image. Just change image link for each post.\nex: src=\"'.$image_url.'\"</p>\n\n<pre><code>function rss_feed_from_external_link( $content ) {\n global $post;\n $content = '<figure><img width=\"150\" height=\"128\" src=\"https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png\" class=\"attachment-thumbnail size-thumbnail wp-post-image\" alt=\"\" sizes=\"100vw\" /></figure>' . $content;\n return $content;\n}\nadd_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );\nadd_filter( 'the_content_feed', 'rss_feed_from_external_link' );\n</code></pre>\n\n<p>Image showing for custom field.</p>\n\n<pre><code>add_filter('the_content', 'custom_fields_for_feeds');\nadd_filter('the_meta','custom_files_for_feed');\n\nfunction custom_fields_for_feeds( $content ) {\n\n global $post;\n global $post;\n// Get the custom fields ***\n\n// Checks for thumbnail\n $image = get_post_meta($post->ID, 'Thumbnail', $single = true);\n// Checks for thumbnail alt text\n $image_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);\n if($image_alt == '') { $image_alt = 'This image has no alt text'; }\n\n if($image !== '') {\n $content = '<figure><img src=\"'.$image.'\" alt=\"'.$image_alt.'\" /></figure>' . $content;\n return $content;\n } \n else {\n $content = $content;\n return $content;\n }\n\nadd_filter('the_content', 'custom_fields_for_feeds');\nadd_filter('the_meta','custom_files_for_feed');\n</code></pre>\n\n<p>You can also use custom image fields to display in the RSS feed.</p>\n\n<p>Let me know you not solve your problem.</p>\n"
},
{
"answer_id": 345822,
"author": "Jodyshop",
"author_id": 127580,
"author_profile": "https://wordpress.stackexchange.com/users/127580",
"pm_score": 0,
"selected": false,
"text": "<p>This code is working like a charm, you can add a custom image without affecting any page (the image only shown in the RSS feed file).</p>\n\n<pre><code>function rss_feed_from_external_link( $content ) {\n global $post;\n $content = '<figure><img width=\"100%\" height=\"auto\" src=\"img_src\" class=\"\" alt=\"\" /></figure>' . $content;\n return $content;\n}\nadd_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );\nadd_filter( 'the_content_feed', 'rss_feed_from_external_link' );\n</code></pre>\n\n<p>Thank you</p>\n"
}
]
| 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/100682/"
]
| I want to add image from post content in my rss feed but all the tutorials that I find are only for featured image. I want image from post content and not featured image. How can I do this? | Here is the [link](http://wpcodesnippet.com/display-featured-post-thumbnails-wordpress-feeds/) I found a solution. How to display featured post thumbnails in WordPress feeds
paste this code snippet in your theme functions.php file
```
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
//if you want to show thumbnail image
$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;
// if you want to show full image
//$content = '<p>' . get_the_post_thumbnail( $post->ID,'full' ) . '</p>' . $content;
//if you want to custom image using add_image_size()
//$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'custom-image-size' ) . '</figure>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
```
This is the concepts how to you show external link image. How you fetch the external image, it upon you.
it's showing all the post same image. Just change image link for each post.
ex: src="'.$image\_url.'"
```
function rss_feed_from_external_link( $content ) {
global $post;
$content = '<figure><img width="150" height="128" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" sizes="100vw" /></figure>' . $content;
return $content;
}
add_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );
add_filter( 'the_content_feed', 'rss_feed_from_external_link' );
```
Image showing for custom field.
```
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
function custom_fields_for_feeds( $content ) {
global $post;
global $post;
// Get the custom fields ***
// Checks for thumbnail
$image = get_post_meta($post->ID, 'Thumbnail', $single = true);
// Checks for thumbnail alt text
$image_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);
if($image_alt == '') { $image_alt = 'This image has no alt text'; }
if($image !== '') {
$content = '<figure><img src="'.$image.'" alt="'.$image_alt.'" /></figure>' . $content;
return $content;
}
else {
$content = $content;
return $content;
}
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
```
You can also use custom image fields to display in the RSS feed.
Let me know you not solve your problem. |
259,713 | <p>As everyone might be aware that there are many wordpress website builders in the market, Can anyone explain me whats the real difference between Theme Builders and Page Builders? I looked up in google but couldn't find the answer to it.</p>
| [
{
"answer_id": 259708,
"author": "shpwebhost",
"author_id": 114992,
"author_profile": "https://wordpress.stackexchange.com/users/114992",
"pm_score": -1,
"selected": false,
"text": "<p>If you want to use content images on other website or pages you may use WordPress REST API. This will help your access all data of the content.</p>\n"
},
{
"answer_id": 259724,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 1,
"selected": true,
"text": "<p>Here is the <a href=\"http://wpcodesnippet.com/display-featured-post-thumbnails-wordpress-feeds/\" rel=\"nofollow noreferrer\">link</a> I found a solution. How to display featured post thumbnails in WordPress feeds</p>\n\n<p>paste this code snippet in your theme functions.php file</p>\n\n<pre><code>// display featured post thumbnails in WordPress feeds\n function wcs_post_thumbnails_in_feeds( $content ) {\n global $post;\n if( has_post_thumbnail( $post->ID ) ) {\n\n//if you want to show thumbnail image\n $content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;\n\n// if you want to show full image\n//$content = '<p>' . get_the_post_thumbnail( $post->ID,'full' ) . '</p>' . $content;\n\n//if you want to custom image using add_image_size()\n //$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'custom-image-size' ) . '</figure>' . $content;\n }\n return $content;\n }\n add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );\n add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );\n</code></pre>\n\n<p>This is the concepts how to you show external link image. How you fetch the external image, it upon you.</p>\n\n<p>it's showing all the post same image. Just change image link for each post.\nex: src=\"'.$image_url.'\"</p>\n\n<pre><code>function rss_feed_from_external_link( $content ) {\n global $post;\n $content = '<figure><img width=\"150\" height=\"128\" src=\"https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png\" class=\"attachment-thumbnail size-thumbnail wp-post-image\" alt=\"\" sizes=\"100vw\" /></figure>' . $content;\n return $content;\n}\nadd_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );\nadd_filter( 'the_content_feed', 'rss_feed_from_external_link' );\n</code></pre>\n\n<p>Image showing for custom field.</p>\n\n<pre><code>add_filter('the_content', 'custom_fields_for_feeds');\nadd_filter('the_meta','custom_files_for_feed');\n\nfunction custom_fields_for_feeds( $content ) {\n\n global $post;\n global $post;\n// Get the custom fields ***\n\n// Checks for thumbnail\n $image = get_post_meta($post->ID, 'Thumbnail', $single = true);\n// Checks for thumbnail alt text\n $image_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);\n if($image_alt == '') { $image_alt = 'This image has no alt text'; }\n\n if($image !== '') {\n $content = '<figure><img src=\"'.$image.'\" alt=\"'.$image_alt.'\" /></figure>' . $content;\n return $content;\n } \n else {\n $content = $content;\n return $content;\n }\n\nadd_filter('the_content', 'custom_fields_for_feeds');\nadd_filter('the_meta','custom_files_for_feed');\n</code></pre>\n\n<p>You can also use custom image fields to display in the RSS feed.</p>\n\n<p>Let me know you not solve your problem.</p>\n"
},
{
"answer_id": 345822,
"author": "Jodyshop",
"author_id": 127580,
"author_profile": "https://wordpress.stackexchange.com/users/127580",
"pm_score": 0,
"selected": false,
"text": "<p>This code is working like a charm, you can add a custom image without affecting any page (the image only shown in the RSS feed file).</p>\n\n<pre><code>function rss_feed_from_external_link( $content ) {\n global $post;\n $content = '<figure><img width=\"100%\" height=\"auto\" src=\"img_src\" class=\"\" alt=\"\" /></figure>' . $content;\n return $content;\n}\nadd_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );\nadd_filter( 'the_content_feed', 'rss_feed_from_external_link' );\n</code></pre>\n\n<p>Thank you</p>\n"
}
]
| 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115217/"
]
| As everyone might be aware that there are many wordpress website builders in the market, Can anyone explain me whats the real difference between Theme Builders and Page Builders? I looked up in google but couldn't find the answer to it. | Here is the [link](http://wpcodesnippet.com/display-featured-post-thumbnails-wordpress-feeds/) I found a solution. How to display featured post thumbnails in WordPress feeds
paste this code snippet in your theme functions.php file
```
// display featured post thumbnails in WordPress feeds
function wcs_post_thumbnails_in_feeds( $content ) {
global $post;
if( has_post_thumbnail( $post->ID ) ) {
//if you want to show thumbnail image
$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'thumbnail' ) . '</figure>' . $content;
// if you want to show full image
//$content = '<p>' . get_the_post_thumbnail( $post->ID,'full' ) . '</p>' . $content;
//if you want to custom image using add_image_size()
//$content = '<figure>' . get_the_post_thumbnail( $post->ID, 'custom-image-size' ) . '</figure>' . $content;
}
return $content;
}
add_filter( 'the_excerpt_rss', 'wcs_post_thumbnails_in_feeds' );
add_filter( 'the_content_feed', 'wcs_post_thumbnails_in_feeds' );
```
This is the concepts how to you show external link image. How you fetch the external image, it upon you.
it's showing all the post same image. Just change image link for each post.
ex: src="'.$image\_url.'"
```
function rss_feed_from_external_link( $content ) {
global $post;
$content = '<figure><img width="150" height="128" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png" class="attachment-thumbnail size-thumbnail wp-post-image" alt="" sizes="100vw" /></figure>' . $content;
return $content;
}
add_filter( 'the_excerpt_rss', 'rss_feed_from_external_link' );
add_filter( 'the_content_feed', 'rss_feed_from_external_link' );
```
Image showing for custom field.
```
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
function custom_fields_for_feeds( $content ) {
global $post;
global $post;
// Get the custom fields ***
// Checks for thumbnail
$image = get_post_meta($post->ID, 'Thumbnail', $single = true);
// Checks for thumbnail alt text
$image_alt = get_post_meta($post->ID, 'Thumbnail Alt', $single = true);
if($image_alt == '') { $image_alt = 'This image has no alt text'; }
if($image !== '') {
$content = '<figure><img src="'.$image.'" alt="'.$image_alt.'" /></figure>' . $content;
return $content;
}
else {
$content = $content;
return $content;
}
add_filter('the_content', 'custom_fields_for_feeds');
add_filter('the_meta','custom_files_for_feed');
```
You can also use custom image fields to display in the RSS feed.
Let me know you not solve your problem. |
259,716 | <p>When I call <a href="https://developer.wordpress.org/reference/functions/get_search_form" rel="nofollow noreferrer"><code>get_search_form()</code></a>, it outputs:</p>
<pre><code><form class="search-form">
<meta itemprop="target">
<input type="search">
<input type="submit">
</form>
</code></pre>
<p>But I wanted it to generate with a <code>span</code> inside, like:</p>
<pre><code><form class="search-form">
<meta itemprop="target">
<input type="search">
<span class="submit-icon"></span>
<input type="submit">
</form>
</code></pre>
<p>Any ideas?</p>
| [
{
"answer_id": 259717,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 2,
"selected": false,
"text": "<p>Tested and worked fine.</p>\n\n<p>Add this code in functions.php, You will get what you want. Now you can modify search form as you need. </p>\n\n<pre><code>function my_search_form( $form ) {\n $form = '<form role=\"search\" method=\"get\" class=\"search-form\" action=\"' . home_url( '/' ) . '\" >\n <div><label>\n <span class=\"screen-reader-text\"> ' . _x( 'Search for:', 'label' ) .'</span>\n <input type=\"search\" class=\"search-field\"\n placeholder=\"' . get_search_query() . '\"\n value=\"' . get_search_query().'\" name=\"s\"\n title=\"' . esc_attr_x( 'Search for:', 'label' ).' \" />\n </label>\n <span class=\"submit-icon\"></span>\n <input type=\"submit\" class=\"search-submit\"\n value=\"' . esc_attr_x( 'Search', 'submit button' ). '\" />\n </form>\n ';\n\n return $form;\n}\nadd_filter( 'get_search_form', 'my_search_form', 99 );\necho get_search_form();\n</code></pre>\n"
},
{
"answer_id": 259728,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 2,
"selected": false,
"text": "<p>You need to create a php file named searchform.php in your theme.. then just copy and paste the search form code like this below</p>\n\n<pre><code><form method=\"get\" id=\"searchform\" action=\"<?php echo esc_url( home_url( '/' ) ); ?>\">\n <label for=\"s\" class=\"assistive-text\"><?php _e( 'Search', 'theme_text_domain' ); ?></label>\n <input type=\"text\" class=\"field\" name=\"s\" id=\"s\" placeholder=\"<?php esc_attr_e( 'Search', 'theme_text_domain' ); ?>\" />\n <input type=\"submit\" class=\"submit\" name=\"submit\" id=\"searchsubmit\" value=\"<?php esc_attr_e( 'Search', 'theme_text_domain' ); ?>\" />\n </form>\n</code></pre>\n\n<p>Now you can modify the form deleting or inserting anything in the above code..</p>\n"
},
{
"answer_id": 259772,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 3,
"selected": true,
"text": "<p>If we look at the source code of <a href=\"https://developer.wordpress.org/reference/functions/get_search_form/\" rel=\"nofollow noreferrer\"><code>get_search_form()</code></a>, notice that before the form gets rendered, the <code>search_form_format</code> filter hook gets fired. We can use that to add another filter attached to <code>get_search_form</code> where the callback is dependent upon the format.</p>\n\n<pre><code>add_filter( 'search_form_format', 'wpse_259716_search_form_format', 99, 1 );\nfunction wpse_259716_search_form_format( $format ) {\n if( in_array( $format, array( 'xhtml', 'html5' ) ) ) {\n add_filter( 'get_search_form', \"wpse_259716_get_search_form_$format\", 99, 1 );\n }\n return $format;\n}\n\nfunction wpse_259716_get_search_form_xhtml( $form ) {\n $search = '<input type=\"submit\"';\n $xhtml = 'some xhtml';\n $replace = $xhtml . $search;\n return str_replace( $search, $replace, $form );\n}\n\nfunction wpse_259716_get_search_form_html5( $form ) {\n $search = '<input type=\"submit\"';\n $html5 = 'some html5';\n $replace = $html5 . $search;\n return str_replace( $search, $replace, $form );\n}\n</code></pre>\n\n<p>Alternatively, you could use a class-based approach.</p>\n\n<pre><code>$wpse_259716 = new wpse_259716();\nadd_filter( 'search_form_format', array( $wpse_259716, 'search_form_format' ), 99, 1 );\nadd_filter( 'get_search_form', array( $wpse_259716, 'get_search_form' ), 99, 1 );\n\nclass wpse_259716 {\n protected $format;\n public function search_form_format( $format ) {\n return $this->format = $format;\n }\n public function get_search_form( $form ) {\n $search = $replace = '<input type=\"submit\"';\n if( 'xhtml' === $this->format ) {\n $xhtml = 'some xhtml';\n $replace = $xhmtl . $search;\n }\n elseif( 'html5' === $this->format ) {\n $html5 = 'some html5';\n $replace = $html5 . $search;\n }\n return str_replace( $search, $replace, $form );\n }\n}\n</code></pre>\n"
}
]
| 2017/03/11 | [
"https://wordpress.stackexchange.com/questions/259716",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115077/"
]
| When I call [`get_search_form()`](https://developer.wordpress.org/reference/functions/get_search_form), it outputs:
```
<form class="search-form">
<meta itemprop="target">
<input type="search">
<input type="submit">
</form>
```
But I wanted it to generate with a `span` inside, like:
```
<form class="search-form">
<meta itemprop="target">
<input type="search">
<span class="submit-icon"></span>
<input type="submit">
</form>
```
Any ideas? | If we look at the source code of [`get_search_form()`](https://developer.wordpress.org/reference/functions/get_search_form/), notice that before the form gets rendered, the `search_form_format` filter hook gets fired. We can use that to add another filter attached to `get_search_form` where the callback is dependent upon the format.
```
add_filter( 'search_form_format', 'wpse_259716_search_form_format', 99, 1 );
function wpse_259716_search_form_format( $format ) {
if( in_array( $format, array( 'xhtml', 'html5' ) ) ) {
add_filter( 'get_search_form', "wpse_259716_get_search_form_$format", 99, 1 );
}
return $format;
}
function wpse_259716_get_search_form_xhtml( $form ) {
$search = '<input type="submit"';
$xhtml = 'some xhtml';
$replace = $xhtml . $search;
return str_replace( $search, $replace, $form );
}
function wpse_259716_get_search_form_html5( $form ) {
$search = '<input type="submit"';
$html5 = 'some html5';
$replace = $html5 . $search;
return str_replace( $search, $replace, $form );
}
```
Alternatively, you could use a class-based approach.
```
$wpse_259716 = new wpse_259716();
add_filter( 'search_form_format', array( $wpse_259716, 'search_form_format' ), 99, 1 );
add_filter( 'get_search_form', array( $wpse_259716, 'get_search_form' ), 99, 1 );
class wpse_259716 {
protected $format;
public function search_form_format( $format ) {
return $this->format = $format;
}
public function get_search_form( $form ) {
$search = $replace = '<input type="submit"';
if( 'xhtml' === $this->format ) {
$xhtml = 'some xhtml';
$replace = $xhmtl . $search;
}
elseif( 'html5' === $this->format ) {
$html5 = 'some html5';
$replace = $html5 . $search;
}
return str_replace( $search, $replace, $form );
}
}
``` |
259,811 | <p>I have recently setup a Linode Apache2 Debian server and I am hosting my WordPress site on it. It seems I can only connect to the server with SFTP.</p>
<p>When I attempt to add/update a plugin I am presented with this screen:</p>
<p><a href="https://i.stack.imgur.com/oSyRL.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oSyRL.png" alt="enter image description here"></a></p>
<p>There doesn't appear to be an option to use SFTP instead of FTP or FTPS. I cannot find any plugins or anything to do this.</p>
<p>Because of this, I cannot add/update plugins.</p>
<p>What are my options?</p>
| [
{
"answer_id": 259857,
"author": "geraldo",
"author_id": 38096,
"author_profile": "https://wordpress.stackexchange.com/users/38096",
"pm_score": 1,
"selected": false,
"text": "<p>I use <a href=\"https://wordpress.org/plugins/ssh-sftp-updater-support/\" rel=\"nofollow noreferrer\">SSH SFTP Updater Support</a> and it works fine. From the project description:</p>\n\n<blockquote>\n <p>\"SSH SFTP Updater Support\" is the easiest way to keep your WordPress\n installation up-to-date with SFTP.</p>\n</blockquote>\n"
},
{
"answer_id": 260872,
"author": "LBNerdBard",
"author_id": 17076,
"author_profile": "https://wordpress.stackexchange.com/users/17076",
"pm_score": 3,
"selected": true,
"text": "<p>Looks like a permissions issue:</p>\n\n<pre><code>sudo chown -R www-data:www-data /var/www\n</code></pre>\n"
}
]
| 2017/03/12 | [
"https://wordpress.stackexchange.com/questions/259811",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86794/"
]
| I have recently setup a Linode Apache2 Debian server and I am hosting my WordPress site on it. It seems I can only connect to the server with SFTP.
When I attempt to add/update a plugin I am presented with this screen:
[](https://i.stack.imgur.com/oSyRL.png)
There doesn't appear to be an option to use SFTP instead of FTP or FTPS. I cannot find any plugins or anything to do this.
Because of this, I cannot add/update plugins.
What are my options? | Looks like a permissions issue:
```
sudo chown -R www-data:www-data /var/www
``` |
259,834 | <p>I've followed all the steps for migrating my existing wordpress site to another server. However, when I try to login to the migrated site, it keeps redirecting me to the old one, despite whether I use wp-admin.php or wp-login.php.</p>
<p>I have also read about a dozen different pages on migrating worpress accounts, but not one of them encounters the problems I am having with some of the steps.</p>
<p>These are the steps I have followed, including differences I am encountering with those specified on migration instructions (problems highlighted in bold):</p>
<p>1) Downloaded all wordpress files from oldsite to my hard drive using ftp.</p>
<p>2) Downloaded the database from my oldsite using PHP myadmin.</p>
<p>3) Uploaded all the wordpress files to a chosen directory on my newsite using ftp.</p>
<p>4) Created a new database on the newsite using PHP Myadmin. <strong>As I am loading onto a different server, I created a new database using the same database name and password from the oldsite. That way I didn't have to change the WPconfig file. Is that okay to do? Not a single migration article I read used the same database and password, nor did they say not to, so I assumed it would be okay.</strong></p>
<p>5) Used phpMyadmin to change the database entry in wp_options to the new URL. <strong>However, every instruction I read says there are two fields to change: siteurl and home. There is no home field in my wp-options. Just siteurl.</strong></p>
<p>6) I used the following string entered into SQL in phpMyadmin to change all the oldsite urls to the newsite url successfully:</p>
<p>update wp_posts set post_content = replace(
post_content, '<a href="http://oldsite/" rel="nofollow noreferrer">http://oldsite/</a>',
'<a href="http://newsite/" rel="nofollow noreferrer">http://newsite/</a>');</p>
<p>Did the same for all these database tables:</p>
<p>wp_posts
wp_redirection_logs
wp_users
wp_redirection_items</p>
<p>I checked each table and all of the changes were fine.</p>
<p>7) Checked every database table to make sure there were no instances of the oldsite URL. Could not find one.</p>
<p>8)Entered newsite URL into browser. <strong>I get a 404 message. The menu, latest postings and banner all appear okay, but if I hover over any of them they are all pointing to the oldsite URLs.</strong></p>
<p><strong>9)When I try to get into the admin panel of the newsite, it allows me to enter the name and password, then automatically redirects me to the oldsite and asks me to login again. Tried on different browsers but the results are always the same.</strong></p>
<p>Any ideas what I'm doing wrong?</p>
| [
{
"answer_id": 259836,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": false,
"text": "<p>First make sure that your wp-config file you've got is connected to the right database.</p>\n\n<p>You need to go into your new database and change the site url and home url (this is definitely your missing issue here) to the new address. I suggest not doing this through phpmyadmin though as it will cause some problems.</p>\n\n<p>Go get this tool: <a href=\"https://interconnectit.com/products/search-and-replace-for-wordpress-databases/\" rel=\"nofollow noreferrer\">https://interconnectit.com/products/search-and-replace-for-wordpress-databases/</a></p>\n\n<p>Upload it into your www/ folder. (I usually rename the search and replace folder to SRDB.)</p>\n\n<p>now navigate to your site with the SRDB at the end. (www.example.com/SRDB)and the top two lines you'll see a search field and a replace field. (if you get a db connection error here, double check the wp-config to ensure that it has the right credentials). In the search place your old site address</p>\n\n<p>in the replace field place your new url </p>\n\n<p>hit live live run.</p>\n\n<p>ONLY do this after ensuring you're on your new url and that it's loaded into your new database.</p>\n\n<p>This should fix your problems!</p>\n\n<p>In the future there will have to be no phpmyadmin searches either when you use this tool. </p>\n"
},
{
"answer_id": 259837,
"author": "ferdouswp",
"author_id": 114362,
"author_profile": "https://wordpress.stackexchange.com/users/114362",
"pm_score": 1,
"selected": true,
"text": "<p>Try to add the following two lines in <code>wp-config.php</code> file:</p>\n\n<pre><code>define('WP_HOME','http://example.com');\ndefine('WP_SITEURL','http://example.com');\n</code></pre>\n"
}
]
| 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259834",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115295/"
]
| I've followed all the steps for migrating my existing wordpress site to another server. However, when I try to login to the migrated site, it keeps redirecting me to the old one, despite whether I use wp-admin.php or wp-login.php.
I have also read about a dozen different pages on migrating worpress accounts, but not one of them encounters the problems I am having with some of the steps.
These are the steps I have followed, including differences I am encountering with those specified on migration instructions (problems highlighted in bold):
1) Downloaded all wordpress files from oldsite to my hard drive using ftp.
2) Downloaded the database from my oldsite using PHP myadmin.
3) Uploaded all the wordpress files to a chosen directory on my newsite using ftp.
4) Created a new database on the newsite using PHP Myadmin. **As I am loading onto a different server, I created a new database using the same database name and password from the oldsite. That way I didn't have to change the WPconfig file. Is that okay to do? Not a single migration article I read used the same database and password, nor did they say not to, so I assumed it would be okay.**
5) Used phpMyadmin to change the database entry in wp\_options to the new URL. **However, every instruction I read says there are two fields to change: siteurl and home. There is no home field in my wp-options. Just siteurl.**
6) I used the following string entered into SQL in phpMyadmin to change all the oldsite urls to the newsite url successfully:
update wp\_posts set post\_content = replace(
post\_content, '<http://oldsite/>',
'<http://newsite/>');
Did the same for all these database tables:
wp\_posts
wp\_redirection\_logs
wp\_users
wp\_redirection\_items
I checked each table and all of the changes were fine.
7) Checked every database table to make sure there were no instances of the oldsite URL. Could not find one.
8)Entered newsite URL into browser. **I get a 404 message. The menu, latest postings and banner all appear okay, but if I hover over any of them they are all pointing to the oldsite URLs.**
**9)When I try to get into the admin panel of the newsite, it allows me to enter the name and password, then automatically redirects me to the oldsite and asks me to login again. Tried on different browsers but the results are always the same.**
Any ideas what I'm doing wrong? | Try to add the following two lines in `wp-config.php` file:
```
define('WP_HOME','http://example.com');
define('WP_SITEURL','http://example.com');
``` |
259,839 | <p>I decided to integrate several standalone WordPress websites into a single Multisite installation.</p>
<p>I created a brand new Multisite install with subdomains, created a MU network site with subdomain URL, and exported the content from the original standalone site, then imported that content into the subdomain MU site. I then deleted the original standalone site from cPanel, and set the MU site's domain name to the original domain name.</p>
<p>The main site loads fine now on its original domain name, but when I try to login to the subdomain site at <code>site.example.com/wp-admin/</code> (using the brand new multisite's network admin user credentials), I receive an error:</p>
<blockquote>
<p>ERROR: Cookies are blocked or not supported by your browser. You must
enable cookies to use WordPress.</p>
</blockquote>
<p>But cookies <em>are</em> enabled in Chrome.</p>
<p>I tried adding the following to <code>wp-config.php</code>:</p>
<pre><code>define('COOKIE_DOMAIN', false);
</code></pre>
<p>...but the issue remains.</p>
<p>The same issue occurs if I use WP Migrate DB Pro to pull in a standalone website into a MU subdomain site, then delete the standalone site from cPanel, and then set the MU subdomain site's domain to be the original standalone site's domain name... the site's frontend loads fine, but I just can't login to WP admin.</p>
| [
{
"answer_id": 260295,
"author": "Dean Jansen",
"author_id": 114897,
"author_profile": "https://wordpress.stackexchange.com/users/114897",
"pm_score": -1,
"selected": false,
"text": "<p>Please try adding the following to your wp-config.php file</p>\n\n<p>Also remove all cookies from your browser before testing</p>\n\n<pre><code>define( 'COOKIE_DOMAIN', $_SERVER[ 'HTTP_HOST' ] );\n</code></pre>\n"
},
{
"answer_id": 261087,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 6,
"selected": true,
"text": "<p>First clear your browser's cache (including cookies), and your server's cache (e.g. cache plugins). Then set the following in your <code>wp-config.php</code> file:</p>\n<pre><code>define('ADMIN_COOKIE_PATH', '/');\ndefine('COOKIE_DOMAIN', '');\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', '');\n</code></pre>\n<p>Also, you may checkout the <a href=\"https://community.bitnami.com/t/wp-multisite-multidomains-cookies-issue/46603\" rel=\"nofollow noreferrer\">answer from HERE</a>:</p>\n<pre><code>define('WP_ALLOW_MULTISITE', true);\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', false);\ndefine('DOMAIN_CURRENT_SITE', 'example.com');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\ndefine('SUNRISE', 'on');\n</code></pre>\n<p>If it still fails, then <a href=\"https://stackoverflow.com/a/21593484/7466542\">read this answer</a> or contact your server's support. There may be a configuration issue on the server.</p>\n"
},
{
"answer_id": 287924,
"author": "Ruben Apolinar",
"author_id": 132844,
"author_profile": "https://wordpress.stackexchange.com/users/132844",
"pm_score": 2,
"selected": false,
"text": "<p>I just finished troubleshooting a similar issue with subdomain multisite. </p>\n\n<p>With:</p>\n\n<pre><code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);\n</code></pre>\n\n<p>The site was still throwing a cookie error and in some instances of trying what was suggested above......... </p>\n\n<pre><code>define('ADMIN_COOKIE_PATH', '/');\ndefine('COOKIE_DOMAIN', '');\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', ''); \n</code></pre>\n\n<p>This caused a different error to delete defines referencing \"COOKIE_DOMAIN\" upon visiting subsites. </p>\n\n<p>Finally I was able to login after making sure both of these were defined just above the multisite network information</p>\n\n<pre><code>define('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);\ndefine('COOKIE_DOMAIN', '');\n</code></pre>\n\n<p>Try making sure these are both defined. I hope this helps.</p>\n"
},
{
"answer_id": 291871,
"author": "Joone Hur",
"author_id": 135358,
"author_profile": "https://wordpress.stackexchange.com/users/135358",
"pm_score": 1,
"selected": false,
"text": "<p>I commented out define('SUNRISE', 'on'); </p>\n\n<pre>\n/* define('SUNRISE', 'on'); */\ndefine('COOKIE_DOMAIN', $_SERVER['HTTP_HOST']);\ndefine('COOKIE_DOMAIN', '');\n</pre>\n\n<p>Then, I don't see the below error message:</p>\n\n<pre>\nERROR: Cookies are blocked or not supported by your browser. You must enable cookies to use WordPress.\n</pre>\n\n<p>Login also started working.</p>\n"
},
{
"answer_id": 299114,
"author": "user140609",
"author_id": 140609,
"author_profile": "https://wordpress.stackexchange.com/users/140609",
"pm_score": 3,
"selected": false,
"text": "<p>Using WordPress version 4.9.4.</p>\n<p>I was getting the cookie error and looked through various help options and eventually solved it by using a parts of Scott's fix. (Note: I didn't do any cookie cache clearing.)</p>\n<ol>\n<li><p>Editing out <code>sunrise.php</code> line in <code>wp-config.php</code> (I was using native domain mapping so removed the MU plugin install changes that I'd made )</p>\n</li>\n<li><p>Adjusted my <code>wp-config.php</code> to</p>\n<pre class=\"lang-php prettyprint-override\"><code>/* Multisite */\n\ndefine('WP_DEBUG', false);\n\ndefine( 'WP_ALLOW_MULTISITE', true );\n\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', true);\ndefine('DOMAIN_CURRENT_SITE', 'www.mysite.example');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n/* define( ‘COOKIE_DOMAIN’, $_SERVER[ ‘HTTP_HOST’ ] ); */\n\ndefine('ADMIN_COOKIE_PATH', '/');\ndefine('COOKIE_DOMAIN', '');\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', '');\n\n/* That's all, stop editing! Happy blogging. */\n</code></pre>\n</li>\n</ol>\n"
},
{
"answer_id": 299483,
"author": "Andy",
"author_id": 132064,
"author_profile": "https://wordpress.stackexchange.com/users/132064",
"pm_score": 0,
"selected": false,
"text": "<pre><code>define('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', true);\n//define('DOMAIN_CURRENT_SITE', 'masterdigitalservices.com');\n//define('PATH_CURRENT_SITE', '/');\n//define('SITE_ID_CURRENT_SITE', 1);\n//define('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n\n<p>Here's my new wp-config. Looks like it got hardcoded to be a specific site, and wasn't letting other domains work -- only subdomains. Great answers here.</p>\n"
},
{
"answer_id": 302351,
"author": "snake",
"author_id": 82138,
"author_profile": "https://wordpress.stackexchange.com/users/82138",
"pm_score": 0,
"selected": false,
"text": "<p>I was having this issue as well, and nothing I did helped.\nTried it in Microsoft Edge, and didn't get the error.</p>\n\n<p>So in my case at least, it was just Google Chrome causing the problem.</p>\n"
},
{
"answer_id": 303051,
"author": "ronaut",
"author_id": 143256,
"author_profile": "https://wordpress.stackexchange.com/users/143256",
"pm_score": 1,
"selected": false,
"text": "<p>So I was having this issue as well and came across a lot of solutions like the ones mentioned here but they didn't work.</p>\n<p>What did work was simply adding the following to the multisite configuration in wp-config:</p>\n<pre><code>define('COOKIE_DOMAIN', false);\n</code></pre>\n<p>so that the section in wp-config looks like so:</p>\n<pre><code>define( 'WP_ALLOW_MULTISITE', true );\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', true);\ndefine('DOMAIN_CURRENT_SITE', 'example.com');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\ndefine('COOKIE_DOMAIN', false);\n</code></pre>\n<p>posting here so that others may find it and spend less time banging their head against their desk than I did.</p>\n"
},
{
"answer_id": 311924,
"author": "Martin from WP-Stars.com",
"author_id": 85008,
"author_profile": "https://wordpress.stackexchange.com/users/85008",
"pm_score": 0,
"selected": false,
"text": "<p>Strangely it worked for me (on more than one multisites) to set SUBDOMAIN_INSTALL to false. To be honest, I hadn't had time to investigate further why ...</p>\n\n<p><code>define('SUBDOMAIN_INSTALL', false);</code></p>\n"
},
{
"answer_id": 316926,
"author": "sam tapsell",
"author_id": 152513,
"author_profile": "https://wordpress.stackexchange.com/users/152513",
"pm_score": 0,
"selected": false,
"text": "<p><strong>THIS FIXED IT FOR ME</strong>\nI had not setup WordPress fully for the new domain name.\nI had created my site <em>subdomain.domain.com</em>\nI then wanted to remain as <em>newdomain.com</em> over <em>subdomain.domain.com</em>\nThis required </p>\n\n<ol>\n<li>WordPress <em>network > admin > site</em>, change site to new name (which I had already done, site was working)</li>\n<li>WordPress <em>network > admin > settings > domains</em>, add in new name to site ID and tick yes for primary domain (to indicate this name is the primary name).\nTo find site ID, you can hover over the <em>network > admin > site</em> which will say which site ID you are working on.\nHope this helps anyone who was getting the cookies are blocked or not supported message when trying to login\nBest wishes\nSamTapsell</li>\n</ol>\n"
},
{
"answer_id": 324050,
"author": "Baga",
"author_id": 157854,
"author_profile": "https://wordpress.stackexchange.com/users/157854",
"pm_score": 0,
"selected": false,
"text": "<p>I was able to resolve the issue after adding the below in wp-config.php. <a href=\"https://codex.wordpress.org/Editing_wp-config.php#Set_Cookie_Domain\" rel=\"nofollow noreferrer\">Reference</a></p>\n\n<pre><code>define( 'COOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'home' ) . '/' ) );\ndefine( 'SITECOOKIEPATH', preg_replace( '|https?://[^/]+|i', '', get_option( 'siteurl' ) . '/' ) );\ndefine( 'ADMIN_COOKIE_PATH', SITECOOKIEPATH . 'wp-admin' );\ndefine( 'PLUGINS_COOKIE_PATH', preg_replace( '|https?://[^/]+|i', '', WP_PLUGIN_URL ) );\n</code></pre>\n"
},
{
"answer_id": 331995,
"author": "George Drew",
"author_id": 163380,
"author_profile": "https://wordpress.stackexchange.com/users/163380",
"pm_score": 2,
"selected": false,
"text": "<p>Finally after hours, literally, of troubleshooting I was able to get this resolved on the AWS Lightsail Bitnami Multisite Wordpress (WordPress 5.0.4) instance by performing the following:</p>\n\n<ol>\n<li>Ensure the WPMU Domain Mapping plugin is disabled</li>\n<li><p>Edit /opt/bitnami/apps/wordpress/htdocs/wp-config.php...</p>\n\n<p>a. Add the following: </p>\n\n<pre><code> define('ADMIN_COOKIE_PATH', '/');\n define('COOKIE_DOMAIN', '');\n define('COOKIEPATH', '');\n define('SITECOOKIEPATH', '');\n\n /* That's all, stop editing! Happy blogging. */\n</code></pre>\n\n<p>b. Comment out:</p>\n\n<pre><code>// define('SUNRISE', 'on');\n</code></pre></li>\n</ol>\n\n<p>After these changes, login was successful - no errors. Thanks for everyone's input. If it was not for that, I would still be scratching my head.</p>\n\n<p>I did find the answer here: </p>\n\n<p><a href=\"https://docs.bitnami.com/aws/apps/wordpress-multisite/configuration/configure-wordpress-multisite\" rel=\"nofollow noreferrer\">https://docs.bitnami.com/aws/apps/wordpress-multisite/configuration/configure-wordpress-multisite</a></p>\n\n<blockquote>\n <p>This <strong>domain mapping functionality is included in WordPress Multisite since v4.5</strong>. If you’re using an older version, you will need the WordPress MU Domain Mapping plugin.</p>\n</blockquote>\n\n<p>So it appears that the WPMU Domain Mapping plugin is unnecessarily included in the AWS Lightsail Bitnami Multisite package.</p>\n"
},
{
"answer_id": 363553,
"author": "David Najman",
"author_id": 142958,
"author_profile": "https://wordpress.stackexchange.com/users/142958",
"pm_score": 0,
"selected": false,
"text": "<p>I solved the problem with this:</p>\n\n<p>Change the setting of DOMAIN_CURRENT_SITE in wp-config.php to:</p>\n\n<pre><code> define('DOMAIN_CURRENT_SITE', $_SERVER['HTTP_HOST']);\n</code></pre>\n\n<p>So my setup is this:</p>\n\n<pre><code>define( 'WP_ALLOW_MULTISITE', true );\ndefine('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', true);\ndefine('DOMAIN_CURRENT_SITE', $_SERVER['HTTP_HOST']);\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n\n<p>Then I could login to all multisite website on url e.g. web1.example.com/wp-admin or web2.example.com/wp-admin.</p>\n"
},
{
"answer_id": 408682,
"author": "jgangso",
"author_id": 104184,
"author_profile": "https://wordpress.stackexchange.com/users/104184",
"pm_score": 0,
"selected": false,
"text": "<p>Don't know about you folks, but for me it helped <em>surprisingly much</em> to change this</p>\n<pre><code>define( 'COOKIEDOMAIN', '' );\n</code></pre>\n<p>to this</p>\n<pre><code>define( 'COOKIE_DOMAIN', '' );\n</code></pre>\n<p>And yes, I still dare to consider myself an experienced PHP & WP developer. Just wanted to share that it happens to all of us. :)</p>\n"
},
{
"answer_id": 410698,
"author": "Jesse Nickles",
"author_id": 152624,
"author_profile": "https://wordpress.stackexchange.com/users/152624",
"pm_score": 0,
"selected": false,
"text": "<p>This is what we are using on SlickStack for Multisite installations... it works for both subdomain networks and/or custom domain names as well:</p>\n<pre><code>define('MULTISITE', true);\ndefine('SUBDOMAIN_INSTALL', true);\ndefine('DOMAIN_CURRENT_SITE', $_SERVER['HTTP_HOST']);\ndefine('NOBLOGREDIRECT', 'https://example.com');\ndefine('PATH_CURRENT_SITE', '/');\ndefine('SITE_ID_CURRENT_SITE', 1);\ndefine('BLOG_ID_CURRENT_SITE', 1);\n</code></pre>\n<p>And then:</p>\n<pre><code>define('COOKIE_DOMAIN', false);\ndefine('COOKIEPATH', '');\ndefine('SITECOOKIEPATH', '');\ndefine('ADMIN_COOKIE_PATH', '/');\n</code></pre>\n"
}
]
| 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259839",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3206/"
]
| I decided to integrate several standalone WordPress websites into a single Multisite installation.
I created a brand new Multisite install with subdomains, created a MU network site with subdomain URL, and exported the content from the original standalone site, then imported that content into the subdomain MU site. I then deleted the original standalone site from cPanel, and set the MU site's domain name to the original domain name.
The main site loads fine now on its original domain name, but when I try to login to the subdomain site at `site.example.com/wp-admin/` (using the brand new multisite's network admin user credentials), I receive an error:
>
> ERROR: Cookies are blocked or not supported by your browser. You must
> enable cookies to use WordPress.
>
>
>
But cookies *are* enabled in Chrome.
I tried adding the following to `wp-config.php`:
```
define('COOKIE_DOMAIN', false);
```
...but the issue remains.
The same issue occurs if I use WP Migrate DB Pro to pull in a standalone website into a MU subdomain site, then delete the standalone site from cPanel, and then set the MU subdomain site's domain to be the original standalone site's domain name... the site's frontend loads fine, but I just can't login to WP admin. | First clear your browser's cache (including cookies), and your server's cache (e.g. cache plugins). Then set the following in your `wp-config.php` file:
```
define('ADMIN_COOKIE_PATH', '/');
define('COOKIE_DOMAIN', '');
define('COOKIEPATH', '');
define('SITECOOKIEPATH', '');
```
Also, you may checkout the [answer from HERE](https://community.bitnami.com/t/wp-multisite-multidomains-cookies-issue/46603):
```
define('WP_ALLOW_MULTISITE', true);
define('MULTISITE', true);
define('SUBDOMAIN_INSTALL', false);
define('DOMAIN_CURRENT_SITE', 'example.com');
define('PATH_CURRENT_SITE', '/');
define('SITE_ID_CURRENT_SITE', 1);
define('BLOG_ID_CURRENT_SITE', 1);
define('SUNRISE', 'on');
```
If it still fails, then [read this answer](https://stackoverflow.com/a/21593484/7466542) or contact your server's support. There may be a configuration issue on the server. |
259,849 | <p>I try to order a WP_Query of a custom post type 'entry' by a meta value 'votes', but it keeps showing up ordered by date.
My code:</p>
<pre><code>$args = array(
'post_type' => 'entry',
'orderby' => 'votes',
'order' => 'DESC',
'posts_per_page' => 10,
'post_status' => 'publish'
);
$loop = new WP_Query($args);
</code></pre>
<p>When I evaluate <code>$loop->request</code> in xDebug, I get this, which indicates the results are indeed ordered by <code>post_date DESC</code>:</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'entry' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
</code></pre>
<p>Do I need to use <code>meta_query</code> to order on custom post type meta fields? I thought that was only needed when you want to compare/restrict results based on custom meta?</p>
| [
{
"answer_id": 259851,
"author": "dhuyvetter",
"author_id": 86095,
"author_profile": "https://wordpress.stackexchange.com/users/86095",
"pm_score": 2,
"selected": false,
"text": "<p>OK, I figured it pour reading about <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\" rel=\"nofollow noreferrer\">Orderby Parameters in WP_Query</a> more carefully. I needed to set <code>votes</code> to <code>meta_key</code> and <code>orderby</code> to <code>meta_value_num</code>:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'entry',\n 'meta_key' => 'votes',\n 'orderby' => 'meta_value_num',\n 'order' => 'DESC',\n 'posts_per_page' => 10,\n 'post_status' => 'publish'\n );\n$loop = new WP_Query($args);\n</code></pre>\n"
},
{
"answer_id": 259854,
"author": "ferdouswp",
"author_id": 114362,
"author_profile": "https://wordpress.stackexchange.com/users/114362",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\n$args = array(\n 'post_type' => 'entry',\n 'meta_key' => 'start_date', //Meta field value name \n 'meta_type' => 'DATETIME',\n 'order' => 'DESC',\n 'orderby' => 'meta_value_num',\n 'posts_per_page' => 10,\n );\n $query = new WP_Query( $args );\n\n if( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();\n //Your Front End filed Value\n //Such as\n ?>\n <h4> <a href=\"<?php the_permalink(); ?>\"><?php the_title(); ?></a> </h4>\n <?php if( get_field('start_date')) { ?><strong> Start Date: </strong><?php echo the_field('start_date'); ?><?php } ?> <br>\n <?php the_excerpt(); ?> <a href=\"<?php the_permalink(); ?>\">Read More &raquo;</a>\n\n <?php endwhile; endif; wp_reset_postdata(); ?>\n</code></pre>\n"
}
]
| 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259849",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86095/"
]
| I try to order a WP\_Query of a custom post type 'entry' by a meta value 'votes', but it keeps showing up ordered by date.
My code:
```
$args = array(
'post_type' => 'entry',
'orderby' => 'votes',
'order' => 'DESC',
'posts_per_page' => 10,
'post_status' => 'publish'
);
$loop = new WP_Query($args);
```
When I evaluate `$loop->request` in xDebug, I get this, which indicates the results are indeed ordered by `post_date DESC`:
```
SELECT SQL_CALC_FOUND_ROWS wp_posts.ID FROM wp_posts WHERE 1=1 AND wp_posts.post_type = 'entry' AND ((wp_posts.post_status = 'publish')) ORDER BY wp_posts.post_date DESC LIMIT 0, 10
```
Do I need to use `meta_query` to order on custom post type meta fields? I thought that was only needed when you want to compare/restrict results based on custom meta? | OK, I figured it pour reading about [Orderby Parameters in WP\_Query](https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters) more carefully. I needed to set `votes` to `meta_key` and `orderby` to `meta_value_num`:
```
$args = array(
'post_type' => 'entry',
'meta_key' => 'votes',
'orderby' => 'meta_value_num',
'order' => 'DESC',
'posts_per_page' => 10,
'post_status' => 'publish'
);
$loop = new WP_Query($args);
``` |
259,883 | <p>I would like to overwrite some content which is located in (<code>inc/</code>) <code>template-tags.php</code> file on parent theme.</p>
<p>Content need to be changed is in function <code>footer_content_widget_area</code> in <code>template-tags.php</code> file and that function is called on <code>functions.php</code>:</p>
<pre><code>add_action( 'page_widgets', 'footer_content_widget_area' );
</code></pre>
| [
{
"answer_id": 260054,
"author": "Justin",
"author_id": 114945,
"author_profile": "https://wordpress.stackexchange.com/users/114945",
"pm_score": -1,
"selected": false,
"text": "<p>As long as you have a child-theme setup correctly then you just allow the child-theme to replace the parent-theme template by placing the template file in the same location. </p>\n\n<p>So based on the location that you mention in your question you would simply place your edited copy of the template-tags.php in the location <strong>child-theme/inc/</strong></p>\n\n<p>the wordpress way of things is explained in the Template_Hierarchy (<a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a>).</p>\n"
},
{
"answer_id": 350709,
"author": "Dan F",
"author_id": 176945,
"author_profile": "https://wordpress.stackexchange.com/users/176945",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>functions.php</code> child theme include <code>template-tags.php</code> from parent theme: </p>\n\n<pre><code>require_once get_theme_file_path( '../parent-theme/inc/template-tags.php' );\n</code></pre>\n\n<p>In the child theme <code>template-tags.php</code> remove parent action and add the child action replacing it:</p>\n\n<pre><code>remove_action( 'tag', 'parent-function', 0 );\nadd_action( 'tag', 'new-child-function', 10 );\n</code></pre>\n"
}
]
| 2017/03/13 | [
"https://wordpress.stackexchange.com/questions/259883",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92020/"
]
| I would like to overwrite some content which is located in (`inc/`) `template-tags.php` file on parent theme.
Content need to be changed is in function `footer_content_widget_area` in `template-tags.php` file and that function is called on `functions.php`:
```
add_action( 'page_widgets', 'footer_content_widget_area' );
``` | In `functions.php` child theme include `template-tags.php` from parent theme:
```
require_once get_theme_file_path( '../parent-theme/inc/template-tags.php' );
```
In the child theme `template-tags.php` remove parent action and add the child action replacing it:
```
remove_action( 'tag', 'parent-function', 0 );
add_action( 'tag', 'new-child-function', 10 );
``` |
259,936 | <p>Having practised mirroring an existing wordpress site, I'm ready to migrate my website to a new server. Having simplified the steps necessary to do this, I'm hoping the following will work without having to change any database entries or Wordpress files. The domain name will stay the same, only the host will change.</p>
<p>1) Backup wordpress files from oldsite<br>
2) Back up database from oldsite<br>
3) Create a database on the new site using the same database name and password from the oldsite. (That way there is no need to change the original config file).<br>
4) Upload oldsite database into newsite database.<br>
5) Upload all wordpress files onto new server<br>
6) Have the DNS record of my domain changed to point to the new server and directory.<br>
7) Wait up to 48 hours (Although the TTL value is set to 10 minutes)<br>
8) Newsite should be working identically to the oldsite<br>
9) Delete all files from oldsite </p>
<p>Should this work okay? </p>
<p>My website is live and my main source of income. It also has good Google rankings which I have spent years achieving. My biggest fear is that by moving from one server to another Google will see it as a duplicate or brand new site and penalize me in the search results. I've also been told that all the Facebook likes on articles will break and will reset to zero. Is that correct?</p>
| [
{
"answer_id": 260054,
"author": "Justin",
"author_id": 114945,
"author_profile": "https://wordpress.stackexchange.com/users/114945",
"pm_score": -1,
"selected": false,
"text": "<p>As long as you have a child-theme setup correctly then you just allow the child-theme to replace the parent-theme template by placing the template file in the same location. </p>\n\n<p>So based on the location that you mention in your question you would simply place your edited copy of the template-tags.php in the location <strong>child-theme/inc/</strong></p>\n\n<p>the wordpress way of things is explained in the Template_Hierarchy (<a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/themes/basics/template-hierarchy/</a>).</p>\n"
},
{
"answer_id": 350709,
"author": "Dan F",
"author_id": 176945,
"author_profile": "https://wordpress.stackexchange.com/users/176945",
"pm_score": 0,
"selected": false,
"text": "<p>In <code>functions.php</code> child theme include <code>template-tags.php</code> from parent theme: </p>\n\n<pre><code>require_once get_theme_file_path( '../parent-theme/inc/template-tags.php' );\n</code></pre>\n\n<p>In the child theme <code>template-tags.php</code> remove parent action and add the child action replacing it:</p>\n\n<pre><code>remove_action( 'tag', 'parent-function', 0 );\nadd_action( 'tag', 'new-child-function', 10 );\n</code></pre>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259936",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115295/"
]
| Having practised mirroring an existing wordpress site, I'm ready to migrate my website to a new server. Having simplified the steps necessary to do this, I'm hoping the following will work without having to change any database entries or Wordpress files. The domain name will stay the same, only the host will change.
1) Backup wordpress files from oldsite
2) Back up database from oldsite
3) Create a database on the new site using the same database name and password from the oldsite. (That way there is no need to change the original config file).
4) Upload oldsite database into newsite database.
5) Upload all wordpress files onto new server
6) Have the DNS record of my domain changed to point to the new server and directory.
7) Wait up to 48 hours (Although the TTL value is set to 10 minutes)
8) Newsite should be working identically to the oldsite
9) Delete all files from oldsite
Should this work okay?
My website is live and my main source of income. It also has good Google rankings which I have spent years achieving. My biggest fear is that by moving from one server to another Google will see it as a duplicate or brand new site and penalize me in the search results. I've also been told that all the Facebook likes on articles will break and will reset to zero. Is that correct? | In `functions.php` child theme include `template-tags.php` from parent theme:
```
require_once get_theme_file_path( '../parent-theme/inc/template-tags.php' );
```
In the child theme `template-tags.php` remove parent action and add the child action replacing it:
```
remove_action( 'tag', 'parent-function', 0 );
add_action( 'tag', 'new-child-function', 10 );
``` |
259,942 | <p>Where is the value for <code>admin_email</code> set?</p>
<pre><code>$email = get_option('admin_email');
</code></pre>
<p>How can I change it?</p>
| [
{
"answer_id": 259944,
"author": "ngearing",
"author_id": 50184,
"author_profile": "https://wordpress.stackexchange.com/users/50184",
"pm_score": 3,
"selected": false,
"text": "<p>In Wordpress backend go to: <strong>Settings > General</strong> and the field <strong>'Email Address'</strong>.</p>\n\n<p>Or in php: update_option('admin_email', '[email protected]');\n<a href=\"https://codex.wordpress.org/Function_Reference/update_option\" rel=\"noreferrer\">https://codex.wordpress.org/Function_Reference/update_option</a></p>\n"
},
{
"answer_id": 356902,
"author": "John Dee",
"author_id": 131224,
"author_profile": "https://wordpress.stackexchange.com/users/131224",
"pm_score": 1,
"selected": false,
"text": "<p>As of 4.9 there is a requirement the user send an outbound email in order to change the admin email from the backend. If you can't send outbound email, you can't change the email without custom code. This plugin restores functionality to pre-4.9:</p>\n\n<p><a href=\"https://wordpress.org/plugins/change-admin-email-setting-without-outbound-email/\" rel=\"nofollow noreferrer\">Change Admin Email</a></p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115340/"
]
| Where is the value for `admin_email` set?
```
$email = get_option('admin_email');
```
How can I change it? | In Wordpress backend go to: **Settings > General** and the field **'Email Address'**.
Or in php: update\_option('admin\_email', 'your\[email protected]');
<https://codex.wordpress.org/Function_Reference/update_option> |
259,949 | <p>I wanted to exclude <code>pages</code> from the search results, and found many ways to do it, and was wondering why use <code>!is_admin()</code> or <code>is_main_query()</code> and which way would be better.</p>
<pre><code>add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
</code></pre>
<hr>
<pre><code>add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
</code></pre>
<hr>
<pre><code>add_action('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
</code></pre>
| [
{
"answer_id": 259955,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> will run in admin as well as the frontend, you can use it to filter posts that appear to the admin users as well as frontend results. Adding <code>! is_admin()</code> will ensure that that code only affects the frontend.</p>\n\n<p><code>is_main_query()</code> will ensure that you are only affecting the query for the posts, not for example the menu items in the nav bar, or a list of posts in the sidebar. It is recommended to use that.</p>\n\n<p>Let me know if this isn't clear,</p>\n"
},
{
"answer_id": 259988,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note that when we use:</p>\n\n<pre><code>$query->set( 'post_type', 'post' );\n</code></pre>\n\n<p>then we're overriding all searchable post types, not only the <code>page</code> post type. </p>\n\n<p>That may be just fine in some cases, and we're done using some of your <code>pre_get_posts</code> snippets that fit our needs.</p>\n\n<p>But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.</p>\n\n<p><strong>Using the register_post_type_args filter.</strong></p>\n\n<p>When the post type isn't specified, the <code>WP_Query</code> search uses any post types that are searchable, <a href=\"https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264\" rel=\"nofollow noreferrer\">namely</a>:</p>\n\n<pre><code>$in_search_post_types = get_post_types( array('exclude_from_search' => false) );\n</code></pre>\n\n<p>When we register a post type, we can set the <code>exclude_from_search</code> parameter as false to exclude it from search.</p>\n\n<p>We can modify it for the <code>page</code> post type setup with:</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $name )\n{\n // Target 'page' post type\n if( 'page' === $name )\n $args['exclude_from_search'] = true;\n\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>More about <code>register_post_type()</code> <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Examples</strong></p>\n\n<p>Here are examples where the page post type would be excluded from the search, using the above filtering:</p>\n\n<ul>\n<li><p>Main query search on the front-end with </p>\n\n<pre><code>https://example.tld?s=testing\n</code></pre></li>\n<li><p>Secondary query like:</p>\n\n<pre><code>$query = new WP_Query( [ 's' => 'testing' ] );\n</code></pre></li>\n<li><p>Secondary query like:</p>\n\n<pre><code>$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );\n</code></pre></li>\n</ul>\n\n<p><strong>Some notes on queries with pre set post types:</strong></p>\n\n<p>Let's consider cases where the post types are fixed, like:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );\n</code></pre>\n\n<p>If the post type is set by some array <code>$post_type</code>, then we can filter the <code>'page'</code> out it with</p>\n\n<pre><code>if( is_array( $post_type ) && count( $post_type ) > 1 )\n{\n $post_type = array_filter( \n $post_type, \n function( $item ) { return 'page' !== $item; } \n );\n}\n</code></pre>\n\n<p>If we don't have direct access to that array, we could use e.g. <code>pre_get_posts</code> to remove the 'page' from the post type array, with help of the <code>get</code>/<code>set</code> methods of <code>WP_Query</code>. Here's an example for the main search query on the front end:</p>\n\n<pre><code>add_action( 'pre_get_posts', function search_filter( \\WP_Query $query )\n{\n if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )\n return;\n\n $post_type = $query->get( 'post_type' );\n\n if( is_array( $post_type ) && count( $post_type ) > 1 )\n {\n $post_type = array_filter( \n $post_type, \n function( $item ) { return 'page' !== $item; } \n );\n $query->set('post_type', $post_type );\n }\n\n} );\n</code></pre>\n\n<p>Why did we check the array count > 1 here?</p>\n\n<p>That's because we should be careful to removing <code>'page'</code> from examples like:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );\n\n $query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );\n</code></pre>\n\n<p>as an empty array or an empty string, for the post type:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );\n\n $query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );\n</code></pre>\n\n<p>will fall back to the <code>'post'</code> post type.</p>\n\n<p>Note that:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );\n</code></pre>\n\n<p>isn't supported, as the resulting post type would be <code>'pagepost'</code>.</p>\n\n<p>In these cases, where we don't have direct access to the <code>WP_Query</code> objects, we could halt the query with tricks like <code>'post__in' => []</code> or <code>1=0</code> in the search WHERE query part or even play with the <code>posts_pre_query</code> filter or using some more advanced methods. There are plenty of answers on this site about that. <a href=\"https://wordpress.stackexchange.com/q/229722/26350\">This</a> and <a href=\"https://wordpress.stackexchange.com/q/226065/\">this</a> is what I recall at the moment.</p>\n\n<p>The <code>null</code> case:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );\n</code></pre>\n\n<p>falls back to <code>'any'</code> post types:</p>\n\n<p>Hope it helps!</p>\n\n<p><strong>PS:</strong></p>\n\n<p>Also note the inconsistency in your snippets, as you have both</p>\n\n<pre><code>add_filter('pre_get_posts','search_filter'); \n</code></pre>\n\n<p>and </p>\n\n<pre><code>add_action('pre_get_posts','search_filter'); \n</code></pre>\n\n<p>It's considered an <em>action</em>, but it will not make any difference, as actions are wrapped as filters, behind the scenes. </p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259949",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115018/"
]
| I wanted to exclude `pages` from the search results, and found many ways to do it, and was wondering why use `!is_admin()` or `is_main_query()` and which way would be better.
```
add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
```
---
```
add_filter('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_search) {
$query->set('post_type', 'post');
}
return $query;
}
```
---
```
add_action('pre_get_posts','search_filter');
function search_filter($query) {
if ( !is_admin() && $query->is_main_query() ) {
if ($query->is_search) {
$query->set('post_type', 'post');
}
}
}
``` | Note that when we use:
```
$query->set( 'post_type', 'post' );
```
then we're overriding all searchable post types, not only the `page` post type.
That may be just fine in some cases, and we're done using some of your `pre_get_posts` snippets that fit our needs.
But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.
**Using the register\_post\_type\_args filter.**
When the post type isn't specified, the `WP_Query` search uses any post types that are searchable, [namely](https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264):
```
$in_search_post_types = get_post_types( array('exclude_from_search' => false) );
```
When we register a post type, we can set the `exclude_from_search` parameter as false to exclude it from search.
We can modify it for the `page` post type setup with:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
// Target 'page' post type
if( 'page' === $name )
$args['exclude_from_search'] = true;
return $args;
}, 10, 2 );
```
More about `register_post_type()` [here](https://developer.wordpress.org/reference/functions/register_post_type/).
**Examples**
Here are examples where the page post type would be excluded from the search, using the above filtering:
* Main query search on the front-end with
```
https://example.tld?s=testing
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing' ] );
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );
```
**Some notes on queries with pre set post types:**
Let's consider cases where the post types are fixed, like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );
```
If the post type is set by some array `$post_type`, then we can filter the `'page'` out it with
```
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
}
```
If we don't have direct access to that array, we could use e.g. `pre_get_posts` to remove the 'page' from the post type array, with help of the `get`/`set` methods of `WP_Query`. Here's an example for the main search query on the front end:
```
add_action( 'pre_get_posts', function search_filter( \WP_Query $query )
{
if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )
return;
$post_type = $query->get( 'post_type' );
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
$query->set('post_type', $post_type );
}
} );
```
Why did we check the array count > 1 here?
That's because we should be careful to removing `'page'` from examples like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );
```
as an empty array or an empty string, for the post type:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );
```
will fall back to the `'post'` post type.
Note that:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );
```
isn't supported, as the resulting post type would be `'pagepost'`.
In these cases, where we don't have direct access to the `WP_Query` objects, we could halt the query with tricks like `'post__in' => []` or `1=0` in the search WHERE query part or even play with the `posts_pre_query` filter or using some more advanced methods. There are plenty of answers on this site about that. [This](https://wordpress.stackexchange.com/q/229722/26350) and [this](https://wordpress.stackexchange.com/q/226065/) is what I recall at the moment.
The `null` case:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );
```
falls back to `'any'` post types:
Hope it helps!
**PS:**
Also note the inconsistency in your snippets, as you have both
```
add_filter('pre_get_posts','search_filter');
```
and
```
add_action('pre_get_posts','search_filter');
```
It's considered an *action*, but it will not make any difference, as actions are wrapped as filters, behind the scenes. |
259,958 | <p>I'm building a function within functions.php</p>
<p>Within my function I want to make use of the post id of current post.
How do I do this?</p>
<p>The last thing I tried was this:</p>
<pre><code>global $post ;
$id = $post->id ;
</code></pre>
<p>However, this returns an empty string.</p>
| [
{
"answer_id": 259955,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> will run in admin as well as the frontend, you can use it to filter posts that appear to the admin users as well as frontend results. Adding <code>! is_admin()</code> will ensure that that code only affects the frontend.</p>\n\n<p><code>is_main_query()</code> will ensure that you are only affecting the query for the posts, not for example the menu items in the nav bar, or a list of posts in the sidebar. It is recommended to use that.</p>\n\n<p>Let me know if this isn't clear,</p>\n"
},
{
"answer_id": 259988,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note that when we use:</p>\n\n<pre><code>$query->set( 'post_type', 'post' );\n</code></pre>\n\n<p>then we're overriding all searchable post types, not only the <code>page</code> post type. </p>\n\n<p>That may be just fine in some cases, and we're done using some of your <code>pre_get_posts</code> snippets that fit our needs.</p>\n\n<p>But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.</p>\n\n<p><strong>Using the register_post_type_args filter.</strong></p>\n\n<p>When the post type isn't specified, the <code>WP_Query</code> search uses any post types that are searchable, <a href=\"https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264\" rel=\"nofollow noreferrer\">namely</a>:</p>\n\n<pre><code>$in_search_post_types = get_post_types( array('exclude_from_search' => false) );\n</code></pre>\n\n<p>When we register a post type, we can set the <code>exclude_from_search</code> parameter as false to exclude it from search.</p>\n\n<p>We can modify it for the <code>page</code> post type setup with:</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $name )\n{\n // Target 'page' post type\n if( 'page' === $name )\n $args['exclude_from_search'] = true;\n\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>More about <code>register_post_type()</code> <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Examples</strong></p>\n\n<p>Here are examples where the page post type would be excluded from the search, using the above filtering:</p>\n\n<ul>\n<li><p>Main query search on the front-end with </p>\n\n<pre><code>https://example.tld?s=testing\n</code></pre></li>\n<li><p>Secondary query like:</p>\n\n<pre><code>$query = new WP_Query( [ 's' => 'testing' ] );\n</code></pre></li>\n<li><p>Secondary query like:</p>\n\n<pre><code>$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );\n</code></pre></li>\n</ul>\n\n<p><strong>Some notes on queries with pre set post types:</strong></p>\n\n<p>Let's consider cases where the post types are fixed, like:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );\n</code></pre>\n\n<p>If the post type is set by some array <code>$post_type</code>, then we can filter the <code>'page'</code> out it with</p>\n\n<pre><code>if( is_array( $post_type ) && count( $post_type ) > 1 )\n{\n $post_type = array_filter( \n $post_type, \n function( $item ) { return 'page' !== $item; } \n );\n}\n</code></pre>\n\n<p>If we don't have direct access to that array, we could use e.g. <code>pre_get_posts</code> to remove the 'page' from the post type array, with help of the <code>get</code>/<code>set</code> methods of <code>WP_Query</code>. Here's an example for the main search query on the front end:</p>\n\n<pre><code>add_action( 'pre_get_posts', function search_filter( \\WP_Query $query )\n{\n if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )\n return;\n\n $post_type = $query->get( 'post_type' );\n\n if( is_array( $post_type ) && count( $post_type ) > 1 )\n {\n $post_type = array_filter( \n $post_type, \n function( $item ) { return 'page' !== $item; } \n );\n $query->set('post_type', $post_type );\n }\n\n} );\n</code></pre>\n\n<p>Why did we check the array count > 1 here?</p>\n\n<p>That's because we should be careful to removing <code>'page'</code> from examples like:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );\n\n $query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );\n</code></pre>\n\n<p>as an empty array or an empty string, for the post type:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );\n\n $query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );\n</code></pre>\n\n<p>will fall back to the <code>'post'</code> post type.</p>\n\n<p>Note that:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );\n</code></pre>\n\n<p>isn't supported, as the resulting post type would be <code>'pagepost'</code>.</p>\n\n<p>In these cases, where we don't have direct access to the <code>WP_Query</code> objects, we could halt the query with tricks like <code>'post__in' => []</code> or <code>1=0</code> in the search WHERE query part or even play with the <code>posts_pre_query</code> filter or using some more advanced methods. There are plenty of answers on this site about that. <a href=\"https://wordpress.stackexchange.com/q/229722/26350\">This</a> and <a href=\"https://wordpress.stackexchange.com/q/226065/\">this</a> is what I recall at the moment.</p>\n\n<p>The <code>null</code> case:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );\n</code></pre>\n\n<p>falls back to <code>'any'</code> post types:</p>\n\n<p>Hope it helps!</p>\n\n<p><strong>PS:</strong></p>\n\n<p>Also note the inconsistency in your snippets, as you have both</p>\n\n<pre><code>add_filter('pre_get_posts','search_filter'); \n</code></pre>\n\n<p>and </p>\n\n<pre><code>add_action('pre_get_posts','search_filter'); \n</code></pre>\n\n<p>It's considered an <em>action</em>, but it will not make any difference, as actions are wrapped as filters, behind the scenes. </p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259958",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/26187/"
]
| I'm building a function within functions.php
Within my function I want to make use of the post id of current post.
How do I do this?
The last thing I tried was this:
```
global $post ;
$id = $post->id ;
```
However, this returns an empty string. | Note that when we use:
```
$query->set( 'post_type', 'post' );
```
then we're overriding all searchable post types, not only the `page` post type.
That may be just fine in some cases, and we're done using some of your `pre_get_posts` snippets that fit our needs.
But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.
**Using the register\_post\_type\_args filter.**
When the post type isn't specified, the `WP_Query` search uses any post types that are searchable, [namely](https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264):
```
$in_search_post_types = get_post_types( array('exclude_from_search' => false) );
```
When we register a post type, we can set the `exclude_from_search` parameter as false to exclude it from search.
We can modify it for the `page` post type setup with:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
// Target 'page' post type
if( 'page' === $name )
$args['exclude_from_search'] = true;
return $args;
}, 10, 2 );
```
More about `register_post_type()` [here](https://developer.wordpress.org/reference/functions/register_post_type/).
**Examples**
Here are examples where the page post type would be excluded from the search, using the above filtering:
* Main query search on the front-end with
```
https://example.tld?s=testing
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing' ] );
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );
```
**Some notes on queries with pre set post types:**
Let's consider cases where the post types are fixed, like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );
```
If the post type is set by some array `$post_type`, then we can filter the `'page'` out it with
```
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
}
```
If we don't have direct access to that array, we could use e.g. `pre_get_posts` to remove the 'page' from the post type array, with help of the `get`/`set` methods of `WP_Query`. Here's an example for the main search query on the front end:
```
add_action( 'pre_get_posts', function search_filter( \WP_Query $query )
{
if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )
return;
$post_type = $query->get( 'post_type' );
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
$query->set('post_type', $post_type );
}
} );
```
Why did we check the array count > 1 here?
That's because we should be careful to removing `'page'` from examples like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );
```
as an empty array or an empty string, for the post type:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );
```
will fall back to the `'post'` post type.
Note that:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );
```
isn't supported, as the resulting post type would be `'pagepost'`.
In these cases, where we don't have direct access to the `WP_Query` objects, we could halt the query with tricks like `'post__in' => []` or `1=0` in the search WHERE query part or even play with the `posts_pre_query` filter or using some more advanced methods. There are plenty of answers on this site about that. [This](https://wordpress.stackexchange.com/q/229722/26350) and [this](https://wordpress.stackexchange.com/q/226065/) is what I recall at the moment.
The `null` case:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );
```
falls back to `'any'` post types:
Hope it helps!
**PS:**
Also note the inconsistency in your snippets, as you have both
```
add_filter('pre_get_posts','search_filter');
```
and
```
add_action('pre_get_posts','search_filter');
```
It's considered an *action*, but it will not make any difference, as actions are wrapped as filters, behind the scenes. |
259,970 | <p>i've got a question. I created a plugin with a menu and i want to show this under the Dashboard menu-item. In some of my wordpress installations the dashboard item will be overwrited. How can i fix this?</p>
<p>My code to add the menu is:</p>
<pre><code>add_menu_page('pluginname', 'pluginname', 'manage_options', 'pluginname-hello', '', 'dashicons-admin-site', 2);
</code></pre>
| [
{
"answer_id": 259955,
"author": "Ben Casey",
"author_id": 114997,
"author_profile": "https://wordpress.stackexchange.com/users/114997",
"pm_score": 2,
"selected": false,
"text": "<p><code>pre_get_posts</code> will run in admin as well as the frontend, you can use it to filter posts that appear to the admin users as well as frontend results. Adding <code>! is_admin()</code> will ensure that that code only affects the frontend.</p>\n\n<p><code>is_main_query()</code> will ensure that you are only affecting the query for the posts, not for example the menu items in the nav bar, or a list of posts in the sidebar. It is recommended to use that.</p>\n\n<p>Let me know if this isn't clear,</p>\n"
},
{
"answer_id": 259988,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 4,
"selected": true,
"text": "<p>Note that when we use:</p>\n\n<pre><code>$query->set( 'post_type', 'post' );\n</code></pre>\n\n<p>then we're overriding all searchable post types, not only the <code>page</code> post type. </p>\n\n<p>That may be just fine in some cases, and we're done using some of your <code>pre_get_posts</code> snippets that fit our needs.</p>\n\n<p>But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.</p>\n\n<p><strong>Using the register_post_type_args filter.</strong></p>\n\n<p>When the post type isn't specified, the <code>WP_Query</code> search uses any post types that are searchable, <a href=\"https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264\" rel=\"nofollow noreferrer\">namely</a>:</p>\n\n<pre><code>$in_search_post_types = get_post_types( array('exclude_from_search' => false) );\n</code></pre>\n\n<p>When we register a post type, we can set the <code>exclude_from_search</code> parameter as false to exclude it from search.</p>\n\n<p>We can modify it for the <code>page</code> post type setup with:</p>\n\n<pre><code>add_filter( 'register_post_type_args', function( $args, $name )\n{\n // Target 'page' post type\n if( 'page' === $name )\n $args['exclude_from_search'] = true;\n\n return $args;\n}, 10, 2 );\n</code></pre>\n\n<p>More about <code>register_post_type()</code> <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>Examples</strong></p>\n\n<p>Here are examples where the page post type would be excluded from the search, using the above filtering:</p>\n\n<ul>\n<li><p>Main query search on the front-end with </p>\n\n<pre><code>https://example.tld?s=testing\n</code></pre></li>\n<li><p>Secondary query like:</p>\n\n<pre><code>$query = new WP_Query( [ 's' => 'testing' ] );\n</code></pre></li>\n<li><p>Secondary query like:</p>\n\n<pre><code>$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );\n</code></pre></li>\n</ul>\n\n<p><strong>Some notes on queries with pre set post types:</strong></p>\n\n<p>Let's consider cases where the post types are fixed, like:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );\n</code></pre>\n\n<p>If the post type is set by some array <code>$post_type</code>, then we can filter the <code>'page'</code> out it with</p>\n\n<pre><code>if( is_array( $post_type ) && count( $post_type ) > 1 )\n{\n $post_type = array_filter( \n $post_type, \n function( $item ) { return 'page' !== $item; } \n );\n}\n</code></pre>\n\n<p>If we don't have direct access to that array, we could use e.g. <code>pre_get_posts</code> to remove the 'page' from the post type array, with help of the <code>get</code>/<code>set</code> methods of <code>WP_Query</code>. Here's an example for the main search query on the front end:</p>\n\n<pre><code>add_action( 'pre_get_posts', function search_filter( \\WP_Query $query )\n{\n if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )\n return;\n\n $post_type = $query->get( 'post_type' );\n\n if( is_array( $post_type ) && count( $post_type ) > 1 )\n {\n $post_type = array_filter( \n $post_type, \n function( $item ) { return 'page' !== $item; } \n );\n $query->set('post_type', $post_type );\n }\n\n} );\n</code></pre>\n\n<p>Why did we check the array count > 1 here?</p>\n\n<p>That's because we should be careful to removing <code>'page'</code> from examples like:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );\n\n $query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );\n</code></pre>\n\n<p>as an empty array or an empty string, for the post type:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );\n\n $query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );\n</code></pre>\n\n<p>will fall back to the <code>'post'</code> post type.</p>\n\n<p>Note that:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );\n</code></pre>\n\n<p>isn't supported, as the resulting post type would be <code>'pagepost'</code>.</p>\n\n<p>In these cases, where we don't have direct access to the <code>WP_Query</code> objects, we could halt the query with tricks like <code>'post__in' => []</code> or <code>1=0</code> in the search WHERE query part or even play with the <code>posts_pre_query</code> filter or using some more advanced methods. There are plenty of answers on this site about that. <a href=\"https://wordpress.stackexchange.com/q/229722/26350\">This</a> and <a href=\"https://wordpress.stackexchange.com/q/226065/\">this</a> is what I recall at the moment.</p>\n\n<p>The <code>null</code> case:</p>\n\n<pre><code> $query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );\n</code></pre>\n\n<p>falls back to <code>'any'</code> post types:</p>\n\n<p>Hope it helps!</p>\n\n<p><strong>PS:</strong></p>\n\n<p>Also note the inconsistency in your snippets, as you have both</p>\n\n<pre><code>add_filter('pre_get_posts','search_filter'); \n</code></pre>\n\n<p>and </p>\n\n<pre><code>add_action('pre_get_posts','search_filter'); \n</code></pre>\n\n<p>It's considered an <em>action</em>, but it will not make any difference, as actions are wrapped as filters, behind the scenes. </p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259970",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115020/"
]
| i've got a question. I created a plugin with a menu and i want to show this under the Dashboard menu-item. In some of my wordpress installations the dashboard item will be overwrited. How can i fix this?
My code to add the menu is:
```
add_menu_page('pluginname', 'pluginname', 'manage_options', 'pluginname-hello', '', 'dashicons-admin-site', 2);
``` | Note that when we use:
```
$query->set( 'post_type', 'post' );
```
then we're overriding all searchable post types, not only the `page` post type.
That may be just fine in some cases, and we're done using some of your `pre_get_posts` snippets that fit our needs.
But sometimes we don't want to hard fix it that way. Here we discuss that kind of scenarios.
**Using the register\_post\_type\_args filter.**
When the post type isn't specified, the `WP_Query` search uses any post types that are searchable, [namely](https://github.com/WordPress/WordPress/blob/d92e1fb1e4ebc3d9c28821023a797f725f7af348/wp-includes/class-wp-query.php#L2264):
```
$in_search_post_types = get_post_types( array('exclude_from_search' => false) );
```
When we register a post type, we can set the `exclude_from_search` parameter as false to exclude it from search.
We can modify it for the `page` post type setup with:
```
add_filter( 'register_post_type_args', function( $args, $name )
{
// Target 'page' post type
if( 'page' === $name )
$args['exclude_from_search'] = true;
return $args;
}, 10, 2 );
```
More about `register_post_type()` [here](https://developer.wordpress.org/reference/functions/register_post_type/).
**Examples**
Here are examples where the page post type would be excluded from the search, using the above filtering:
* Main query search on the front-end with
```
https://example.tld?s=testing
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing' ] );
```
* Secondary query like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'any' ] );
```
**Some notes on queries with pre set post types:**
Let's consider cases where the post types are fixed, like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page', 'post'] ] );
```
If the post type is set by some array `$post_type`, then we can filter the `'page'` out it with
```
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
}
```
If we don't have direct access to that array, we could use e.g. `pre_get_posts` to remove the 'page' from the post type array, with help of the `get`/`set` methods of `WP_Query`. Here's an example for the main search query on the front end:
```
add_action( 'pre_get_posts', function search_filter( \WP_Query $query )
{
if( ! $query->is_search() || ! $query->is_main_query() || ! is_admin() )
return;
$post_type = $query->get( 'post_type' );
if( is_array( $post_type ) && count( $post_type ) > 1 )
{
$post_type = array_filter(
$post_type,
function( $item ) { return 'page' !== $item; }
);
$query->set('post_type', $post_type );
}
} );
```
Why did we check the array count > 1 here?
That's because we should be careful to removing `'page'` from examples like:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [ 'page' ] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page' ] );
```
as an empty array or an empty string, for the post type:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => [] ] );
$query = new WP_Query( [ 's' => 'testing', 'post_type' => '' ] );
```
will fall back to the `'post'` post type.
Note that:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => 'page, post' ] );
```
isn't supported, as the resulting post type would be `'pagepost'`.
In these cases, where we don't have direct access to the `WP_Query` objects, we could halt the query with tricks like `'post__in' => []` or `1=0` in the search WHERE query part or even play with the `posts_pre_query` filter or using some more advanced methods. There are plenty of answers on this site about that. [This](https://wordpress.stackexchange.com/q/229722/26350) and [this](https://wordpress.stackexchange.com/q/226065/) is what I recall at the moment.
The `null` case:
```
$query = new WP_Query( [ 's' => 'testing', 'post_type' => null ] );
```
falls back to `'any'` post types:
Hope it helps!
**PS:**
Also note the inconsistency in your snippets, as you have both
```
add_filter('pre_get_posts','search_filter');
```
and
```
add_action('pre_get_posts','search_filter');
```
It's considered an *action*, but it will not make any difference, as actions are wrapped as filters, behind the scenes. |
259,985 | <p>I have tried is_front_page() but I believe that is the php way of doing it. Perhaps I'm not calling it right because, of course, I'm not getting a response. Maybe I'm just short of my detailed Js ways of accessing the Wordpress classes. </p>
<p>What I'm trying to do is simple. If I am on the front page or home page add this class if I'm not add this other class. Very simple it's just not working. I have even tried a pseudo span tag and add the class to that and it doesn't work. </p>
| [
{
"answer_id": 259986,
"author": "ferdouswp",
"author_id": 114362,
"author_profile": "https://wordpress.stackexchange.com/users/114362",
"pm_score": 0,
"selected": false,
"text": "<p>You can use page id class. If you add page-id class in your java script file maybe solve your problem. </p>\n\n<p><a href=\"https://i.stack.imgur.com/zroWe.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/zroWe.png\" alt=\"enter image description here\"></a></p>\n"
},
{
"answer_id": 259990,
"author": "Dragos Micu",
"author_id": 110131,
"author_profile": "https://wordpress.stackexchange.com/users/110131",
"pm_score": 2,
"selected": false,
"text": "<p>Using jQuery:</p>\n\n<pre><code>jQuery(document).ready(function($){\n if ( $('body').hasClass('home')) {\n $('.menu').addClass('absolute');\n } else {\n $('.menu').addClass('fixed');\n }\n});\n</code></pre>\n"
},
{
"answer_id": 260000,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 3,
"selected": true,
"text": "<p>I just posted <a href=\"https://wordpress.stackexchange.com/a/259996/17305\">an answer to another question</a> about how to do it.</p>\n\n<p>In your case, assuming you used <code>body_class()</code> in your theme, your home page should have a <code><body></code> with class <code>home</code> to it.</p>\n\n<p>So in your JS, you can:</p>\n\n<pre><code>if( $('body.home').length ){\n // Do stuff\n}\n</code></pre>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259985",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64475/"
]
| I have tried is\_front\_page() but I believe that is the php way of doing it. Perhaps I'm not calling it right because, of course, I'm not getting a response. Maybe I'm just short of my detailed Js ways of accessing the Wordpress classes.
What I'm trying to do is simple. If I am on the front page or home page add this class if I'm not add this other class. Very simple it's just not working. I have even tried a pseudo span tag and add the class to that and it doesn't work. | I just posted [an answer to another question](https://wordpress.stackexchange.com/a/259996/17305) about how to do it.
In your case, assuming you used `body_class()` in your theme, your home page should have a `<body>` with class `home` to it.
So in your JS, you can:
```
if( $('body.home').length ){
// Do stuff
}
``` |
259,987 | <p>I have this script that automatically scrolls down to the primary content on page load.</p>
<pre><code>jQuery(document).ready(function($){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);}
});
</code></pre>
<p><strong>1.</strong> However I would like to <em>only</em> apply it to our woocommerce product pages and categories so it doesnt work on home/blog pages. How would i do that? </p>
<p>I can do this <em>poorly</em> by editing WooCommerce core files but i know that's a horrible idea so I'm seeking out help on how to do it correctly via my functions.php file.</p>
<p><strong>2.</strong> Also i would like to know how to apply it to all pages except the home page should that be a better option later on.</p>
<p>Many thanks!</p>
| [
{
"answer_id": 259989,
"author": "Dragos Micu",
"author_id": 110131,
"author_profile": "https://wordpress.stackexchange.com/users/110131",
"pm_score": 2,
"selected": false,
"text": "<p>Step 1: save the code as a new js file, say main.js</p>\n\n<p>Step 2: add a conditional function to function.php of your theme that would say something around the lines:</p>\n\n<pre><code>if (is_shop() || is_product_category()) {\n wp_enqueue_script('main', get_template_directory_uri() . '/js/main.js', false, false, true);\n}\n</code></pre>\n\n<p>Check this page for conditional tags based on your needs:</p>\n\n<p><a href=\"https://docs.woocommerce.com/document/conditional-tags/\" rel=\"nofollow noreferrer\">https://docs.woocommerce.com/document/conditional-tags/</a></p>\n\n<p>Hope it helps!</p>\n\n<p>Edit:</p>\n\n<p>For inline scripting you could do (e.g. inside footer.php):</p>\n\n<pre><code>if (is_shop() || is_product_category()) {?>\n <script>\n jQuery(document).ready(function($){\n if ( $(window).width() < 768 || window.Touch) { \n $('html, body').animate({ scrollTop: $(\"#primary\").offset().top}, 2000);\n } \n });\n </script>\n<?php}\n</code></pre>\n"
},
{
"answer_id": 259996,
"author": "RRikesh",
"author_id": 17305,
"author_profile": "https://wordpress.stackexchange.com/users/17305",
"pm_score": 4,
"selected": true,
"text": "<p>There are two ways you could do that.</p>\n\n<h1>1. Using JS only</h1>\n\n<p>WordPress themes normally use the <a href=\"https://developer.wordpress.org/reference/functions/body_class/\" rel=\"nofollow noreferrer\"><code>body_class()</code></a> function. As a result you'll see that the <code><body></code> tag will have lots of classes. You can then target pages with a specific class to run your code in JavaScript:</p>\n\n<pre><code>if( $('body.whateverclass').length || $('body.anotherclass').length ){\n // Your JS code here\n}\n</code></pre>\n\n<h1>2. Using PHP</h1>\n\n<p>You can harness <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow noreferrer\"><code>wp_localize_script()</code></a> to send a flag to your code.</p>\n\n<p>Let's suppose you enqueued a file called <code>site.js</code> with a handle name of <code>site</code>, in your <code>functions.php</code> you'll have:</p>\n\n<pre><code>wp_register_script( 'site', 'path/to/site.js' );\nwp_enqueue_script( 'site' );\n</code></pre>\n\n<p>You can now add some flags:</p>\n\n<pre><code> wp_register_script( 'site', 'path/to/site.js' ); # Unchanged\n\n $value = '';\n if ( is_shop() || is_some_other_condition() ){\n $value = 'yes';\n }\n wp_localize_script( 'site', 'MYSITE', $value );\n\n wp_enqueue_script( 'site' ); # Unchanged\n</code></pre>\n\n<p>You can then check the <code>MYSITE</code> variable in JavaScript:</p>\n\n<pre><code>if( 'yes' === MYSITE ){\n // Your JS code here\n}\n</code></pre>\n\n<p>Edit:\n<a href=\"https://wordpress.stackexchange.com/questions/259987/apply-jquery-script-to-only-woocommerce-product-pages-and-categories/259996#comment385846_259996\">You asked</a> how to put it in the footer.php:</p>\n\n<pre><code><script>\njQuery(document).ready(function($){\n if( $('body.product-template-default').length || $('body.anotherclass').length ){\n if ( $(window).width() < 768 || window.Touch) { \n $('html, body').animate({ scrollTop: $(\"#primary\").offset().top}, 2000); \n }\n }\n});\n</script> \n</code></pre>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/259987",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
]
| I have this script that automatically scrolls down to the primary content on page load.
```
jQuery(document).ready(function($){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);}
});
```
**1.** However I would like to *only* apply it to our woocommerce product pages and categories so it doesnt work on home/blog pages. How would i do that?
I can do this *poorly* by editing WooCommerce core files but i know that's a horrible idea so I'm seeking out help on how to do it correctly via my functions.php file.
**2.** Also i would like to know how to apply it to all pages except the home page should that be a better option later on.
Many thanks! | There are two ways you could do that.
1. Using JS only
================
WordPress themes normally use the [`body_class()`](https://developer.wordpress.org/reference/functions/body_class/) function. As a result you'll see that the `<body>` tag will have lots of classes. You can then target pages with a specific class to run your code in JavaScript:
```
if( $('body.whateverclass').length || $('body.anotherclass').length ){
// Your JS code here
}
```
2. Using PHP
============
You can harness [`wp_localize_script()`](https://codex.wordpress.org/Function_Reference/wp_localize_script) to send a flag to your code.
Let's suppose you enqueued a file called `site.js` with a handle name of `site`, in your `functions.php` you'll have:
```
wp_register_script( 'site', 'path/to/site.js' );
wp_enqueue_script( 'site' );
```
You can now add some flags:
```
wp_register_script( 'site', 'path/to/site.js' ); # Unchanged
$value = '';
if ( is_shop() || is_some_other_condition() ){
$value = 'yes';
}
wp_localize_script( 'site', 'MYSITE', $value );
wp_enqueue_script( 'site' ); # Unchanged
```
You can then check the `MYSITE` variable in JavaScript:
```
if( 'yes' === MYSITE ){
// Your JS code here
}
```
Edit:
[You asked](https://wordpress.stackexchange.com/questions/259987/apply-jquery-script-to-only-woocommerce-product-pages-and-categories/259996#comment385846_259996) how to put it in the footer.php:
```
<script>
jQuery(document).ready(function($){
if( $('body.product-template-default').length || $('body.anotherclass').length ){
if ( $(window).width() < 768 || window.Touch) {
$('html, body').animate({ scrollTop: $("#primary").offset().top}, 2000);
}
}
});
</script>
``` |
260,015 | <p>I am trying to make my own language switcher for my WordPress site. I am generating all labels using the <code>_e</code> and similar functions. So I am guessing the only thing I need to do is to change the locale used by WordPress. How can I do this programmatically?</p>
<p>So in the ideal scenario when a user clicks on the desired language "this code" is run and WordPress uses the corresponding <code>.mo</code> file for the translation.</p>
| [
{
"answer_id": 260096,
"author": "maxime schoeni",
"author_id": 81094,
"author_profile": "https://wordpress.stackexchange.com/users/81094",
"pm_score": 1,
"selected": false,
"text": "<p>Actually you need to hook in the 'locale' filter to set the language you want:</p>\n\n<pre><code>add_filter('locale', function($locale) {\n return esc_attr($_GET['language']);\n});\n</code></pre>\n\n<p>Then in the links of your switch, you need to pass the language variable:</p>\n\n<pre><code><a href=\"<?php echo add_query_arg('language', 'xx_XX') ?>\">XX</a>\n</code></pre>\n\n<p>Where xx_XX is the language locale code for language XX</p>\n"
},
{
"answer_id": 260129,
"author": "samurdhilbk",
"author_id": 112158,
"author_profile": "https://wordpress.stackexchange.com/users/112158",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to @maxime's answer, I found that the following method worked too. Simply change the <code>$locale</code> global variable. This will fix most translations. If you want to specify the locale for specific text domains, then simply call the <code>load_textdomain()</code> function pointing to the appropriate <code>.mo</code> file.</p>\n\n<pre><code>$locale = 'en_US';\n\nif ( file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {\n load_textdomain( 'my_domain', WP_LANG_DIR . '/' . $locale . '.mo' );\n}\n</code></pre>\n\n<p>Now, in the above example, if your <code>languages</code> folder contains the file <code>en_US.mo</code>, you're good to go.</p>\n\n<p>So when you call something like,</p>\n\n<pre><code>echo _e('Hello', 'my_domain');\n</code></pre>\n\n<p>the appropriate translations in your associated <code>.po</code> file will be reflected.</p>\n\n<p>You can find a detailed explanation at <a href=\"https://codex.buddypress.org/getting-started/customizing/customizing-labels-messages-and-urls/\" rel=\"nofollow noreferrer\">https://codex.buddypress.org/getting-started/customizing/customizing-labels-messages-and-urls/</a>.</p>\n\n<p>This is intended for BuddyPress, but the idea applies generally. </p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112158/"
]
| I am trying to make my own language switcher for my WordPress site. I am generating all labels using the `_e` and similar functions. So I am guessing the only thing I need to do is to change the locale used by WordPress. How can I do this programmatically?
So in the ideal scenario when a user clicks on the desired language "this code" is run and WordPress uses the corresponding `.mo` file for the translation. | Actually you need to hook in the 'locale' filter to set the language you want:
```
add_filter('locale', function($locale) {
return esc_attr($_GET['language']);
});
```
Then in the links of your switch, you need to pass the language variable:
```
<a href="<?php echo add_query_arg('language', 'xx_XX') ?>">XX</a>
```
Where xx\_XX is the language locale code for language XX |
260,021 | <p>I have a project where people can enter their details and only they can see those data by log in to there account.
Instead admin can see all data. </p>
<p>How can i achieve this using wordpress? please help me.</p>
| [
{
"answer_id": 260096,
"author": "maxime schoeni",
"author_id": 81094,
"author_profile": "https://wordpress.stackexchange.com/users/81094",
"pm_score": 1,
"selected": false,
"text": "<p>Actually you need to hook in the 'locale' filter to set the language you want:</p>\n\n<pre><code>add_filter('locale', function($locale) {\n return esc_attr($_GET['language']);\n});\n</code></pre>\n\n<p>Then in the links of your switch, you need to pass the language variable:</p>\n\n<pre><code><a href=\"<?php echo add_query_arg('language', 'xx_XX') ?>\">XX</a>\n</code></pre>\n\n<p>Where xx_XX is the language locale code for language XX</p>\n"
},
{
"answer_id": 260129,
"author": "samurdhilbk",
"author_id": 112158,
"author_profile": "https://wordpress.stackexchange.com/users/112158",
"pm_score": 0,
"selected": false,
"text": "<p>In addition to @maxime's answer, I found that the following method worked too. Simply change the <code>$locale</code> global variable. This will fix most translations. If you want to specify the locale for specific text domains, then simply call the <code>load_textdomain()</code> function pointing to the appropriate <code>.mo</code> file.</p>\n\n<pre><code>$locale = 'en_US';\n\nif ( file_exists( WP_LANG_DIR . '/' . $locale . '.mo' ) ) {\n load_textdomain( 'my_domain', WP_LANG_DIR . '/' . $locale . '.mo' );\n}\n</code></pre>\n\n<p>Now, in the above example, if your <code>languages</code> folder contains the file <code>en_US.mo</code>, you're good to go.</p>\n\n<p>So when you call something like,</p>\n\n<pre><code>echo _e('Hello', 'my_domain');\n</code></pre>\n\n<p>the appropriate translations in your associated <code>.po</code> file will be reflected.</p>\n\n<p>You can find a detailed explanation at <a href=\"https://codex.buddypress.org/getting-started/customizing/customizing-labels-messages-and-urls/\" rel=\"nofollow noreferrer\">https://codex.buddypress.org/getting-started/customizing/customizing-labels-messages-and-urls/</a>.</p>\n\n<p>This is intended for BuddyPress, but the idea applies generally. </p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260021",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115393/"
]
| I have a project where people can enter their details and only they can see those data by log in to there account.
Instead admin can see all data.
How can i achieve this using wordpress? please help me. | Actually you need to hook in the 'locale' filter to set the language you want:
```
add_filter('locale', function($locale) {
return esc_attr($_GET['language']);
});
```
Then in the links of your switch, you need to pass the language variable:
```
<a href="<?php echo add_query_arg('language', 'xx_XX') ?>">XX</a>
```
Where xx\_XX is the language locale code for language XX |
260,035 | <p>Please look at the picture below. I want to get <code>post_id</code> from <code>meta_value</code> = <strong>93</strong>. How can I do that?</p>
<p><a href="https://i.stack.imgur.com/Haekh.png" rel="noreferrer"><img src="https://i.stack.imgur.com/Haekh.png" alt=""></a></p>
| [
{
"answer_id": 260043,
"author": "Thilak",
"author_id": 113208,
"author_profile": "https://wordpress.stackexchange.com/users/113208",
"pm_score": 3,
"selected": false,
"text": "<p>Try this. It will work. </p>\n\n<pre><code>$prepare_guery = $wpdb->prepare( \"SELECT post_id FROM $wpdp->posts where meta_key ='_Wps_crossells' and meta_value like '%%d%'\", $meta_value );\n$get_values = $wpdb->get_col( $prepare_guery );\n</code></pre>\n\n<p><strong>Let me know it's working or not.</strong> </p>\n"
},
{
"answer_id": 332704,
"author": "Munish Thakur",
"author_id": 163923,
"author_profile": "https://wordpress.stackexchange.com/users/163923",
"pm_score": 3,
"selected": false,
"text": "<pre><code>global $wpdb;\n\n$tbl = $wpdb->prefix.'postmeta';\n\n$prepare_guery = $wpdb->prepare( \"SELECT post_id FROM $tbl where meta_key ='_Wps_crossells' and meta_value like '%%d%'\", $meta_value );\n\n$get_values = $wpdb->get_col( $prepare_guery );\n</code></pre>\n\n<p><strong>Note:</strong> Table Should be <code>$wpdb->prefix.'postmeta';</code></p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77080/"
]
| Please look at the picture below. I want to get `post_id` from `meta_value` = **93**. How can I do that?
[](https://i.stack.imgur.com/Haekh.png) | Try this. It will work.
```
$prepare_guery = $wpdb->prepare( "SELECT post_id FROM $wpdp->posts where meta_key ='_Wps_crossells' and meta_value like '%%d%'", $meta_value );
$get_values = $wpdb->get_col( $prepare_guery );
```
**Let me know it's working or not.** |
260,053 | <p>I want to offer my clients WordPress websites, but want to use WP multisite. I've read multiple articles on using a plugin, not using a plugin, etc. </p>
<p>My clients own their own domain names and want me to host/manage their sites. So I'll be using my main website as the install <code>abc.com</code>. </p>
<p>When you visit one of their sites like <code>client1.com</code> or <code>client2.com</code>, I don't want the domain name to be a subsite <code>client1.abc.com</code>. I need them to stay on <code>client1.com</code> or <code>client2.com</code>. </p>
<p>I did find a lot of tutorials, but most are with a plugin and some are reporting buggy behavior. </p>
<p>I've tried messing with the DNS as well, but the site still isn't redirecting. So I guess I'm just looking for the best way to do this. </p>
<p>Any and all help is appreciated.</p>
| [
{
"answer_id": 260186,
"author": "Justin",
"author_id": 114945,
"author_profile": "https://wordpress.stackexchange.com/users/114945",
"pm_score": 1,
"selected": false,
"text": "<p>To keep your options open with an open architecture you can create a multisite Network installation with multiple Networks. This means for each separate client you would give them a new Network. The advantage of this is that you can offer the scalability to Clients and keep your options open. Clients can easily have more sites (sub-domains) added to their Network.</p>\n\n<p>structure would be </p>\n\n<pre><code>Network1 > abc.com (main site for the whole Wordpress Multi-Network install)\nNetwork2 > client1.com\nNetwork3 > client2.com\nNetwork4 > client3.com\nNetwork4 > client3.com/shop\n</code></pre>\n\n<p>this shows,</p>\n\n<ul>\n<li>Client1&2 have only one main site.</li>\n<li>Client3 has a main site \"client3.com\" and also one \"client3.com/shop\" subsite/sub-domain.</li>\n</ul>\n\n<p>To make all this happen you need to install the plugin <a href=\"https://wordpress.org/plugins/wp-multi-network/\" rel=\"nofollow noreferrer\">wp-multi-network</a>. Follow the install guidance for setup within wp-config.php for the plugin and \nalso add this to your wp-config.php file..</p>\n\n<pre><code>define( 'WP_HOME', '//' . $_SERVER['HTTP_HOST'] );\ndefine( 'WP_SITEURL', '//' . $_SERVER['HTTP_HOST'] );\n</code></pre>\n\n<p>Be sure when you create your Wordpress Multi Network installation select \"subfolder\" install and not \"subdomain\" installation (refer to the codex <a href=\"https://codex.wordpress.org/Create_A_Network\" rel=\"nofollow noreferrer\">codex.wordpress.org/Create_A_Network</a>) and configure your sites for wordpress pretty permalinks (ref <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow noreferrer\">codex.wordpress.org/Using_Permalinks</a>)</p>\n"
},
{
"answer_id": 378030,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 0,
"selected": false,
"text": "<p>To do this, set the sites URL option to client1.com and it will handle traffic for client1.com. It's as simple as that. You can do this by editing the site in the network admin. No additional configuration changes should be necessary, and it doesn't matter if you chose a subdirectory or a subdomain install.</p>\n<p>Don't forget to update your host/server/DNS. Just because WordPress knows to handle traffic for that domain, doesn't mean requests to that domain will be routed to WordPress.</p>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260053",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/44899/"
]
| I want to offer my clients WordPress websites, but want to use WP multisite. I've read multiple articles on using a plugin, not using a plugin, etc.
My clients own their own domain names and want me to host/manage their sites. So I'll be using my main website as the install `abc.com`.
When you visit one of their sites like `client1.com` or `client2.com`, I don't want the domain name to be a subsite `client1.abc.com`. I need them to stay on `client1.com` or `client2.com`.
I did find a lot of tutorials, but most are with a plugin and some are reporting buggy behavior.
I've tried messing with the DNS as well, but the site still isn't redirecting. So I guess I'm just looking for the best way to do this.
Any and all help is appreciated. | To keep your options open with an open architecture you can create a multisite Network installation with multiple Networks. This means for each separate client you would give them a new Network. The advantage of this is that you can offer the scalability to Clients and keep your options open. Clients can easily have more sites (sub-domains) added to their Network.
structure would be
```
Network1 > abc.com (main site for the whole Wordpress Multi-Network install)
Network2 > client1.com
Network3 > client2.com
Network4 > client3.com
Network4 > client3.com/shop
```
this shows,
* Client1&2 have only one main site.
* Client3 has a main site "client3.com" and also one "client3.com/shop" subsite/sub-domain.
To make all this happen you need to install the plugin [wp-multi-network](https://wordpress.org/plugins/wp-multi-network/). Follow the install guidance for setup within wp-config.php for the plugin and
also add this to your wp-config.php file..
```
define( 'WP_HOME', '//' . $_SERVER['HTTP_HOST'] );
define( 'WP_SITEURL', '//' . $_SERVER['HTTP_HOST'] );
```
Be sure when you create your Wordpress Multi Network installation select "subfolder" install and not "subdomain" installation (refer to the codex [codex.wordpress.org/Create\_A\_Network](https://codex.wordpress.org/Create_A_Network)) and configure your sites for wordpress pretty permalinks (ref [codex.wordpress.org/Using\_Permalinks](https://codex.wordpress.org/Using_Permalinks)) |
260,070 | <p>I am trying to change pages when I search by category on my website. When I am not searching under a certain category I can switch pages fine but when I am searching for a category I am unable to switch pages. </p>
<pre><code>$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$orderby = ( get_query_var( 'orderby' ) ) ? absint( get_query_var( 'orderby' ) ) : 'display_name';
if($_GET['search'] && !empty($_GET['search'])) {
$search = $_GET['search'];
}
if($_GET['category'] && !empty($_GET['category'])) {
$category = $_GET['category'];
}
$args = array(
'orderby' => 'rand',
'number' => 7,
'paged' => $paged,
'search' => '*'.esc_attr( $search ).'*',
'meta_query' => array (
array(
'key' => 'organization_category_2',
'value' => $category,
'compare' => 'like'
)
)
);
$user_query = new WP_User_Query($args);
</code></pre>
<p>And my pagination links:</p>
<pre><code><?php
$total_user = $user_query->total_users;
$total_pages=ceil($total_user/7);
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '?paged=%#%',
'current' => $paged,
'total' => $total_pages,
'prev_text' => 'Previous',
'next_text' => 'Next',
'type' => 'list',
));
?>
</code></pre>
<p>Whenever I try and do a search I get a url like this:</p>
<p><code>https://mywebsite.ca/directory/?search&category=Government#038;category=Government&paged=2</code></p>
| [
{
"answer_id": 260072,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>The pagination functions work off of the main query, so you'd need to use <code>pre_get_posts</code> instead of creating a new query for them to work.</p>\n\n<p>But, you're using <code>WP_User_Query</code>, so the standard pagination system will never work for you. You're going to have to 'roll your own' pagination system here, and generate your own URLs manually, and set the page yourself based on the URL</p>\n"
},
{
"answer_id": 260128,
"author": "Mukii kumar",
"author_id": 88892,
"author_profile": "https://wordpress.stackexchange.com/users/88892",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if( $user_query->max_num_pages > 1 ) {\n\n $big = 999999;\n echo paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, $paged ),\n 'total' => $user_query->max_num_pages\n ) );\n}\n</code></pre>\n\n<p>This might be useful for you</p>\n"
},
{
"answer_id": 305339,
"author": "Stefan",
"author_id": 93082,
"author_profile": "https://wordpress.stackexchange.com/users/93082",
"pm_score": 1,
"selected": false,
"text": "<p>This is example from officialy WordPress Codex\n<a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query</a></p>\n\n<p>Example of a custom query: </p>\n\n<pre><code><?php\n//Protect against arbitrary paged values\n$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;\n\n$args = array(\n 'posts_per_page' => 5,\n 'category_name' => 'gallery',\n 'paged' => $paged,\n);\n\n$the_query = new WP_Query( $args );\n?>\n<!-- the loop etc.. -->\n</code></pre>\n\n<p>Example of paginate_links parameters adapted to the custom query above: </p>\n\n<pre><code><?php\n$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $the_query->max_num_pages\n) );\n?>\n</code></pre>\n"
}
]
| 2017/03/14 | [
"https://wordpress.stackexchange.com/questions/260070",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80568/"
]
| I am trying to change pages when I search by category on my website. When I am not searching under a certain category I can switch pages fine but when I am searching for a category I am unable to switch pages.
```
$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;
$orderby = ( get_query_var( 'orderby' ) ) ? absint( get_query_var( 'orderby' ) ) : 'display_name';
if($_GET['search'] && !empty($_GET['search'])) {
$search = $_GET['search'];
}
if($_GET['category'] && !empty($_GET['category'])) {
$category = $_GET['category'];
}
$args = array(
'orderby' => 'rand',
'number' => 7,
'paged' => $paged,
'search' => '*'.esc_attr( $search ).'*',
'meta_query' => array (
array(
'key' => 'organization_category_2',
'value' => $category,
'compare' => 'like'
)
)
);
$user_query = new WP_User_Query($args);
```
And my pagination links:
```
<?php
$total_user = $user_query->total_users;
$total_pages=ceil($total_user/7);
echo paginate_links(array(
'base' => get_pagenum_link(1) . '%_%',
'format' => '?paged=%#%',
'current' => $paged,
'total' => $total_pages,
'prev_text' => 'Previous',
'next_text' => 'Next',
'type' => 'list',
));
?>
```
Whenever I try and do a search I get a url like this:
`https://mywebsite.ca/directory/?search&category=Government#038;category=Government&paged=2` | The pagination functions work off of the main query, so you'd need to use `pre_get_posts` instead of creating a new query for them to work.
But, you're using `WP_User_Query`, so the standard pagination system will never work for you. You're going to have to 'roll your own' pagination system here, and generate your own URLs manually, and set the page yourself based on the URL |
260,083 | <p>How can I use <code>do_action</code> and <code>add_action</code> to return an array in <code>do_action</code>?</p>
<p>My sample code:</p>
<pre><code>function name_fun_one(){
$namearray[] = array('k1'=> 'text1', 'k2' => 'text1');
$namearray[] = array('k1'=> 'text2', 'k2' => 'text2');
do_action('add_in_namearray');
foreach($namearray as $val)
{
//loop
}
}
function add_name_fun_one()
{
$namearray[] = array('k1'=> 'text3', 'k2' => 'text3');
$namearray[] = array('k1'=> 'text4', 'k2' => 'text4');
}
add_action('name_fun_one', 'add_name_fun_one');
</code></pre>
| [
{
"answer_id": 260072,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 2,
"selected": false,
"text": "<p>The pagination functions work off of the main query, so you'd need to use <code>pre_get_posts</code> instead of creating a new query for them to work.</p>\n\n<p>But, you're using <code>WP_User_Query</code>, so the standard pagination system will never work for you. You're going to have to 'roll your own' pagination system here, and generate your own URLs manually, and set the page yourself based on the URL</p>\n"
},
{
"answer_id": 260128,
"author": "Mukii kumar",
"author_id": 88892,
"author_profile": "https://wordpress.stackexchange.com/users/88892",
"pm_score": 1,
"selected": false,
"text": "<pre><code>if( $user_query->max_num_pages > 1 ) {\n\n $big = 999999;\n echo paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, $paged ),\n 'total' => $user_query->max_num_pages\n ) );\n}\n</code></pre>\n\n<p>This might be useful for you</p>\n"
},
{
"answer_id": 305339,
"author": "Stefan",
"author_id": 93082,
"author_profile": "https://wordpress.stackexchange.com/users/93082",
"pm_score": 1,
"selected": false,
"text": "<p>This is example from officialy WordPress Codex\n<a href=\"https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/paginate_links#Example_With_a_Custom_Query</a></p>\n\n<p>Example of a custom query: </p>\n\n<pre><code><?php\n//Protect against arbitrary paged values\n$paged = ( get_query_var( 'paged' ) ) ? absint( get_query_var( 'paged' ) ) : 1;\n\n$args = array(\n 'posts_per_page' => 5,\n 'category_name' => 'gallery',\n 'paged' => $paged,\n);\n\n$the_query = new WP_Query( $args );\n?>\n<!-- the loop etc.. -->\n</code></pre>\n\n<p>Example of paginate_links parameters adapted to the custom query above: </p>\n\n<pre><code><?php\n$big = 999999999; // need an unlikely integer\n\necho paginate_links( array(\n 'base' => str_replace( $big, '%#%', esc_url( get_pagenum_link( $big ) ) ),\n 'format' => '?paged=%#%',\n 'current' => max( 1, get_query_var('paged') ),\n 'total' => $the_query->max_num_pages\n) );\n?>\n</code></pre>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260083",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115426/"
]
| How can I use `do_action` and `add_action` to return an array in `do_action`?
My sample code:
```
function name_fun_one(){
$namearray[] = array('k1'=> 'text1', 'k2' => 'text1');
$namearray[] = array('k1'=> 'text2', 'k2' => 'text2');
do_action('add_in_namearray');
foreach($namearray as $val)
{
//loop
}
}
function add_name_fun_one()
{
$namearray[] = array('k1'=> 'text3', 'k2' => 'text3');
$namearray[] = array('k1'=> 'text4', 'k2' => 'text4');
}
add_action('name_fun_one', 'add_name_fun_one');
``` | The pagination functions work off of the main query, so you'd need to use `pre_get_posts` instead of creating a new query for them to work.
But, you're using `WP_User_Query`, so the standard pagination system will never work for you. You're going to have to 'roll your own' pagination system here, and generate your own URLs manually, and set the page yourself based on the URL |
260,095 | <p>I need to add a menu to a submenu in admin menu bar. Is it possible to do this in wordpress?</p>
<p>For Example :</p>
<pre><code>A
|
-> B
|
-> C
</code></pre>
<p>Or is there any work-around or hack to accomplish this?</p>
| [
{
"answer_id": 260104,
"author": "Savan Dholu",
"author_id": 108472,
"author_profile": "https://wordpress.stackexchange.com/users/108472",
"pm_score": 1,
"selected": false,
"text": "<p>No, it is not possible to create third level menu in admin panel. If you look at the definition of <strong>add_submenu_page</strong>, you need to mention the parent slug name. For eg:</p>\n\n<pre><code>add_menu_page ( 'Test Menu', 'Test Menu', 'read', 'testmainmenu', '', '' );\nadd_submenu_page ( 'testmainmenu', 'Test Menu', 'Child1', 'read', 'child1', '');\n</code></pre>\n\n<p>The first parameter of the <strong>add_submenu_page</strong> will be parent slug name. So you may think we can write <strong>child1</strong> as parent slug name to create the third level. Eg:</p>\n\n<pre><code>add_submenu_page ( 'child1', 'Test Menu', 'Child2', 'read', 'child2', '');\n</code></pre>\n\n<p>It's not working so go this <a href=\"https://developer.wordpress.org/reference/functions/add_submenu_page/\" rel=\"nofollow noreferrer\">Submenu reference</a> </p>\n"
},
{
"answer_id": 260167,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": false,
"text": "<p>While the main admin menus (i.e., those on the left-hand side of the screen) can only be 2 deep (A > B), nodes in the <a href=\"https://codex.wordpress.org/Toolbar\" rel=\"nofollow noreferrer\">toolbar</a> can be arbitrarily deep.</p>\n\n<p>I don't know if using the toolbar would be a suitable workaround for you, but if so, then you could do something like:</p>\n\n<pre><code>add_action ('wp_before_admin_bar_render', 'wpse_admin_toolbar_test') ;\n\nfunction\nadmin_toolbar ()\n{\n global $wp_admin_bar ;\n\n $args = array (\n 'id' => 'wpse_admin_toolbar_test',\n 'title' => 'WPSE Admin Toolbar Test',\n ) ;\n $node = $wp_admin_bar->add_node ($args) ;\n\n for ($i = 0 ; $i < 4 ; $i++) {\n $args = array (\n 'id' => \"wpse_admin_toolbar_test_item_{$i}\",\n 'parent' => 'wpse_admin_toolbar_test',\n 'title' => \"Item $i\",\n ) ;\n $wp_admin_bar->add_node ($args) ;\n\n for ($y = 0 ; $y < 3 ; $y++) {\n $args = array (\n 'id' => \"wpse_admin_toolbar_test_item_{$i}_subitem_{$y}\",\n 'parent' => \"wpse_admin_toolbar_test_item_{$i}\",\n 'title' => \"Sub Item $y\",\n ) ;\n $wp_admin_bar->add_node ($args) ;\n\n for ($z = 0 ; $z < 2 ; $z++) {\n $args = array (\n 'id' => \"wpse_admin_toolbar_test_item_{$i}_subitem_{$y}_subitem_{$z}\",\n 'parent' => \"wpse_admin_toolbar_test_item_{$i}_subitem_{$y}\",\n 'title' => \"Sub-Sub Item $z\",\n // in the real-world, this URL would be to something that\n // would perform the action for this node\n 'href' => admin_url (),\n ) ;\n $wp_admin_bar->add_node ($args) ;\n }\n }\n }\n\n return ;\n}\n</code></pre>\n\n<p>The above would produce the following:\n<a href=\"https://i.stack.imgur.com/TUQy8.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/TUQy8.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260095",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/90559/"
]
| I need to add a menu to a submenu in admin menu bar. Is it possible to do this in wordpress?
For Example :
```
A
|
-> B
|
-> C
```
Or is there any work-around or hack to accomplish this? | While the main admin menus (i.e., those on the left-hand side of the screen) can only be 2 deep (A > B), nodes in the [toolbar](https://codex.wordpress.org/Toolbar) can be arbitrarily deep.
I don't know if using the toolbar would be a suitable workaround for you, but if so, then you could do something like:
```
add_action ('wp_before_admin_bar_render', 'wpse_admin_toolbar_test') ;
function
admin_toolbar ()
{
global $wp_admin_bar ;
$args = array (
'id' => 'wpse_admin_toolbar_test',
'title' => 'WPSE Admin Toolbar Test',
) ;
$node = $wp_admin_bar->add_node ($args) ;
for ($i = 0 ; $i < 4 ; $i++) {
$args = array (
'id' => "wpse_admin_toolbar_test_item_{$i}",
'parent' => 'wpse_admin_toolbar_test',
'title' => "Item $i",
) ;
$wp_admin_bar->add_node ($args) ;
for ($y = 0 ; $y < 3 ; $y++) {
$args = array (
'id' => "wpse_admin_toolbar_test_item_{$i}_subitem_{$y}",
'parent' => "wpse_admin_toolbar_test_item_{$i}",
'title' => "Sub Item $y",
) ;
$wp_admin_bar->add_node ($args) ;
for ($z = 0 ; $z < 2 ; $z++) {
$args = array (
'id' => "wpse_admin_toolbar_test_item_{$i}_subitem_{$y}_subitem_{$z}",
'parent' => "wpse_admin_toolbar_test_item_{$i}_subitem_{$y}",
'title' => "Sub-Sub Item $z",
// in the real-world, this URL would be to something that
// would perform the action for this node
'href' => admin_url (),
) ;
$wp_admin_bar->add_node ($args) ;
}
}
}
return ;
}
```
The above would produce the following:
[](https://i.stack.imgur.com/TUQy8.png) |
260,105 | <p>This is a question I can't find the answer to:</p>
<p><strong>Can I run two separate Multisite networks under one domain?</strong></p>
<p>Here's the scenario, to better explain, we have a company website that already uses a WordPress Multisite network to run our country sites, like so:</p>
<pre><code>http://www.companysite.com/
http://www.companysite.com/fr/
http://www.companysite.com/se/
http://www.companysite.com/de/
http://www.companysite.com/jp/
http://www.companysite.com/cn/
etc.
</code></pre>
<p>All of these sites use the same theme, the same plugins, so it makes sense to run them off one network.</p>
<p>Then we have a bunch of separate "stand-alone" wordpress sites that are marketing "campaign"-based sites, each one unique, usually developed by 3rd parties, with their own themes and plugins, which run of sub-directories of the multisite installations:</p>
<pre><code>http://www.companysite.com/education
http://www.companysite.com/marketing
http://www.companysite.com/innovation
etc.
</code></pre>
<p>We don't really want to run them off the same Multisite installation because these use different themes and plugins, are written by 3rd parties, are subject to spikes due to marketing campaigns, and are less secure/stable than our country based sites network.</p>
<p>However, we do need them to be on the same domain...</p>
<p>Which brings me back to my original question:</p>
<p><strong>Can I run two separate Multisite networks under one domain?</strong></p>
<p>Thanks for reading!</p>
| [
{
"answer_id": 260109,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 1,
"selected": false,
"text": "<p>You can install a new wordpress in a sub folder, let's call it \"www2\", so you'll have this URL : </p>\n\n<pre><code>http://www2.companysite.com/\n</code></pre>\n\n<p>Then you configure your NEW network so you can have this structure : </p>\n\n<pre><code>http://www2.companysite.com/education\nhttp://www2.companysite.com/marketing\n</code></pre>\n\n<p>Now you have 2 seperate wordpress installations and 2 different networks.</p>\n\n<p>Wish this is what you'r looking for :)</p>\n"
},
{
"answer_id": 260110,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 3,
"selected": true,
"text": "<p>You can not run different networks or different Multisite installations under one domain in the default possibilities of WP. But you can use one Multiste with multiple networks with the help of a plugin - <a href=\"https://wordpress.org/plugins/wp-multi-network/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-multi-network/</a></p>\n\n<p>With this plugin get you the chance to create different networks with sites in one installation, one Multisite. Like the follow structure example.</p>\n\n<pre><code>http://www.companysite.com/education\n -- /www.companysite.com/education/de\n -- /www.companysite.com/education/en\n -- ...\nhttp://www.companysite.com/marketing\n -- /www.companysite.com/marketing/de\n -- /www.companysite.com/marketing/en\n -- ...\nhttp://www.companysite.com/innovation\n -- /www.companysite.com/innovation/de\n -- /www.companysite.com/innovation/en\n -- ...\n</code></pre>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73939/"
]
| This is a question I can't find the answer to:
**Can I run two separate Multisite networks under one domain?**
Here's the scenario, to better explain, we have a company website that already uses a WordPress Multisite network to run our country sites, like so:
```
http://www.companysite.com/
http://www.companysite.com/fr/
http://www.companysite.com/se/
http://www.companysite.com/de/
http://www.companysite.com/jp/
http://www.companysite.com/cn/
etc.
```
All of these sites use the same theme, the same plugins, so it makes sense to run them off one network.
Then we have a bunch of separate "stand-alone" wordpress sites that are marketing "campaign"-based sites, each one unique, usually developed by 3rd parties, with their own themes and plugins, which run of sub-directories of the multisite installations:
```
http://www.companysite.com/education
http://www.companysite.com/marketing
http://www.companysite.com/innovation
etc.
```
We don't really want to run them off the same Multisite installation because these use different themes and plugins, are written by 3rd parties, are subject to spikes due to marketing campaigns, and are less secure/stable than our country based sites network.
However, we do need them to be on the same domain...
Which brings me back to my original question:
**Can I run two separate Multisite networks under one domain?**
Thanks for reading! | You can not run different networks or different Multisite installations under one domain in the default possibilities of WP. But you can use one Multiste with multiple networks with the help of a plugin - <https://wordpress.org/plugins/wp-multi-network/>
With this plugin get you the chance to create different networks with sites in one installation, one Multisite. Like the follow structure example.
```
http://www.companysite.com/education
-- /www.companysite.com/education/de
-- /www.companysite.com/education/en
-- ...
http://www.companysite.com/marketing
-- /www.companysite.com/marketing/de
-- /www.companysite.com/marketing/en
-- ...
http://www.companysite.com/innovation
-- /www.companysite.com/innovation/de
-- /www.companysite.com/innovation/en
-- ...
``` |
260,114 | <p>i'm working on a plugin and i got a checkbox with the setting code:</p>
<pre><code> register_setting('plugin551-setting-group', 'livechat_option');
</code></pre>
<p>I want it to be default true, the checkbox in the setting page is now default false.
How can i do this?</p>
| [
{
"answer_id": 260109,
"author": "Sami",
"author_id": 102593,
"author_profile": "https://wordpress.stackexchange.com/users/102593",
"pm_score": 1,
"selected": false,
"text": "<p>You can install a new wordpress in a sub folder, let's call it \"www2\", so you'll have this URL : </p>\n\n<pre><code>http://www2.companysite.com/\n</code></pre>\n\n<p>Then you configure your NEW network so you can have this structure : </p>\n\n<pre><code>http://www2.companysite.com/education\nhttp://www2.companysite.com/marketing\n</code></pre>\n\n<p>Now you have 2 seperate wordpress installations and 2 different networks.</p>\n\n<p>Wish this is what you'r looking for :)</p>\n"
},
{
"answer_id": 260110,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 3,
"selected": true,
"text": "<p>You can not run different networks or different Multisite installations under one domain in the default possibilities of WP. But you can use one Multiste with multiple networks with the help of a plugin - <a href=\"https://wordpress.org/plugins/wp-multi-network/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/wp-multi-network/</a></p>\n\n<p>With this plugin get you the chance to create different networks with sites in one installation, one Multisite. Like the follow structure example.</p>\n\n<pre><code>http://www.companysite.com/education\n -- /www.companysite.com/education/de\n -- /www.companysite.com/education/en\n -- ...\nhttp://www.companysite.com/marketing\n -- /www.companysite.com/marketing/de\n -- /www.companysite.com/marketing/en\n -- ...\nhttp://www.companysite.com/innovation\n -- /www.companysite.com/innovation/de\n -- /www.companysite.com/innovation/en\n -- ...\n</code></pre>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115020/"
]
| i'm working on a plugin and i got a checkbox with the setting code:
```
register_setting('plugin551-setting-group', 'livechat_option');
```
I want it to be default true, the checkbox in the setting page is now default false.
How can i do this? | You can not run different networks or different Multisite installations under one domain in the default possibilities of WP. But you can use one Multiste with multiple networks with the help of a plugin - <https://wordpress.org/plugins/wp-multi-network/>
With this plugin get you the chance to create different networks with sites in one installation, one Multisite. Like the follow structure example.
```
http://www.companysite.com/education
-- /www.companysite.com/education/de
-- /www.companysite.com/education/en
-- ...
http://www.companysite.com/marketing
-- /www.companysite.com/marketing/de
-- /www.companysite.com/marketing/en
-- ...
http://www.companysite.com/innovation
-- /www.companysite.com/innovation/de
-- /www.companysite.com/innovation/en
-- ...
``` |
260,117 | <p>I am new to wordpress, I am trying to develop a theme on localhost, I am trying to load style.css using this code in functions.php</p>
<pre><code>function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
</code></pre>
<p>And style.css is</p>
<pre><code>body{background:green;}
</code></pre>
<p>But this code is not working </p>
<p>Can someone explain what i am doing wrong here ?</p>
| [
{
"answer_id": 260118,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": 4,
"selected": true,
"text": "<p>Are you sure you theme is active?</p>\n\n<p>If you see your style.css code it should not have only the CSS code but also the Theme defination at header of your style.css.</p>\n\n<p>Please make sure if your theme is active. </p>\n\n<p>The above code for loading CSS file looks good and should work if your theme is active.</p>\n\n<p><strong>Update</strong> :</p>\n\n<p>Have you added <code>wp_head()</code> and <code>wp_footer()</code> in <code>header.php</code> and <code>footer.php</code> respectively?</p>\n\n<p><code>wp_head()</code> should be added before <code></head></code> tag in your HTML and <code>wp_footer()</code> should be added before <code></body></code> tag in HTML.</p>\n"
},
{
"answer_id": 260124,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 0,
"selected": false,
"text": "<p>Style.css is added by default when you make your theme. Why you want to add it through functions.php? You can also call any css in header.php also.</p>\n"
},
{
"answer_id": 359584,
"author": "Paras shah",
"author_id": 183429,
"author_profile": "https://wordpress.stackexchange.com/users/183429",
"pm_score": 0,
"selected": false,
"text": "<p>Added <code>wp_head()</code> and <code>wp_footer()</code> in header.php and footer.php file\nand make sure make file functions.php to add your files using this two function <code>wp_enqueue_style</code> and <code>wp_enqueue_script</code></p>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114573/"
]
| I am new to wordpress, I am trying to develop a theme on localhost, I am trying to load style.css using this code in functions.php
```
function add_theme_scripts() {
wp_enqueue_style( 'style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'add_theme_scripts' );
```
And style.css is
```
body{background:green;}
```
But this code is not working
Can someone explain what i am doing wrong here ? | Are you sure you theme is active?
If you see your style.css code it should not have only the CSS code but also the Theme defination at header of your style.css.
Please make sure if your theme is active.
The above code for loading CSS file looks good and should work if your theme is active.
**Update** :
Have you added `wp_head()` and `wp_footer()` in `header.php` and `footer.php` respectively?
`wp_head()` should be added before `</head>` tag in your HTML and `wp_footer()` should be added before `</body>` tag in HTML. |
260,134 | <p>I am getting post id from url like this</p>
<pre><code>https://www.example.com/download/?id=241
</code></pre>
<p>and in base of this id i want to get post data from db but it is getting nothing i tried this code</p>
<pre><code> <?php
$id = $_GET['id'];
// WP_Query arguments
$args = array (
'category_name' => 'download',
'showposts' => '1',
'post_id' => $id,
'post_type' => 'page'
);
// The Query
$my_query = new WP_Query( $args );
//print_r($my_query);
if ($my_query->have_posts() ) : while ($my_query->have_posts() ) : $my_query->the_post(); // Start the loop
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id, true);
?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" target="_blank">
<img src="<?php echo $thumb_url[0]; ?>" />
<h3><?php the_title(); ?></h3>
<time>تاريخ النشر: <?php the_time('l, F j, Y'); ?></time>
</a>
<?php
endwhile; endif;// End the Loop and Check for Posts
wp_reset_query(); // Reset the loop
?>
</code></pre>
<p>So i want to get the data by using the <code>id</code> i am getting through url. So please tell me what can i do with my code</p>
| [
{
"answer_id": 260135,
"author": "ehsan",
"author_id": 109403,
"author_profile": "https://wordpress.stackexchange.com/users/109403",
"pm_score": 1,
"selected": false,
"text": "<p>You may use $_GET parameter to get the id.</p>\n\n<pre><code>$id = $_GET['id'];\n</code></pre>\n\n<p>Or try this:</p>\n\n<pre><code>global $post;\necho $post->ID;\n</code></pre>\n\n<p>But it seems you have a problem in the args array. when you know the exact id of requested post you don't need to use it like that. you can use this instead:</p>\n\n<pre><code>get_post($id);\n</code></pre>\n\n<p>And then you do not need to loop through because you have one post to show.</p>\n"
},
{
"answer_id": 262180,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 0,
"selected": false,
"text": "<p>It's not working for a couple reasons.</p>\n\n<ol>\n<li>You are trying to query the ID of a page and are specify a category taxonomy. Pages don't have categories associated with them normally.</li>\n<li>The download is likely it's own post type so you'll want to specify that instead of \"page\"</li>\n</ol>\n\n<p>Change your query args to the following and that <em>should</em> do the trick (based on the info that I have).</p>\n\n<pre><code>$args = array (\n 'post_type' => 'download', //use post_type instead since downloads is a post type not a taxonomy \n 'posts_per_page' => '1',\n 'post_id' => $id,\n);\n</code></pre>\n"
},
{
"answer_id": 286826,
"author": "Anand Pratap Rao",
"author_id": 132030,
"author_profile": "https://wordpress.stackexchange.com/users/132030",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$id = $_GET['id']; // get the ID from the URL\n\n$post_data = get_post($id); // get post object\n</code></pre>\n\n<p>Then you get the post in <code>$post_data</code>. Simply check with:</p>\n\n<pre><code>var_dump($post_data);\n</code></pre>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260134",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113134/"
]
| I am getting post id from url like this
```
https://www.example.com/download/?id=241
```
and in base of this id i want to get post data from db but it is getting nothing i tried this code
```
<?php
$id = $_GET['id'];
// WP_Query arguments
$args = array (
'category_name' => 'download',
'showposts' => '1',
'post_id' => $id,
'post_type' => 'page'
);
// The Query
$my_query = new WP_Query( $args );
//print_r($my_query);
if ($my_query->have_posts() ) : while ($my_query->have_posts() ) : $my_query->the_post(); // Start the loop
$thumb_id = get_post_thumbnail_id();
$thumb_url = wp_get_attachment_image_src($thumb_id, true);
?>
<a href="<?php the_permalink() ?>" title="<?php the_title(); ?>" target="_blank">
<img src="<?php echo $thumb_url[0]; ?>" />
<h3><?php the_title(); ?></h3>
<time>تاريخ النشر: <?php the_time('l, F j, Y'); ?></time>
</a>
<?php
endwhile; endif;// End the Loop and Check for Posts
wp_reset_query(); // Reset the loop
?>
```
So i want to get the data by using the `id` i am getting through url. So please tell me what can i do with my code | You may use $\_GET parameter to get the id.
```
$id = $_GET['id'];
```
Or try this:
```
global $post;
echo $post->ID;
```
But it seems you have a problem in the args array. when you know the exact id of requested post you don't need to use it like that. you can use this instead:
```
get_post($id);
```
And then you do not need to loop through because you have one post to show. |
260,141 | <p>i'm try to filter posts by an cascade dropdown categories.
But when i select an option of the cascade, he showing all the posts.
How can i filter ONLY posts through the selected option?</p>
<p>This is my structure:</p>
<p><strong>Functions.php</strong></p>
<pre><code> function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() . '/assets/js/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'exclude' => '1,2,4,5,7,8,9,10,11,12',
'post_type' => 'post',
'nopaging' => true, // show all posts in one go
);
echo $taxonomy;
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-md-4">
<div class="img-thumb">
<a href="<?php the_field('link_do_case'); ?>">
<?php the_post_thumbnail(); ?>
</a>
</div>
<small><?php the_title(); ?></small>
</div>
<?php endwhile; ?>
<?php else: ?>
<h2>Case não encontrado</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
</code></pre>
<p>This is my script</p>
<pre><code>jQuery(document).ready(function(jQuery) {
jQuery('.post-tags select').on('change', function(event) {
console.log('mudou');
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = jQuery(this).attr('title');
// After user click on tag, fade out list of posts
jQuery('.tagged-posts').fadeOut();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
};
jQuery.post( afp_vars.afp_ajax_url, data, function(response) {
if( response ) {
// Display posts on page
jQuery('.tagged-posts').html( response );
// Restore div visibility
jQuery('.tagged-posts').fadeIn();
};
});
});
});
</code></pre>
<p>And this is my structure page</p>
<pre><code><div id="ajax-cases">
<?php
// WP Query
$args = array(
'post_type' => 'post',
'exclude' => '1,2,4,5,7,8,9,10,11',
'post_status' => 'publish',
'nopaging' => true, // show all posts in one go
);
$query = new WP_Query( $args );
$tax = 'category';
$terms = get_terms( $tax, $args);
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<h2>Busque pelo tipo de Trabalho</h2>
<?php
echo '<select>';
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '<option value="' . $term_link . '" class="tax-filter">' . $term->name . '</option> ';
}
echo '</select>';
?>
</div>
<?php endif ;?>
<div class="tagged-posts">
// here must be show the posts selected trough the category option
</div>
</code></pre>
<p></p>
| [
{
"answer_id": 260135,
"author": "ehsan",
"author_id": 109403,
"author_profile": "https://wordpress.stackexchange.com/users/109403",
"pm_score": 1,
"selected": false,
"text": "<p>You may use $_GET parameter to get the id.</p>\n\n<pre><code>$id = $_GET['id'];\n</code></pre>\n\n<p>Or try this:</p>\n\n<pre><code>global $post;\necho $post->ID;\n</code></pre>\n\n<p>But it seems you have a problem in the args array. when you know the exact id of requested post you don't need to use it like that. you can use this instead:</p>\n\n<pre><code>get_post($id);\n</code></pre>\n\n<p>And then you do not need to loop through because you have one post to show.</p>\n"
},
{
"answer_id": 262180,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 0,
"selected": false,
"text": "<p>It's not working for a couple reasons.</p>\n\n<ol>\n<li>You are trying to query the ID of a page and are specify a category taxonomy. Pages don't have categories associated with them normally.</li>\n<li>The download is likely it's own post type so you'll want to specify that instead of \"page\"</li>\n</ol>\n\n<p>Change your query args to the following and that <em>should</em> do the trick (based on the info that I have).</p>\n\n<pre><code>$args = array (\n 'post_type' => 'download', //use post_type instead since downloads is a post type not a taxonomy \n 'posts_per_page' => '1',\n 'post_id' => $id,\n);\n</code></pre>\n"
},
{
"answer_id": 286826,
"author": "Anand Pratap Rao",
"author_id": 132030,
"author_profile": "https://wordpress.stackexchange.com/users/132030",
"pm_score": 1,
"selected": false,
"text": "<pre><code>$id = $_GET['id']; // get the ID from the URL\n\n$post_data = get_post($id); // get post object\n</code></pre>\n\n<p>Then you get the post in <code>$post_data</code>. Simply check with:</p>\n\n<pre><code>var_dump($post_data);\n</code></pre>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260141",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84579/"
]
| i'm try to filter posts by an cascade dropdown categories.
But when i select an option of the cascade, he showing all the posts.
How can i filter ONLY posts through the selected option?
This is my structure:
**Functions.php**
```
function ajax_filter_posts_scripts() {
// Enqueue script
wp_register_script('afp_script', get_template_directory_uri() . '/assets/js/ajax-filter-posts.js', false, null, false);
wp_enqueue_script('afp_script');
wp_localize_script( 'afp_script', 'afp_vars', array(
'afp_nonce' => wp_create_nonce( 'afp_nonce' ), // Create nonce which we later will use to verify AJAX request
'afp_ajax_url' => admin_url( 'admin-ajax.php' ),
)
);
}
add_action('wp_enqueue_scripts', 'ajax_filter_posts_scripts', 100);
// Script for getting posts
function ajax_filter_get_posts( $taxonomy ) {
// Verify nonce
if( !isset( $_POST['afp_nonce'] ) || !wp_verify_nonce( $_POST['afp_nonce'], 'afp_nonce' ) )
die('Permission denied');
$taxonomy = $_POST['taxonomy'];
// WP Query
$args = array(
'exclude' => '1,2,4,5,7,8,9,10,11,12',
'post_type' => 'post',
'nopaging' => true, // show all posts in one go
);
echo $taxonomy;
// If taxonomy is not set, remove key from array and get all posts
if( !$taxonomy ) {
unset( $args['tag'] );
}
$query = new WP_Query( $args );
if ( $query->have_posts() ) : while ( $query->have_posts() ) : $query->the_post(); ?>
<div class="col-md-4">
<div class="img-thumb">
<a href="<?php the_field('link_do_case'); ?>">
<?php the_post_thumbnail(); ?>
</a>
</div>
<small><?php the_title(); ?></small>
</div>
<?php endwhile; ?>
<?php else: ?>
<h2>Case não encontrado</h2>
<?php endif;
die();
}
add_action('wp_ajax_filter_posts', 'ajax_filter_get_posts');
add_action('wp_ajax_nopriv_filter_posts', 'ajax_filter_get_posts');
```
This is my script
```
jQuery(document).ready(function(jQuery) {
jQuery('.post-tags select').on('change', function(event) {
console.log('mudou');
// Prevent default action - opening tag page
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
// Get tag slug from title attirbute
var selecetd_taxonomy = jQuery(this).attr('title');
// After user click on tag, fade out list of posts
jQuery('.tagged-posts').fadeOut();
data = {
action: 'filter_posts', // function to execute
afp_nonce: afp_vars.afp_nonce, // wp_nonce
taxonomy: selecetd_taxonomy, // selected tag
};
jQuery.post( afp_vars.afp_ajax_url, data, function(response) {
if( response ) {
// Display posts on page
jQuery('.tagged-posts').html( response );
// Restore div visibility
jQuery('.tagged-posts').fadeIn();
};
});
});
});
```
And this is my structure page
```
<div id="ajax-cases">
<?php
// WP Query
$args = array(
'post_type' => 'post',
'exclude' => '1,2,4,5,7,8,9,10,11',
'post_status' => 'publish',
'nopaging' => true, // show all posts in one go
);
$query = new WP_Query( $args );
$tax = 'category';
$terms = get_terms( $tax, $args);
$count = count( $terms );
if ( $count > 0 ): ?>
<div class="post-tags">
<h2>Busque pelo tipo de Trabalho</h2>
<?php
echo '<select>';
foreach ( $terms as $term ) {
$term_link = get_term_link( $term, $tax );
echo '<option value="' . $term_link . '" class="tax-filter">' . $term->name . '</option> ';
}
echo '</select>';
?>
</div>
<?php endif ;?>
<div class="tagged-posts">
// here must be show the posts selected trough the category option
</div>
``` | You may use $\_GET parameter to get the id.
```
$id = $_GET['id'];
```
Or try this:
```
global $post;
echo $post->ID;
```
But it seems you have a problem in the args array. when you know the exact id of requested post you don't need to use it like that. you can use this instead:
```
get_post($id);
```
And then you do not need to loop through because you have one post to show. |
260,180 | <p>When should you use <code>add_action</code> to enqueue or register a script, vs just using <code>wp_register_script</code> and/or <code>wp_enqueue_script</code>? In other words, both <code>example 1</code> and <code>example 2</code> below seem to accomplish the same thing when in <code>functions.php</code>, so why do so many resources say that <code>example 1</code> is the correct way of loading scripts in WP?</p>
<p><strong>Example 1:</strong></p>
<pre><code>function my_assets() {
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
}
add_action( 'wp_enqueue_scripts', 'my_assets' );
</code></pre>
<p><strong>Example 2:</strong></p>
<pre><code>wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
</code></pre>
<p>(yes, I know in example 2 you could skip registering the script and just enqueue it as necessary)</p>
| [
{
"answer_id": 260181,
"author": "kraftner",
"author_id": 47733,
"author_profile": "https://wordpress.stackexchange.com/users/47733",
"pm_score": 1,
"selected": false,
"text": "<p>Well it works the same <em>in the case where you tested it</em>.</p>\n\n<p>The answer could actually be somewhat complex, but mainly having it inside an action callback only registers them when needed, just putting it inside the <code>functions.php</code> it happens always when the theme is active.</p>\n\n<p>First of all this can be a waste of performance, registering stuff that is never used. You might think that it should be there in any case, but actually in WP there are plenty of situations where frontend JS/CSS is totally irrelevant. The most obvious situation is the backend. But also some plugin might create an endpoint that doesn't need JS/CSS. And there are plenty more of that.</p>\n\n<p>Last but not least by having this on an action third party code (plugins, child themes) can unhook the callback to e.g. replace it with something else.</p>\n\n<p>I hope this gives you a basic understanding why it is good practice to only do stuff on the appropriate hook.</p>\n\n<p>To close things this could also be relevant/interesting for you: <a href=\"https://wordpress.stackexchange.com/a/21579/47733\">https://wordpress.stackexchange.com/a/21579/47733</a></p>\n"
},
{
"answer_id": 260182,
"author": "forethought",
"author_id": 115386,
"author_profile": "https://wordpress.stackexchange.com/users/115386",
"pm_score": 0,
"selected": false,
"text": "<p>The short answer to your question is time. <code>wp_enqueue_scripts</code> makes sure that scripts are available when needed. </p>\n\n<blockquote>\n <p>wp_enqueue_scripts is the proper hook to use when enqueuing items that\n are meant to appear on the front end.</p>\n</blockquote>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260180",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3811/"
]
| When should you use `add_action` to enqueue or register a script, vs just using `wp_register_script` and/or `wp_enqueue_script`? In other words, both `example 1` and `example 2` below seem to accomplish the same thing when in `functions.php`, so why do so many resources say that `example 1` is the correct way of loading scripts in WP?
**Example 1:**
```
function my_assets() {
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
}
add_action( 'wp_enqueue_scripts', 'my_assets' );
```
**Example 2:**
```
wp_register_script( 'owl-carousel', get_stylesheet_directory_uri() . '/owl.carousel.js', array( 'jquery' ) );
wp_enqueue_script( 'owl-carousel' );
```
(yes, I know in example 2 you could skip registering the script and just enqueue it as necessary) | Well it works the same *in the case where you tested it*.
The answer could actually be somewhat complex, but mainly having it inside an action callback only registers them when needed, just putting it inside the `functions.php` it happens always when the theme is active.
First of all this can be a waste of performance, registering stuff that is never used. You might think that it should be there in any case, but actually in WP there are plenty of situations where frontend JS/CSS is totally irrelevant. The most obvious situation is the backend. But also some plugin might create an endpoint that doesn't need JS/CSS. And there are plenty more of that.
Last but not least by having this on an action third party code (plugins, child themes) can unhook the callback to e.g. replace it with something else.
I hope this gives you a basic understanding why it is good practice to only do stuff on the appropriate hook.
To close things this could also be relevant/interesting for you: <https://wordpress.stackexchange.com/a/21579/47733> |
260,199 | <p>Im using the following to access tables information from my Wordpress DB</p>
<pre><code> require_once(ABSPATH . 'wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($conn, DB_NAME);
</code></pre>
<p>It works fine I'm able to connect and display the information. The trouble is when I try to do the same thing from a plugin within the Dashboard under tools, I get the following message:</p>
<blockquote>
<p>Notice: Use of undefined constant ABSPATH - assumed 'ABSPATH' in
C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
on line 2</p>
<p>Warning: require_once(ABSPATHwp-config.php): failed to open stream: No
such file or directory in
C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
on line 2</p>
<p>Fatal error: require_once(): Failed opening required
'ABSPATHwp-config.php' (include_path='.;C:\xampp\php\PEAR') in
C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
on line 2</p>
</blockquote>
<p>I have checked my wp config and I do have the following</p>
<pre><code> /** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
</code></pre>
<p>Is there something I am missing with my implementation?</p>
<p>Thanks</p>
| [
{
"answer_id": 260241,
"author": "user1049961",
"author_id": 47664,
"author_profile": "https://wordpress.stackexchange.com/users/47664",
"pm_score": -1,
"selected": false,
"text": "<p>You are probably just missing the slash in the <code>require_once</code>. Change it to:</p>\n\n<pre><code>require_once(ABSPATH . '/wp-settings.php');\n</code></pre>\n"
},
{
"answer_id": 260271,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": true,
"text": "<p>I'm guessing this is a custom \"plugin\" where you are wanting to run a file externally that connects to the WordPress database, not really as a standard plugin which loads within WordPress environment, as in that case as @belinus says you can just use <code>$wpdb</code> class.</p>\n\n<p>Anyway, since <code>ABSPATH</code> is defined IN <code>wp-config.php</code>, you can't use <code>ABSPATH</code> to find and load <code>wp-config.php</code> - because it hasn't loaded and thus isn't defined yet. That's the flawed logic... hence the errors you are getting.</p>\n\n<p>If you know for certain that <code>wp-config.php</code> is in a directory above where the \"plugin\" file is, you can do something like this:</p>\n\n<pre><code>function find_require($file,$folder=null) {\n if ($folder === null) {$folder = dirname(__FILE__);}\n $path = $folder.'/'.$file;\n if (file_exists($path)) {require($path); return $folder;}\n else {\n $upfolder = find_require($file,dirname($folder));\n if ($upfolder != '') {return $upfolder;}\n }\n}\n$configpath = find_require('wp-config.php');\n</code></pre>\n\n<p>This will recursively search for <code>wp-config.php</code> above the plugin file directory and load it when it does. (Again this assumes the <code>wp-config.php</code> is located in a directory above the plugin file.)</p>\n"
}
]
| 2017/03/15 | [
"https://wordpress.stackexchange.com/questions/260199",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115478/"
]
| Im using the following to access tables information from my Wordpress DB
```
require_once(ABSPATH . 'wp-config.php');
$conn = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD);
mysqli_select_db($conn, DB_NAME);
```
It works fine I'm able to connect and display the information. The trouble is when I try to do the same thing from a plugin within the Dashboard under tools, I get the following message:
>
> Notice: Use of undefined constant ABSPATH - assumed 'ABSPATH' in
> C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
> on line 2
>
>
> Warning: require\_once(ABSPATHwp-config.php): failed to open stream: No
> such file or directory in
> C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
> on line 2
>
>
> Fatal error: require\_once(): Failed opening required
> 'ABSPATHwp-config.php' (include\_path='.;C:\xampp\php\PEAR') in
> C:\xampp\htdocs\wordpressexpensereport\wp-content\plugins\editdb\connection.php
> on line 2
>
>
>
I have checked my wp config and I do have the following
```
/** Absolute path to the WordPress directory. */
if ( !defined('ABSPATH') )
define('ABSPATH', dirname(__FILE__) . '/');
/** Sets up WordPress vars and included files. */
require_once(ABSPATH . 'wp-settings.php');
```
Is there something I am missing with my implementation?
Thanks | I'm guessing this is a custom "plugin" where you are wanting to run a file externally that connects to the WordPress database, not really as a standard plugin which loads within WordPress environment, as in that case as @belinus says you can just use `$wpdb` class.
Anyway, since `ABSPATH` is defined IN `wp-config.php`, you can't use `ABSPATH` to find and load `wp-config.php` - because it hasn't loaded and thus isn't defined yet. That's the flawed logic... hence the errors you are getting.
If you know for certain that `wp-config.php` is in a directory above where the "plugin" file is, you can do something like this:
```
function find_require($file,$folder=null) {
if ($folder === null) {$folder = dirname(__FILE__);}
$path = $folder.'/'.$file;
if (file_exists($path)) {require($path); return $folder;}
else {
$upfolder = find_require($file,dirname($folder));
if ($upfolder != '') {return $upfolder;}
}
}
$configpath = find_require('wp-config.php');
```
This will recursively search for `wp-config.php` above the plugin file directory and load it when it does. (Again this assumes the `wp-config.php` is located in a directory above the plugin file.) |
260,227 | <p>So I have this theme where there is an about section that is showing in the customizer, but there isn't a specific post type on the admin page that adds post to this section.</p>
<p>How do I add post to the about section with the template code stated below.</p>
<pre><code>if(isset($xt_corporate_lite_opt['xt_about_page']) &&
$xt_corporate_lite_opt['xt_about_page'] != '') {
$xt_query = new WP_Query(array(
'page_id' => $xt_corporate_lite_opt['xt_about_page']
));
if ($xt_query->have_posts()) {
while ($xt_query->have_posts()) {
$xt_query->the_post();
the_content();
}
}
wp_reset_postdata();
}
</code></pre>
| [
{
"answer_id": 260243,
"author": "1naveengiri",
"author_id": 114894,
"author_profile": "https://wordpress.stackexchange.com/users/114894",
"pm_score": 1,
"selected": false,
"text": "<p>You can try this code to show only post.</p>\n\n<pre><code>if(isset($xt_corporate_lite_opt['xt_about_page']) && $xt_corporate_lite_opt['xt_about_page'] != '') {\n $args = array( 'post_type' => 'post');\n $xt_query = new WP_Query($args);\n if ($xt_query->have_posts()) {\n while ($xt_query->have_posts()) {\n $xt_query->the_post();\n the_content();\n }\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>if you have any doubt in WP_Query.\nthen you could check this link in detail.</p>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a></p>\n"
},
{
"answer_id": 260245,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 0,
"selected": false,
"text": "<p>Assuming that your code snippet is running on a portion of the page, rather then being used to override the entire page content you'll want to change the WP_Query arguments.</p>\n\n<p>To show a list of posts on that page: <code>post_type => 'post'</code>\nTo show all posts on that page: <code>posts_per_page => -1</code>\nTo limit the number of posts on that page to 5: <code>posts_per_page => 5</code></p>\n\n<p>So that would look something like this:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post', // only show posts in this query\n 'posts_per_page' => 5, // only show 5 posts. Leave this blank to have the query results set by your website settings instead\n);\n</code></pre>\n\n<p>Also, make sure that your query ends with <code>wp_reset_query</code> to restore the $wp_query variable and all data back to the original query.</p>\n\n<p>So your full function would look something like this:</p>\n\n<pre><code>if(isset($xt_corporate_lite_opt['xt_about_page']) && $xt_corporate_lite_opt['xt_about_page'] != '') {\n $args = array( \n 'post_type' => 'post',\n // Any extra arguments you want here that WP_Query will take\n );\n $xt_query = new WP_Query($args);\n if ($xt_query->have_posts()) {\n while ($xt_query->have_posts()) {\n $xt_query->the_post();\n the_content();\n }\n wp_reset_query(); // put this right after the while loop or after you're sure you are done using those variables (like pagination)\n }\n}\n</code></pre>\n\n<p><code>wp_reset_postdata()</code> is similar to <code>wp_reset_query()</code> but will only restore the $post variable NOT the the full query. You could probably use either in this situation ;)</p>\n\n<p><strong>Helpful Documentation:</strong></p>\n\n<ol>\n<li>wp_reset_query: <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_reset_query</a></li>\n<li>wp_reset_postdata: <a href=\"https://codex.wordpress.org/Function_Reference/wp_reset_postdata\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_reset_postdata</a></li>\n<li>WP_Query: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a> (you probably have already looked at this a bit, but it's very handy to know everything you can get with WP_Query. It's a very very powerful tool!)</li>\n</ol>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260227",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115499/"
]
| So I have this theme where there is an about section that is showing in the customizer, but there isn't a specific post type on the admin page that adds post to this section.
How do I add post to the about section with the template code stated below.
```
if(isset($xt_corporate_lite_opt['xt_about_page']) &&
$xt_corporate_lite_opt['xt_about_page'] != '') {
$xt_query = new WP_Query(array(
'page_id' => $xt_corporate_lite_opt['xt_about_page']
));
if ($xt_query->have_posts()) {
while ($xt_query->have_posts()) {
$xt_query->the_post();
the_content();
}
}
wp_reset_postdata();
}
``` | You can try this code to show only post.
```
if(isset($xt_corporate_lite_opt['xt_about_page']) && $xt_corporate_lite_opt['xt_about_page'] != '') {
$args = array( 'post_type' => 'post');
$xt_query = new WP_Query($args);
if ($xt_query->have_posts()) {
while ($xt_query->have_posts()) {
$xt_query->the_post();
the_content();
}
}
wp_reset_postdata();
}
```
if you have any doubt in WP\_Query.
then you could check this link in detail.
<https://codex.wordpress.org/Class_Reference/WP_Query> |
260,236 | <p>Is there any way that I can log anything in WordPress similar to logs we can do it in Magento?</p>
<p>I am integrating a custom plugin in that I have added few functions with help of hooks, So I need to debug something in it. In this I need if I can enter any text or data into WordPress logs.</p>
<p>If so Please let me know the procedure for generating log into WordPress.</p>
| [
{
"answer_id": 260246,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress can do logging! Check out the WordPress debugging page here <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"noreferrer\">https://codex.wordpress.org/Debugging_in_WordPress</a></p>\n\n<p>I typically like to set my local development websites up to log errors in a debug file, rather than to have them output on the screen.</p>\n\n<p>Head over to to your wp_config file and scroll to the bottom where it defines WP_DEBUG.</p>\n\n<p>This is what my typical setup looks like:</p>\n\n<pre><code>define('WP_DEBUG', true); // To enable debugging. Leave things just like this to output errors, warnings, notices to the screen:\ndefine( 'WP_DEBUG_LOG', true ); // To turn on logging\ndefine( 'WP_DEBUG_DISPLAY', false ); // To prevent output of errors, warnings, notices to the screen (which I personally find SUPER annoying):\n</code></pre>\n\n<p>With those settings, WordPress will now log errors, warnings, and notices to a <code>debug.log</code> file located in <code>/wp-content/debug.log</code></p>\n\n<p>Log files in production environments are security threats so <strong>IF</strong> you decide to have logging on a production environment, it would be a good idea to set your .htaccess file to deny access to the log file (or similarly use a security plugin to block it). That way you still get your logs, but don't have to worry about hackers getting all that info as well.</p>\n"
},
{
"answer_id": 260309,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 7,
"selected": true,
"text": "<p>You can enable WordPress logging adding this to <code>wp-config.php</code>:</p>\n<pre><code> // Enable WP_DEBUG mode\ndefine( 'WP_DEBUG', true );\n\n// Enable Debug logging to the /wp-content/debug.log file\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n<p>you can write to the log file using the <a href=\"https://www.php.net/manual/en/function.error-log.php\" rel=\"noreferrer\"><code>error_log()</code> function</a> provided by PHP.</p>\n<p>The following code snippet is a very useful function wrapper for it, make it available in your plugin:</p>\n<pre><code>if (!function_exists('write_log')) {\n\n function write_log($log) {\n if (true === WP_DEBUG) {\n if (is_array($log) || is_object($log)) {\n error_log(print_r($log, true));\n } else {\n error_log($log);\n }\n }\n }\n\n}\n\nwrite_log('THIS IS THE START OF MY CUSTOM DEBUG');\n//i can log data like objects\nwrite_log($whatever_you_want_to_log);\n</code></pre>\n<p>if you cant find the <code>debug.log</code> file, try generating something for it, since it will not be created if there are no <code>errors</code>, also in some hosted servers you might need to check where the error log is located using php info.</p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260236",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/60922/"
]
| Is there any way that I can log anything in WordPress similar to logs we can do it in Magento?
I am integrating a custom plugin in that I have added few functions with help of hooks, So I need to debug something in it. In this I need if I can enter any text or data into WordPress logs.
If so Please let me know the procedure for generating log into WordPress. | You can enable WordPress logging adding this to `wp-config.php`:
```
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
```
you can write to the log file using the [`error_log()` function](https://www.php.net/manual/en/function.error-log.php) provided by PHP.
The following code snippet is a very useful function wrapper for it, make it available in your plugin:
```
if (!function_exists('write_log')) {
function write_log($log) {
if (true === WP_DEBUG) {
if (is_array($log) || is_object($log)) {
error_log(print_r($log, true));
} else {
error_log($log);
}
}
}
}
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
//i can log data like objects
write_log($whatever_you_want_to_log);
```
if you cant find the `debug.log` file, try generating something for it, since it will not be created if there are no `errors`, also in some hosted servers you might need to check where the error log is located using php info. |
260,249 | <p>I'm trying to write a plugin that adds a value from a meta box to a post on save_post. But I can't figure out how to get the value from the form field in the meta box This is the relevant code:</p>
<pre><code>function sw_add_document_meta_boxes() {
if (get_current_screen()->id == 'dokument') {
add_meta_box('access_level', 'Tilgangsnivå', 'sw_ac_meta_box');
}
}
function sw_ac_meta_box() {
$html = '<p class="description">';
$html .= 'Velg laveste tilgangsnivå';
$html .= '</p>';
$html .= '<select name="access_level" id="access_level">';
$html .= '<option value="4">Ansatt</option>';
$html .= '<option value="3">Fagansvarlig</option>';
$html .= '<option value="2">Daglig leder</option>';
$html .= '<option value="1">Superbruker</option>';
$html .= '</select>';
echo $html;
}
function sw_ac_set_access_level($id) {
$meta_value =
add_post_meta($id, 'access_level', $meta_value, true);
}
add_action('add_meta_boxes', 'sw_add_document_meta_boxes');
add_action('save_post', 'sw_ac_set_access_level');
</code></pre>
<p>I guess my question is, what should I write on the line '$meta_value =' in the 'sw_ac_set_access_level()' function? Take into account that I'm a total wordpress noob, so I might be on the wrong track entirely.</p>
| [
{
"answer_id": 260246,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 3,
"selected": false,
"text": "<p>WordPress can do logging! Check out the WordPress debugging page here <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"noreferrer\">https://codex.wordpress.org/Debugging_in_WordPress</a></p>\n\n<p>I typically like to set my local development websites up to log errors in a debug file, rather than to have them output on the screen.</p>\n\n<p>Head over to to your wp_config file and scroll to the bottom where it defines WP_DEBUG.</p>\n\n<p>This is what my typical setup looks like:</p>\n\n<pre><code>define('WP_DEBUG', true); // To enable debugging. Leave things just like this to output errors, warnings, notices to the screen:\ndefine( 'WP_DEBUG_LOG', true ); // To turn on logging\ndefine( 'WP_DEBUG_DISPLAY', false ); // To prevent output of errors, warnings, notices to the screen (which I personally find SUPER annoying):\n</code></pre>\n\n<p>With those settings, WordPress will now log errors, warnings, and notices to a <code>debug.log</code> file located in <code>/wp-content/debug.log</code></p>\n\n<p>Log files in production environments are security threats so <strong>IF</strong> you decide to have logging on a production environment, it would be a good idea to set your .htaccess file to deny access to the log file (or similarly use a security plugin to block it). That way you still get your logs, but don't have to worry about hackers getting all that info as well.</p>\n"
},
{
"answer_id": 260309,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 7,
"selected": true,
"text": "<p>You can enable WordPress logging adding this to <code>wp-config.php</code>:</p>\n<pre><code> // Enable WP_DEBUG mode\ndefine( 'WP_DEBUG', true );\n\n// Enable Debug logging to the /wp-content/debug.log file\ndefine( 'WP_DEBUG_LOG', true );\n</code></pre>\n<p>you can write to the log file using the <a href=\"https://www.php.net/manual/en/function.error-log.php\" rel=\"noreferrer\"><code>error_log()</code> function</a> provided by PHP.</p>\n<p>The following code snippet is a very useful function wrapper for it, make it available in your plugin:</p>\n<pre><code>if (!function_exists('write_log')) {\n\n function write_log($log) {\n if (true === WP_DEBUG) {\n if (is_array($log) || is_object($log)) {\n error_log(print_r($log, true));\n } else {\n error_log($log);\n }\n }\n }\n\n}\n\nwrite_log('THIS IS THE START OF MY CUSTOM DEBUG');\n//i can log data like objects\nwrite_log($whatever_you_want_to_log);\n</code></pre>\n<p>if you cant find the <code>debug.log</code> file, try generating something for it, since it will not be created if there are no <code>errors</code>, also in some hosted servers you might need to check where the error log is located using php info.</p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260249",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115521/"
]
| I'm trying to write a plugin that adds a value from a meta box to a post on save\_post. But I can't figure out how to get the value from the form field in the meta box This is the relevant code:
```
function sw_add_document_meta_boxes() {
if (get_current_screen()->id == 'dokument') {
add_meta_box('access_level', 'Tilgangsnivå', 'sw_ac_meta_box');
}
}
function sw_ac_meta_box() {
$html = '<p class="description">';
$html .= 'Velg laveste tilgangsnivå';
$html .= '</p>';
$html .= '<select name="access_level" id="access_level">';
$html .= '<option value="4">Ansatt</option>';
$html .= '<option value="3">Fagansvarlig</option>';
$html .= '<option value="2">Daglig leder</option>';
$html .= '<option value="1">Superbruker</option>';
$html .= '</select>';
echo $html;
}
function sw_ac_set_access_level($id) {
$meta_value =
add_post_meta($id, 'access_level', $meta_value, true);
}
add_action('add_meta_boxes', 'sw_add_document_meta_boxes');
add_action('save_post', 'sw_ac_set_access_level');
```
I guess my question is, what should I write on the line '$meta\_value =' in the 'sw\_ac\_set\_access\_level()' function? Take into account that I'm a total wordpress noob, so I might be on the wrong track entirely. | You can enable WordPress logging adding this to `wp-config.php`:
```
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
```
you can write to the log file using the [`error_log()` function](https://www.php.net/manual/en/function.error-log.php) provided by PHP.
The following code snippet is a very useful function wrapper for it, make it available in your plugin:
```
if (!function_exists('write_log')) {
function write_log($log) {
if (true === WP_DEBUG) {
if (is_array($log) || is_object($log)) {
error_log(print_r($log, true));
} else {
error_log($log);
}
}
}
}
write_log('THIS IS THE START OF MY CUSTOM DEBUG');
//i can log data like objects
write_log($whatever_you_want_to_log);
```
if you cant find the `debug.log` file, try generating something for it, since it will not be created if there are no `errors`, also in some hosted servers you might need to check where the error log is located using php info. |
260,284 | <p>My Server Env for a wordpress site is as follows:</p>
<pre><code>---------- --------- -------------
| Client | <-- HTTPS --> | Proxy | <-- HTTP --> | Wordpress |
---------- --------- -------------
</code></pre>
<p>The Problem is that the Wordpress Site itself is served internally over HTTP but the Client communicates over HTTPS with the Proxy. Since Wordpress is configured with HTTP it returns links and images-src with "http://" which leads to <code>mixed-content</code> errors in the browsers. (Eg. all css / script links generated by wp_head() return http:// urls)</p>
<p>Can i configure Wordpress to generate only "https://" urls, even if it's serverd over HTTP?</p>
<p>Wordpress runs on nginx webserver<br>
The Proxy is also nginx </p>
| [
{
"answer_id": 260293,
"author": "hcheung",
"author_id": 111577,
"author_profile": "https://wordpress.stackexchange.com/users/111577",
"pm_score": 3,
"selected": true,
"text": "<p>Please take a look at <a href=\"https://wordpress.org/support/article/administration-over-ssl/\" rel=\"nofollow noreferrer\">Administation Over SSL</a>, particularly the \"Using a Reverse Proxy\" section. </p>\n"
},
{
"answer_id": 260299,
"author": "Industrial Themes",
"author_id": 274,
"author_profile": "https://wordpress.stackexchange.com/users/274",
"pm_score": 1,
"selected": false,
"text": "<p>What about using a Force SSL plugin like <a href=\"https://wordpress.org/plugins/wp-force-ssl/\" rel=\"nofollow noreferrer\">this one</a>?</p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86177/"
]
| My Server Env for a wordpress site is as follows:
```
---------- --------- -------------
| Client | <-- HTTPS --> | Proxy | <-- HTTP --> | Wordpress |
---------- --------- -------------
```
The Problem is that the Wordpress Site itself is served internally over HTTP but the Client communicates over HTTPS with the Proxy. Since Wordpress is configured with HTTP it returns links and images-src with "http://" which leads to `mixed-content` errors in the browsers. (Eg. all css / script links generated by wp\_head() return http:// urls)
Can i configure Wordpress to generate only "https://" urls, even if it's serverd over HTTP?
Wordpress runs on nginx webserver
The Proxy is also nginx | Please take a look at [Administation Over SSL](https://wordpress.org/support/article/administration-over-ssl/), particularly the "Using a Reverse Proxy" section. |
260,311 | <p>I'm new to Wordpress theme development. I'd like to make a simple Testimonial page that a non-technical user can add more testimonial later. Here's the example of the page:
<a href="http://heartyjuice.com.au/testimonials/" rel="nofollow noreferrer">Testimonials page</a></p>
<p>I'd like to have a admin screen where user input the name, upload the picture, and the testimonial detail. After that the testimonial item can be add to the page.</p>
<p>Please show me how to approach this. What is the right direction to go about this?</p>
| [
{
"answer_id": 260316,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 2,
"selected": true,
"text": "<p>I would suggest a custom post type for your Testimonials. Each will be created as an individual post and you will have the ability to query, sort, categorize, your testimonials just as you can with blog posts, or any other post type. Non-technical site admins can simply \"add new testimonial\" and edit existing, etc, just as if they were working with pages, blog posts, etc</p>\n\n<p>You must register your <code>testimonial</code> post type for that to happen. An extremely simple example. You will want to define many more of the optional parameters than this example:</p>\n\n<pre><code>function wpse_register_post_types() {\n$args = array(\n 'public' => true,\n 'label' => 'Testimonials'\n);\nregister_post_type( 'testimonial', $args );\n}\n\nadd_action( 'init', 'wpse_register_post_types' );\n</code></pre>\n\n<p>Full WP Codex documentation here:\n<a href=\"https://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/register_post_type</a></p>\n\n<p>This is an extremely simplified example to show the basics: create a function to handle registration, hook that function to WP's <code>init</code> action.</p>\n\n<p>In a real application you will want to define your labels and other arguments for the <code>register_post_type()</code> function.</p>\n\n<p>Depending on how you intend to use the testimonials on the front end, you will need templates for your new custom post type:</p>\n\n<p><code>archive-testimonial.php</code> <-- this will display all of the published testimonials; your example page\n<code>single-testimonial.php</code> <-- used to display a single testimonial; when a user clicks through to see all of the details on a single testimonial</p>\n\n<p>This will get you started. For advanced features, like displaying random testimonials on a page, you'll want to read up on using the <code>WP_Query</code> class for custom queries.</p>\n\n<p>Welcome to WPSE!</p>\n"
},
{
"answer_id": 260327,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>You could also consider enabling comments. Whether the admin user inputs them or customers input them directly, as long as they're moderating comments, new ones wouldn't show up until an admin had approved them. This would restrict the testimonials to only appear on the page where the comments are added, but would be simpler code-wise. Depends on whether they may want to feature testimonials in other areas later.</p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260311",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115555/"
]
| I'm new to Wordpress theme development. I'd like to make a simple Testimonial page that a non-technical user can add more testimonial later. Here's the example of the page:
[Testimonials page](http://heartyjuice.com.au/testimonials/)
I'd like to have a admin screen where user input the name, upload the picture, and the testimonial detail. After that the testimonial item can be add to the page.
Please show me how to approach this. What is the right direction to go about this? | I would suggest a custom post type for your Testimonials. Each will be created as an individual post and you will have the ability to query, sort, categorize, your testimonials just as you can with blog posts, or any other post type. Non-technical site admins can simply "add new testimonial" and edit existing, etc, just as if they were working with pages, blog posts, etc
You must register your `testimonial` post type for that to happen. An extremely simple example. You will want to define many more of the optional parameters than this example:
```
function wpse_register_post_types() {
$args = array(
'public' => true,
'label' => 'Testimonials'
);
register_post_type( 'testimonial', $args );
}
add_action( 'init', 'wpse_register_post_types' );
```
Full WP Codex documentation here:
<https://codex.wordpress.org/Function_Reference/register_post_type>
This is an extremely simplified example to show the basics: create a function to handle registration, hook that function to WP's `init` action.
In a real application you will want to define your labels and other arguments for the `register_post_type()` function.
Depending on how you intend to use the testimonials on the front end, you will need templates for your new custom post type:
`archive-testimonial.php` <-- this will display all of the published testimonials; your example page
`single-testimonial.php` <-- used to display a single testimonial; when a user clicks through to see all of the details on a single testimonial
This will get you started. For advanced features, like displaying random testimonials on a page, you'll want to read up on using the `WP_Query` class for custom queries.
Welcome to WPSE! |
260,315 | <p>I am trying to clean up a DB of 4000+ posts and the editors TAGGED the posts that they want to keep with an "audit2017" tag. Is there a way with SQL to select all posts *without this tag and delete them?</p>
<p>I am not very experienced with SQL but can manage this if I had the right query.</p>
<p>Any help appreciated, thanks!</p>
| [
{
"answer_id": 260383,
"author": "Mihai Apetrei",
"author_id": 115589,
"author_profile": "https://wordpress.stackexchange.com/users/115589",
"pm_score": 0,
"selected": false,
"text": "<p>Was looking into this to help you come with a solution. I'm not able to find one for the sql panel, but I guess you could first get all the posts that do not have that tag id (as shown here <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Class_Reference/WP_Query</a>):</p>\n\n<p><code>$query = new WP_Query( array( 'tag__not_in' => array( 37, 47 ) ) );</code></p>\n\n<p>And then delete them using some php:<br/></p>\n\n<ul>\n<li><code>https://developer.wordpress.org/reference/functions/wp_delete_post/</code></li>\n<li>another example:\n<code>http://wordpress.stackexchange.com/questions/48214/manually-delete-post-from-database</code></li>\n</ul>\n\n<p>This plugin was perfect if the client was doing the exact opposite, adding a specific tag to all the posts he DOESN'T WANT to keep: <a href=\"https://wordpress.org/plugins/bulk-delete/\" rel=\"nofollow noreferrer\">https://wordpress.org/plugins/bulk-delete/</a></p>\n\n<p>Hope this info is helpful.</p>\n"
},
{
"answer_id": 370066,
"author": "Raham",
"author_id": 190855,
"author_profile": "https://wordpress.stackexchange.com/users/190855",
"pm_score": 1,
"selected": false,
"text": "<p>I just created a function that can bulk delete posts that doesn't have specific tag(s).</p>\n<p>You need to have the IDs of the tags that you want to keep their posts.\n[In case you don't know how to get those IDs: Quick solution is go to tags page on the website admin panel. Click on the tag. In the new page address bar you can see the tag_id]</p>\n<p>Replace the "TagID"s with your actual tag IDs on this line:</p>\n<pre><code>$tags_to_delete = array( $TagID1, $TagID2 , ... );\n</code></pre>\n<p>Then place the code at the end of your theme's functions.php file. Open your homepage. It will move all the posts that don't have specific tag(s) to trash.</p>\n<p>This code will be run every time that you open a page in your frontend.</p>\n<p>The runtime depends on you number of post and your server configuration.\nI tested it for about 3500 posts on a not very high config server and it took about 40 seconds to finish.</p>\n<p>I strongly suggest to remove the code from your website after you are done with it.</p>\n<pre><code>// Change the $TagIDs with the tag IDs in your database\n$tags_to_delete = array( $TagID1, $TagID2 , ... );\n\n// This function will bulk delete posts that don't have specific tag(s)\nfunction delete_posts_by_not_tag( $tags ) {\n\n// WP_Query arguments\n$args = array(\n 'post_type' => array( 'post' ),\n 'nopaging' => true,\n 'posts_per_page' => '-1',\n 'tag__not_in' => array( $tags ),\n);\n\n// The Query\n$query = new WP_Query( $args );\n\n// The Loop\nif ( $query->have_posts() ) {\n\n $totalpost = $query->found_posts;\n echo "Number of Posts: " . $totalpost;\n\n echo "<hr>";\n\n while ( $query->have_posts() ) {\n $query->the_post();\n\n $current_id = $post->ID;\n wp_delete_post( $current_id );\n echo "Post by ID '" . $current_id . "' is deleted.<br>";\n }\n\n echo "<hr>";\n\n} else {\n\n echo "No post found to delete!";\n\n}\n\n// Restore original Post Data\nwp_reset_postdata();\n\n}\n\n// Run the function to delete all the posts that don't have specific tag(s)\ndelete_posts_by_not_tag( $tags_to_delete );\n\n\n \n</code></pre>\n"
},
{
"answer_id": 404514,
"author": "Laban Johnson",
"author_id": 221006,
"author_profile": "https://wordpress.stackexchange.com/users/221006",
"pm_score": 0,
"selected": false,
"text": "<p>If you only need to run something once, or occasionally, instead of a plugin you can also create another php file you can run it from on the side without impacting your site's speed.</p>\n<p>Just</p>\n<p>require_once('wp-load.php');\nglobal $wpdb;</p>\n<p>Then you can do whatever you want or need, using $wpdb</p>\n<p>Load it from your browser to run it. If you want the look and feel of your site you can:</p>\n<p>get_header();\n{ your code here }\nget_footer();</p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260315",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115559/"
]
| I am trying to clean up a DB of 4000+ posts and the editors TAGGED the posts that they want to keep with an "audit2017" tag. Is there a way with SQL to select all posts \*without this tag and delete them?
I am not very experienced with SQL but can manage this if I had the right query.
Any help appreciated, thanks! | I just created a function that can bulk delete posts that doesn't have specific tag(s).
You need to have the IDs of the tags that you want to keep their posts.
[In case you don't know how to get those IDs: Quick solution is go to tags page on the website admin panel. Click on the tag. In the new page address bar you can see the tag\_id]
Replace the "TagID"s with your actual tag IDs on this line:
```
$tags_to_delete = array( $TagID1, $TagID2 , ... );
```
Then place the code at the end of your theme's functions.php file. Open your homepage. It will move all the posts that don't have specific tag(s) to trash.
This code will be run every time that you open a page in your frontend.
The runtime depends on you number of post and your server configuration.
I tested it for about 3500 posts on a not very high config server and it took about 40 seconds to finish.
I strongly suggest to remove the code from your website after you are done with it.
```
// Change the $TagIDs with the tag IDs in your database
$tags_to_delete = array( $TagID1, $TagID2 , ... );
// This function will bulk delete posts that don't have specific tag(s)
function delete_posts_by_not_tag( $tags ) {
// WP_Query arguments
$args = array(
'post_type' => array( 'post' ),
'nopaging' => true,
'posts_per_page' => '-1',
'tag__not_in' => array( $tags ),
);
// The Query
$query = new WP_Query( $args );
// The Loop
if ( $query->have_posts() ) {
$totalpost = $query->found_posts;
echo "Number of Posts: " . $totalpost;
echo "<hr>";
while ( $query->have_posts() ) {
$query->the_post();
$current_id = $post->ID;
wp_delete_post( $current_id );
echo "Post by ID '" . $current_id . "' is deleted.<br>";
}
echo "<hr>";
} else {
echo "No post found to delete!";
}
// Restore original Post Data
wp_reset_postdata();
}
// Run the function to delete all the posts that don't have specific tag(s)
delete_posts_by_not_tag( $tags_to_delete );
``` |
260,359 | <p>I'm having a heck of a time with this! I'm trying to force this page to only show a limited amount of words regardless if they insert a readmore tag.</p>
<p>I was going to use the_excerpt, but it doesn't add a readmore link at the end of the excerpt.</p>
<p>I have my index page pulling my blog roll by using this code:</p>
<pre><code><div class="entry-content">
<?php
/* translators: %s: Name of current post */
the_content( sprintf(
__( 'more %s <span class="meta-nav">...</span>', 'gateway' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
?>
</div>
</code></pre>
<p>In my reading settings I have set "For each article in a feed, show" to "summary".</p>
<p>So I guess my question is this: Is there a away to limit the_content() or alternatively add a read more to the_excerpt()?</p>
| [
{
"answer_id": 260361,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>Try <code>wp_trim_words()</code> <a href=\"https://codex.wordpress.org/Function_Reference/wp_trim_words\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/wp_trim_words</a></p>\n\n<p>You won't be able to use it with <code>the_content()</code> though because it echoes the content. You'll want to use it with <code>get_the_content()</code> which just returns the info.</p>\n\n<p>So it'd look something like this</p>\n\n<pre><code>echo wp_trim_words( get_the_content(), $num_words, $more_text );\n</code></pre>\n\n<p><strong>Edit:</strong></p>\n\n<p>It's good to note that <code>the_content</code> and <code>get_the_content</code> will return/echo any HTML that is in your content, while <code>the_excerpt</code> or <code>get_the_excerpt</code> will return only the text. So use the one that best fits your needs on how many words you want to return and whether or not you care to include HTML (such as images or embeded videos) in your output.</p>\n"
},
{
"answer_id": 260563,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 1,
"selected": true,
"text": "<p>I couldn't get this resolved with the_content() so i went simple and this works:</p>\n\n<pre><code> the_excerpt();\n echo '<a href=\"' . esc_url( get_the_permalink() ) . '\"> more...</a>';\n</code></pre>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260359",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77767/"
]
| I'm having a heck of a time with this! I'm trying to force this page to only show a limited amount of words regardless if they insert a readmore tag.
I was going to use the\_excerpt, but it doesn't add a readmore link at the end of the excerpt.
I have my index page pulling my blog roll by using this code:
```
<div class="entry-content">
<?php
/* translators: %s: Name of current post */
the_content( sprintf(
__( 'more %s <span class="meta-nav">...</span>', 'gateway' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
?>
</div>
```
In my reading settings I have set "For each article in a feed, show" to "summary".
So I guess my question is this: Is there a away to limit the\_content() or alternatively add a read more to the\_excerpt()? | I couldn't get this resolved with the\_content() so i went simple and this works:
```
the_excerpt();
echo '<a href="' . esc_url( get_the_permalink() ) . '"> more...</a>';
``` |
260,371 | <p>I have made a child theme of a themify theme. I used thier example on enqueuing as well as my own. In both cases the child css is loaded after the parent. </p>
<p>Loaded on Line <code>53</code></p>
<pre><code><link rel='stylesheet' id='parent-style-css' href='https://example.com/wp-content/themes/themify-ultra/style.css?ver=4.7.3' type='text/css' media='all' />
</code></pre>
<p>Loaded on Line <code>69</code></p>
<pre><code><link rel='stylesheet' id='theme-style-css' href='https://example.com/wp-content/themes/Ultra-Child/style.css?ver=1.0.0' type='text/css' media='all' />
</code></pre>
<p>However the elements in the line 53 file override the 69 file. I have tried a few things that have changed positions and one that even loads the same child stylesheet twice. The earlier stylesheet caches and overrides unless I change the version number. It still overrides but will update if I change the version. Exact same elements in both files, one change, no <code>!important</code>. Why is the first one overriding the second?</p>
<p>This is the entire Child functions.php:</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', PHP_INT_MAX);
function theme_enqueue_styles() {
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css' );
}
// Queue parent style followed by child/customized style
add_action( 'wp_enqueue_scripts', 'theme_enqueue_parent_styles', 9);
function theme_enqueue_parent_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
</code></pre>
| [
{
"answer_id": 260390,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>I looked at my child theme's functions.php and I found that I had commented out the line to enqueue the child style.css. I'm guessing that the stylesheet is loaded automatically because that is the active theme. I would suggest you try not explicitly loading your child theme's stylesheet and see if that helps.</p>\n\n<p>P.S. Only include the styles in your child stylesheet that need to be overridden. In other words, at this point, you should only have styles for h1, h2, h3, et al.</p>\n"
},
{
"answer_id": 260616,
"author": "JpaytonWPD",
"author_id": 70863,
"author_profile": "https://wordpress.stackexchange.com/users/70863",
"pm_score": 1,
"selected": true,
"text": "<p>Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS. </p>\n\n<p>Chromes console still showed it as the remote CSS file even though it was inlined. </p>\n\n<p>Disabling the built in minification fixed the issue. </p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260371",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
]
| I have made a child theme of a themify theme. I used thier example on enqueuing as well as my own. In both cases the child css is loaded after the parent.
Loaded on Line `53`
```
<link rel='stylesheet' id='parent-style-css' href='https://example.com/wp-content/themes/themify-ultra/style.css?ver=4.7.3' type='text/css' media='all' />
```
Loaded on Line `69`
```
<link rel='stylesheet' id='theme-style-css' href='https://example.com/wp-content/themes/Ultra-Child/style.css?ver=1.0.0' type='text/css' media='all' />
```
However the elements in the line 53 file override the 69 file. I have tried a few things that have changed positions and one that even loads the same child stylesheet twice. The earlier stylesheet caches and overrides unless I change the version number. It still overrides but will update if I change the version. Exact same elements in both files, one change, no `!important`. Why is the first one overriding the second?
This is the entire Child functions.php:
```
add_action( 'wp_enqueue_scripts', 'theme_enqueue_styles', PHP_INT_MAX);
function theme_enqueue_styles() {
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css' );
}
// Queue parent style followed by child/customized style
add_action( 'wp_enqueue_scripts', 'theme_enqueue_parent_styles', 9);
function theme_enqueue_parent_styles() {
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
}
``` | Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS.
Chromes console still showed it as the remote CSS file even though it was inlined.
Disabling the built in minification fixed the issue. |
260,373 | <p>I'm using twentyseventeen theme as base to design my own, but when i use wp_nav_menu to print menus, it adds some unwanted svg elements which break my design. Elements are like:</p>
<pre><code><svg class="icon icon-angle-down" aria-hidden="true" role="img">
<use href="#icon-angle-down" xlink:href="#icon-angle-down"></use> </svg>
</code></pre>
<p>How can i disable this?</p>
| [
{
"answer_id": 260390,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>I looked at my child theme's functions.php and I found that I had commented out the line to enqueue the child style.css. I'm guessing that the stylesheet is loaded automatically because that is the active theme. I would suggest you try not explicitly loading your child theme's stylesheet and see if that helps.</p>\n\n<p>P.S. Only include the styles in your child stylesheet that need to be overridden. In other words, at this point, you should only have styles for h1, h2, h3, et al.</p>\n"
},
{
"answer_id": 260616,
"author": "JpaytonWPD",
"author_id": 70863,
"author_profile": "https://wordpress.stackexchange.com/users/70863",
"pm_score": 1,
"selected": true,
"text": "<p>Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS. </p>\n\n<p>Chromes console still showed it as the remote CSS file even though it was inlined. </p>\n\n<p>Disabling the built in minification fixed the issue. </p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260373",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115587/"
]
| I'm using twentyseventeen theme as base to design my own, but when i use wp\_nav\_menu to print menus, it adds some unwanted svg elements which break my design. Elements are like:
```
<svg class="icon icon-angle-down" aria-hidden="true" role="img">
<use href="#icon-angle-down" xlink:href="#icon-angle-down"></use> </svg>
```
How can i disable this? | Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS.
Chromes console still showed it as the remote CSS file even though it was inlined.
Disabling the built in minification fixed the issue. |
260,375 | <p>Im working with custom post types - named 'Products'</p>
<p>I have multiple taxonomies registered - 'Category' and 'Dosage'</p>
<p>And I'm trying to setup pages that only display custom post types 'products' IF taxonomy Category='injectors' AND Dosage='1ml, 2ml, 5ml' </p>
<p>I hope that makes sense - manage to get custom post archives working fine for a single taxonomy, but not sure about filtering by multiple.</p>
<p>Cheers,</p>
<p>This is the code i'm trying to get work but it doesn't</p>
<pre><code><?php
$myquery['tax_query'] = array(
'relation' => 'OR',
array(
'taxonomy' => 'product_category',
'terms' => array('shrouded'),
'field' => 'slug',
),
array(
'taxonomy' => 'dosages',
'terms' => array( '1ml' ),
'field' => 'slug',
),
);
query_posts($myquery); ?>
</code></pre>
| [
{
"answer_id": 260390,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 1,
"selected": false,
"text": "<p>I looked at my child theme's functions.php and I found that I had commented out the line to enqueue the child style.css. I'm guessing that the stylesheet is loaded automatically because that is the active theme. I would suggest you try not explicitly loading your child theme's stylesheet and see if that helps.</p>\n\n<p>P.S. Only include the styles in your child stylesheet that need to be overridden. In other words, at this point, you should only have styles for h1, h2, h3, et al.</p>\n"
},
{
"answer_id": 260616,
"author": "JpaytonWPD",
"author_id": 70863,
"author_profile": "https://wordpress.stackexchange.com/users/70863",
"pm_score": 1,
"selected": true,
"text": "<p>Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS. </p>\n\n<p>Chromes console still showed it as the remote CSS file even though it was inlined. </p>\n\n<p>Disabling the built in minification fixed the issue. </p>\n"
}
]
| 2017/03/16 | [
"https://wordpress.stackexchange.com/questions/260375",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115588/"
]
| Im working with custom post types - named 'Products'
I have multiple taxonomies registered - 'Category' and 'Dosage'
And I'm trying to setup pages that only display custom post types 'products' IF taxonomy Category='injectors' AND Dosage='1ml, 2ml, 5ml'
I hope that makes sense - manage to get custom post archives working fine for a single taxonomy, but not sure about filtering by multiple.
Cheers,
This is the code i'm trying to get work but it doesn't
```
<?php
$myquery['tax_query'] = array(
'relation' => 'OR',
array(
'taxonomy' => 'product_category',
'terms' => array('shrouded'),
'field' => 'slug',
),
array(
'taxonomy' => 'dosages',
'terms' => array( '1ml' ),
'field' => 'slug',
),
);
query_posts($myquery); ?>
``` | Themifies built in minification was inlining the parent CSS after the child. Which is why I could not find it, I was not looking for inline CSS.
Chromes console still showed it as the remote CSS file even though it was inlined.
Disabling the built in minification fixed the issue. |
260,399 | <p>I´m building a child theme for a parent theme that loads in its functions.php <strong>all</strong> its scripts in a single minified JS file. And it does so before the closing body tag by setting the last parameter of <code>wp_enqueue_script()</code> to "true"</p>
<p>However, note that this <strong>single file</strong> includes several libraries before the developer´s code shows up at the very bottom. So, by scrolling down the file, you´d get: jQuery, Parsley, Slick, Select2 and, finally, developer´s code. </p>
<p>Like I said, <strong>all in the same file</strong>, one after the other, resulting in a BIG file (242kb minified, over 20K lines of code).</p>
<p>So, when creating my custom jQuery scripts in my child theme, I´m able to load them on the page, but none of my scripts work. Console shows "Uncaught ReferenceError: $ is not defined" which, I assume, indicates that jQuery is not installed... </p>
<p>But jQuery IS in that single minified file I mentioned before. And my theme uses jQuery... So I´m puzzled. Why is it not working?</p>
<p>I suspect this has something to do with this approach made by the parent theme´s developer, where he did not install jQuery like you normally would. Overriding the original file by copying it entirely only to include a few simple lines seems not the way to go... any thoughts on how to solve this?</p>
<p>I´m loading my script in my child theme´s function.php like this:</p>
<pre><code>define( 'BLK_BOX_VERSION', '1.0.0' );
define( 'BLK_BOX_TEMPLATE_URI', get_stylesheet_directory_uri() );
define( 'BLK_BOX_THEME_SLUG', 'black-box' );
if ( ! function_exists( 'headerNavBar_script' ) ) :
function headerNavBar_script() {
wp_enqueue_script( BLK_BOX_THEME_SLUG . '-scripts', BLK_BOX_TEMPLATE_URI . '/static/dist/scripts/navbar-scroll.js', array(), BLK_BOX_VERSION, true );
}
endif;
add_action( 'wp_enqueue_scripts', 'headerNavBar_script' );
</code></pre>
| [
{
"answer_id": 260400,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>WordPress loads jQuery in noconflict mode. Therefore, but default, you cannot use $(). You can fix this one of two ways.</p>\n\n<p>1) Change <code>$()</code> to <code>jQuery()</code> in your script.</p>\n\n<p>2) Wrap all your jQuery in an anonymous function as follows:</p>\n\n<pre><code>(function($) {\n // Your Code Here\n})(jQuery)\n</code></pre>\n\n<p>Note: Option 2 only works if you're not loading scripts in the header. If you do there's some slight stuff you need to do to make it work.</p>\n\n<p>I would remove your copy of jQuery in your minified script and just let WordPress handle loading it.</p>\n"
},
{
"answer_id": 260403,
"author": "Diogo",
"author_id": 115596,
"author_profile": "https://wordpress.stackexchange.com/users/115596",
"pm_score": 0,
"selected": false,
"text": "<p>Finally got it to work!</p>\n\n<p>In addition to wrapping my jQuery in an anonymous function, like belinus kindly suggested, I needed to add <code>wp_enqueue_script('jquery');</code>right before enqueuing my script.</p>\n\n<p>This was an answer provided by Gavin Simpson at Stack Overflow:\n<a href=\"https://stackoverflow.com/questions/28248113/jquery-is-not-defined-in-wordpress-but-my-script-is-enqueued-properly\">https://stackoverflow.com/questions/28248113/jquery-is-not-defined-in-wordpress-but-my-script-is-enqueued-properly</a></p>\n\n<p>It worked!</p>\n"
},
{
"answer_id": 302867,
"author": "Keshav Kalra",
"author_id": 48303,
"author_profile": "https://wordpress.stackexchange.com/users/48303",
"pm_score": 1,
"selected": false,
"text": "<p>change all $ to jQuery and enque script this way so your script will load after loading jQuery and since wordpress do use prototype so we cannt use $ user jQuery </p>\n\n<pre><code>wp_enqueue_script('name_of_script','path',array('jquery'));\n</code></pre>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115596/"
]
| I´m building a child theme for a parent theme that loads in its functions.php **all** its scripts in a single minified JS file. And it does so before the closing body tag by setting the last parameter of `wp_enqueue_script()` to "true"
However, note that this **single file** includes several libraries before the developer´s code shows up at the very bottom. So, by scrolling down the file, you´d get: jQuery, Parsley, Slick, Select2 and, finally, developer´s code.
Like I said, **all in the same file**, one after the other, resulting in a BIG file (242kb minified, over 20K lines of code).
So, when creating my custom jQuery scripts in my child theme, I´m able to load them on the page, but none of my scripts work. Console shows "Uncaught ReferenceError: $ is not defined" which, I assume, indicates that jQuery is not installed...
But jQuery IS in that single minified file I mentioned before. And my theme uses jQuery... So I´m puzzled. Why is it not working?
I suspect this has something to do with this approach made by the parent theme´s developer, where he did not install jQuery like you normally would. Overriding the original file by copying it entirely only to include a few simple lines seems not the way to go... any thoughts on how to solve this?
I´m loading my script in my child theme´s function.php like this:
```
define( 'BLK_BOX_VERSION', '1.0.0' );
define( 'BLK_BOX_TEMPLATE_URI', get_stylesheet_directory_uri() );
define( 'BLK_BOX_THEME_SLUG', 'black-box' );
if ( ! function_exists( 'headerNavBar_script' ) ) :
function headerNavBar_script() {
wp_enqueue_script( BLK_BOX_THEME_SLUG . '-scripts', BLK_BOX_TEMPLATE_URI . '/static/dist/scripts/navbar-scroll.js', array(), BLK_BOX_VERSION, true );
}
endif;
add_action( 'wp_enqueue_scripts', 'headerNavBar_script' );
``` | change all $ to jQuery and enque script this way so your script will load after loading jQuery and since wordpress do use prototype so we cannt use $ user jQuery
```
wp_enqueue_script('name_of_script','path',array('jquery'));
``` |
260,410 | <p>I am creating a custom admin section. I have the following code:</p>
<pre><code>// Top level menu
add_menu_page('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
// Details: https://wordpress.stackexchange.com/questions/66498/add-menu-page-with-different-name-for-first-submenu-item
add_submenu_page('Books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page');
// The Add Book menu page
add_submenu_page('Books', 'Add New Book', 'Add Book', 'publish_posts', 'add-book', 'render_add_book_page');
// The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)
add_submenu_page(null, 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page');
</code></pre>
<p>As you notice in the last line of code, the first parameter of the <code>add_submenu_page()</code> is set to <code>null</code>. This is to ensure that the <strong>Edit Book</strong> page is hidden (<a href="https://wordpress.stackexchange.com/questions/73622/add-an-admin-page-but-dont-show-it-on-the-admin-menu">more details about this here</a>). Access to the <strong>Edit Book</strong> page is done via the main menu, from the list of all books.</p>
<p>The problem is, when I go to the <strong>Edit Book</strong> page, the Admin Menu to the left collapses (on the other hand, the default WordPress behaviour is as follows: If you go to an <strong>Edit Post</strong> page, or the <strong>Edit Page</strong> page, both the <strong>Posts</strong> and <strong>Pages</strong> menu stay expanded for their respective <em>edit</em> pages). In my case, the menu collapses.</p>
<p>How can I keep the menu to the left expanded when I go to the <strong>Edit Book</strong> page, to behave in a similar fashion to that of WordPress?</p>
<p>Thanks.</p>
| [
{
"answer_id": 260415,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>For your particular situation, where you need to have a menu registered, but not shown unless you click on it from a link on another page you can add a conditional check to see if you're on the editing page. If so, then change replace <code>null</code> with <code>book</code> per the <code>add_submenu_page()</code> parameters.</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page( 'Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17 );\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page( 'books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n // The Add Book menu page\n add_submenu_page( 'books', 'Add New Book', 'Add Book', 'publish_posts', 'add-book', 'render_add_book_page' );\n\n // Check the get parameter for page to see if its the page you want to display in the menu only when you're on it.\n if ( $_GET['page'] === 'edit-book' ) {\n // The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)\n add_submenu_page( 'books', 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n } else {\n // The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)\n add_submenu_page( null, 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n }\n}\n</code></pre>\n\n<p>An additional note. If it turns out that you need to also keep that menu item hidden even when selected you can enqueue a style to hide it only when you're on that page.</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function () {\n if ( $_GET['page'] === 'edit-book' ) {\n wp_enqueue_style( 'book-edit', get_stylesheet_directory_uri() . '/assets/css/book-edit.css' );\n }\n} );\n</code></pre>\n\n<p>Where the contents of book-edit.css would be something as simple as:</p>\n\n<pre><code>#toplevel_page_books li.current {\n display: none;\n}\n</code></pre>\n"
},
{
"answer_id": 260475,
"author": "Greeso",
"author_id": 34253,
"author_profile": "https://wordpress.stackexchange.com/users/34253",
"pm_score": 2,
"selected": true,
"text": "<p>The solution is based on the ideas provided by @Ian. Thanks.</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n // The Edit Book menu page and display it as the All Books page\n add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n }\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p>And we must hide the first menu item</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function () {\n\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n\n // Load CSS file\n wp_enqueue_style('book-edit', 'path/to/css/menu.css');\n\n // Load jQuery\n wp_enqueue_script('jquery');\n\n // Load \n wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');\n }\n});\n</code></pre>\n\n<p>And the content of <code>menu.css</code> is:</p>\n\n<pre><code>#toplevel_page_books li.current {\n display: none;\n}\n\n#toplevel_page_books li.wp-first-item {\n display: list-item;\n}\n</code></pre>\n\n<p>Also the content of 'menu.js' is:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n $('#toplevel_page_books li.wp-first-item').addClass('current');\n\n});\n</code></pre>\n\n<hr>\n\n<p><strong>TL;DR</strong></p>\n\n<p>To understand how all this works, here is a step-by-step explanation.</p>\n\n<p><strong>Step 1:</strong> We add the main menu item (the <em>books</em> menu item) to display the list of books</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n}\n</code></pre>\n\n<p><strong>Step 2:</strong> We add the <em>add-book</em> menu item as a submenu to the main <em>books</em> menu item</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p><strong>Step 3:</strong> Finishing Step 2 above adds the books menu item, The menu list on the left side would look like this:</p>\n\n<pre><code>Books <---------- This is the main top level menu names\n Books <---------- This is the first sub-menu\n Add New <---------- This is the second sub-menu\n</code></pre>\n\n<p>However, we should fix this. The intended list should look like this</p>\n\n<pre><code>Books <---------- This is the main top level menu names\n All Books <---------- This is the first sub-menu\n Add New <---------- This is the second sub-menu\n</code></pre>\n\n<p>To do this, we have to modify our code as follows:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p><strong>Step 4:</strong> Next we should add a sub menu to edit books (the <em>edit-book</em> menu item). After adding his submenu, and when we are at the <em>edit-book</em> page, the menu on the left should look like this:</p>\n\n<pre><code>Books\n All Books <---------- When we are in the 'edit-book' page, this menu item is selected and is highlighted (typically white in color), and also clicking on \"All Books\" would return us back to the \"All Books\" page.\n Add New\n</code></pre>\n\n<p>The solution I tried first was what I posted in my original question, which did not work exactly. So, based on discussions with @Ian and looking at his proposed solution, I came up with this:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n // If we are in the 'edit-book' page, then display the 'edit-book' submenu, otherwise, display the regular 'books' menu\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n // Display the 'edit-book' menu page and display it as the 'all-books' page\n // Notice that the slug is 'edit-book', but the display name is 'All Books'\n add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n }\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p>Now, if we click on the 'books' menu item, or the 'add-book' menu item, then everything is fine. However, if we try to edit an existing book then the following menu list will be displayed</p>\n\n<pre><code>Books\n All Books <---------- This is the first sub-menu (due to the first submenu call)\n All Books <---------- This is the 'edit-book' page (HIGHLIGHTED)\n Add New\n</code></pre>\n\n<p><strong>Step 5:</strong> Now we notice the following: By clicking on the first submenu, the \"All Books\" page will be rendered, and clicking on the second submenu will render the \"Edit\" page; and in our case, we want to render the \"All Books\" page. \nTherefore, we have to hide the SECOND submenu and make the first submenu highlighted. This is done as follows:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function () {\n\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n\n // Load CSS file\n wp_enqueue_style('book-edit', 'path/to/css/menu.css');\n\n // Load jQuery\n wp_enqueue_script('jquery');\n\n // Load \n wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');\n }\n});\n</code></pre>\n\n<p>And the content of <code>menu.css</code> is:</p>\n\n<pre><code>#toplevel_page_books li.current {\n display: none;\n}\n\n#toplevel_page_books li.wp-first-item {\n display: list-item;\n}\n</code></pre>\n\n<p>Also the content of 'menu.js' is:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n $('#toplevel_page_books li.wp-first-item').addClass('current');\n\n});\n</code></pre>\n\n<p>And now everything works like a charm.</p>\n"
},
{
"answer_id": 401566,
"author": "LauGau",
"author_id": 188239,
"author_profile": "https://wordpress.stackexchange.com/users/188239",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, you just have to register your menu normally, with the declaration of the parent page like so:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function create_menu_and_submenu_page(){\n\n // Top level menu\n add_menu_page(\n 'Books',\n 'Books',\n 'publish_posts',\n 'books',\n 'render_books_page',\n '',\n 17\n );\n\n // Here the other subpages\n // ...\n\n // Submenu page\n add_submenu_page(\n 'books', // Here put the parent slug\n 'Edit Book',\n 'Edit Book',\n 'publish_posts',\n 'edit-book',\n 'render_edit_book_page'\n );\n}\n</code></pre>\n<p>And then, you simply have to hide it like that:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// We remove the unecessary links from the left menu\n// while keeping the plugin menu selected\nadd_action( 'admin_head', function() {\n remove_submenu_page( 'books', 'edit-book' ); // 'parent-slug', 'subpage-slug'\n} );\n</code></pre>\n<p>Hope it will help someone else in the future.\nHappy Coding :)</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260410",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
]
| I am creating a custom admin section. I have the following code:
```
// Top level menu
add_menu_page('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
// Details: https://wordpress.stackexchange.com/questions/66498/add-menu-page-with-different-name-for-first-submenu-item
add_submenu_page('Books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page');
// The Add Book menu page
add_submenu_page('Books', 'Add New Book', 'Add Book', 'publish_posts', 'add-book', 'render_add_book_page');
// The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)
add_submenu_page(null, 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page');
```
As you notice in the last line of code, the first parameter of the `add_submenu_page()` is set to `null`. This is to ensure that the **Edit Book** page is hidden ([more details about this here](https://wordpress.stackexchange.com/questions/73622/add-an-admin-page-but-dont-show-it-on-the-admin-menu)). Access to the **Edit Book** page is done via the main menu, from the list of all books.
The problem is, when I go to the **Edit Book** page, the Admin Menu to the left collapses (on the other hand, the default WordPress behaviour is as follows: If you go to an **Edit Post** page, or the **Edit Page** page, both the **Posts** and **Pages** menu stay expanded for their respective *edit* pages). In my case, the menu collapses.
How can I keep the menu to the left expanded when I go to the **Edit Book** page, to behave in a similar fashion to that of WordPress?
Thanks. | The solution is based on the ideas provided by @Ian. Thanks.
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// The Edit Book menu page and display it as the All Books page
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
And we must hide the first menu item
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
---
**TL;DR**
To understand how all this works, here is a step-by-step explanation.
**Step 1:** We add the main menu item (the *books* menu item) to display the list of books
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
}
```
**Step 2:** We add the *add-book* menu item as a submenu to the main *books* menu item
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 3:** Finishing Step 2 above adds the books menu item, The menu list on the left side would look like this:
```
Books <---------- This is the main top level menu names
Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
However, we should fix this. The intended list should look like this
```
Books <---------- This is the main top level menu names
All Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
To do this, we have to modify our code as follows:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 4:** Next we should add a sub menu to edit books (the *edit-book* menu item). After adding his submenu, and when we are at the *edit-book* page, the menu on the left should look like this:
```
Books
All Books <---------- When we are in the 'edit-book' page, this menu item is selected and is highlighted (typically white in color), and also clicking on "All Books" would return us back to the "All Books" page.
Add New
```
The solution I tried first was what I posted in my original question, which did not work exactly. So, based on discussions with @Ian and looking at his proposed solution, I came up with this:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// If we are in the 'edit-book' page, then display the 'edit-book' submenu, otherwise, display the regular 'books' menu
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Display the 'edit-book' menu page and display it as the 'all-books' page
// Notice that the slug is 'edit-book', but the display name is 'All Books'
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
Now, if we click on the 'books' menu item, or the 'add-book' menu item, then everything is fine. However, if we try to edit an existing book then the following menu list will be displayed
```
Books
All Books <---------- This is the first sub-menu (due to the first submenu call)
All Books <---------- This is the 'edit-book' page (HIGHLIGHTED)
Add New
```
**Step 5:** Now we notice the following: By clicking on the first submenu, the "All Books" page will be rendered, and clicking on the second submenu will render the "Edit" page; and in our case, we want to render the "All Books" page.
Therefore, we have to hide the SECOND submenu and make the first submenu highlighted. This is done as follows:
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
And now everything works like a charm. |
260,416 | <p>I'm trying to find a way to get my posts with different look depending on their category.</p>
<p>I have first tried to do it using the <a href="https://developer.wordpress.org/files/2014/10/template-hierarchy.png" rel="nofollow noreferrer">template hierarchy</a> but it seems there is no pattern for the category posts. (ie single-cat-mycategory.php)</p>
<p>So then within single.php I tried the conditional tagging using <code>is_category()</code> but my understanding it's only working for the <code>archive</code> pages.</p>
<p>Finally, I'm now trying to use the <code>is_single()</code> conditional tagging where first I'm looking for all the posts corresponding to my category and pass it as a parameter of <code>is_single()</code></p>
<p><strong>In functions.php</strong></p>
<pre><code>function get_post_id_by_cat(){
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'my_category',
];
$cat_query = new WP_Query( $args );
if ($cat_query -> have_posts()){
while ($cat_query -> have_posts()){
$cat_query -> the_post();
$post_ids[] = get_the_ID();
}
wp_reset_postdata();
}
</code></pre>
<p><strong>In single.php</strong></p>
<pre><code>$my_cat_posts = get_post_id_by_cat();
if (is_single($my_cat_posts)) {
while ( have_posts() ) : the_post();
//do my stuff here
endwhile;
}
</code></pre>
<p><strong>My first question</strong> is this in term of Wordpress design a good way to do this or is there a better way as my concern is mainly for performance, with this method.</p>
<p><strong>If it's ok,</strong>
My issue is that <code>$post_ids</code> is storing the data in a php object format and not an array so <code>is_single()</code> doesn't get the posts ids properly as parameter.
And i don't get how I can get it converted to an array.</p>
<p><code>$post_ids[] = to_array(get_the_ID());</code> return</p>
<blockquote>
<p>Uncaught Error: Call to undefined function to_array()</p>
</blockquote>
<p>or
<code>$post_ids[] = (array)get_the_ID();</code> return each post ids stil has object but within a array like this:</p>
<pre><code>array(8) {
[0]=>
array(1) {
[0]=>
int(5415)
}…
</code></pre>
<p>or
<code>$post_ids[] = get_object_vars(get_the_ID());</code> return </p>
<blockquote>
<p>get_object_vars() expects parameter 1 to be object, integer given</p>
</blockquote>
<p>But if pass this array it does work properly:</p>
<pre><code>$array = ['5415','5413','5411','5401'];
</code></pre>
<p>Hope this is clear enough,</p>
<p>Thanks for any input!</p>
<p>Matth.</p>
| [
{
"answer_id": 260415,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": false,
"text": "<p>For your particular situation, where you need to have a menu registered, but not shown unless you click on it from a link on another page you can add a conditional check to see if you're on the editing page. If so, then change replace <code>null</code> with <code>book</code> per the <code>add_submenu_page()</code> parameters.</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page( 'Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17 );\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page( 'books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n // The Add Book menu page\n add_submenu_page( 'books', 'Add New Book', 'Add Book', 'publish_posts', 'add-book', 'render_add_book_page' );\n\n // Check the get parameter for page to see if its the page you want to display in the menu only when you're on it.\n if ( $_GET['page'] === 'edit-book' ) {\n // The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)\n add_submenu_page( 'books', 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n } else {\n // The Edit Book menu page (this page is hidden from the menu, and accessed via the All Books page only)\n add_submenu_page( null, 'Edit Book', 'Edit Book', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n }\n}\n</code></pre>\n\n<p>An additional note. If it turns out that you need to also keep that menu item hidden even when selected you can enqueue a style to hide it only when you're on that page.</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function () {\n if ( $_GET['page'] === 'edit-book' ) {\n wp_enqueue_style( 'book-edit', get_stylesheet_directory_uri() . '/assets/css/book-edit.css' );\n }\n} );\n</code></pre>\n\n<p>Where the contents of book-edit.css would be something as simple as:</p>\n\n<pre><code>#toplevel_page_books li.current {\n display: none;\n}\n</code></pre>\n"
},
{
"answer_id": 260475,
"author": "Greeso",
"author_id": 34253,
"author_profile": "https://wordpress.stackexchange.com/users/34253",
"pm_score": 2,
"selected": true,
"text": "<p>The solution is based on the ideas provided by @Ian. Thanks.</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n // The Edit Book menu page and display it as the All Books page\n add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n }\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p>And we must hide the first menu item</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function () {\n\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n\n // Load CSS file\n wp_enqueue_style('book-edit', 'path/to/css/menu.css');\n\n // Load jQuery\n wp_enqueue_script('jquery');\n\n // Load \n wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');\n }\n});\n</code></pre>\n\n<p>And the content of <code>menu.css</code> is:</p>\n\n<pre><code>#toplevel_page_books li.current {\n display: none;\n}\n\n#toplevel_page_books li.wp-first-item {\n display: list-item;\n}\n</code></pre>\n\n<p>Also the content of 'menu.js' is:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n $('#toplevel_page_books li.wp-first-item').addClass('current');\n\n});\n</code></pre>\n\n<hr>\n\n<p><strong>TL;DR</strong></p>\n\n<p>To understand how all this works, here is a step-by-step explanation.</p>\n\n<p><strong>Step 1:</strong> We add the main menu item (the <em>books</em> menu item) to display the list of books</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n}\n</code></pre>\n\n<p><strong>Step 2:</strong> We add the <em>add-book</em> menu item as a submenu to the main <em>books</em> menu item</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p><strong>Step 3:</strong> Finishing Step 2 above adds the books menu item, The menu list on the left side would look like this:</p>\n\n<pre><code>Books <---------- This is the main top level menu names\n Books <---------- This is the first sub-menu\n Add New <---------- This is the second sub-menu\n</code></pre>\n\n<p>However, we should fix this. The intended list should look like this</p>\n\n<pre><code>Books <---------- This is the main top level menu names\n All Books <---------- This is the first sub-menu\n Add New <---------- This is the second sub-menu\n</code></pre>\n\n<p>To do this, we have to modify our code as follows:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p><strong>Step 4:</strong> Next we should add a sub menu to edit books (the <em>edit-book</em> menu item). After adding his submenu, and when we are at the <em>edit-book</em> page, the menu on the left should look like this:</p>\n\n<pre><code>Books\n All Books <---------- When we are in the 'edit-book' page, this menu item is selected and is highlighted (typically white in color), and also clicking on \"All Books\" would return us back to the \"All Books\" page.\n Add New\n</code></pre>\n\n<p>The solution I tried first was what I posted in my original question, which did not work exactly. So, based on discussions with @Ian and looking at his proposed solution, I came up with this:</p>\n\n<pre><code>add_action( 'admin_menu', 'add_the_menus' );\nfunction add_the_menus() {\n\n // Top level menu\n add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);\n\n // Adding this function to make the first submenu have a different name than the main menu\n add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );\n\n // If we are in the 'edit-book' page, then display the 'edit-book' submenu, otherwise, display the regular 'books' menu\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n // Display the 'edit-book' menu page and display it as the 'all-books' page\n // Notice that the slug is 'edit-book', but the display name is 'All Books'\n add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );\n }\n\n // The add-book menu page\n add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );\n}\n</code></pre>\n\n<p>Now, if we click on the 'books' menu item, or the 'add-book' menu item, then everything is fine. However, if we try to edit an existing book then the following menu list will be displayed</p>\n\n<pre><code>Books\n All Books <---------- This is the first sub-menu (due to the first submenu call)\n All Books <---------- This is the 'edit-book' page (HIGHLIGHTED)\n Add New\n</code></pre>\n\n<p><strong>Step 5:</strong> Now we notice the following: By clicking on the first submenu, the \"All Books\" page will be rendered, and clicking on the second submenu will render the \"Edit\" page; and in our case, we want to render the \"All Books\" page. \nTherefore, we have to hide the SECOND submenu and make the first submenu highlighted. This is done as follows:</p>\n\n<pre><code>add_action( 'admin_enqueue_scripts', function () {\n\n if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {\n\n // Load CSS file\n wp_enqueue_style('book-edit', 'path/to/css/menu.css');\n\n // Load jQuery\n wp_enqueue_script('jquery');\n\n // Load \n wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');\n }\n});\n</code></pre>\n\n<p>And the content of <code>menu.css</code> is:</p>\n\n<pre><code>#toplevel_page_books li.current {\n display: none;\n}\n\n#toplevel_page_books li.wp-first-item {\n display: list-item;\n}\n</code></pre>\n\n<p>Also the content of 'menu.js' is:</p>\n\n<pre><code>jQuery(document).ready(function($) {\n\n $('#toplevel_page_books li.wp-first-item').addClass('current');\n\n});\n</code></pre>\n\n<p>And now everything works like a charm.</p>\n"
},
{
"answer_id": 401566,
"author": "LauGau",
"author_id": 188239,
"author_profile": "https://wordpress.stackexchange.com/users/188239",
"pm_score": 0,
"selected": false,
"text": "<p>Actually, you just have to register your menu normally, with the declaration of the parent page like so:</p>\n<pre class=\"lang-php prettyprint-override\"><code>function create_menu_and_submenu_page(){\n\n // Top level menu\n add_menu_page(\n 'Books',\n 'Books',\n 'publish_posts',\n 'books',\n 'render_books_page',\n '',\n 17\n );\n\n // Here the other subpages\n // ...\n\n // Submenu page\n add_submenu_page(\n 'books', // Here put the parent slug\n 'Edit Book',\n 'Edit Book',\n 'publish_posts',\n 'edit-book',\n 'render_edit_book_page'\n );\n}\n</code></pre>\n<p>And then, you simply have to hide it like that:</p>\n<pre class=\"lang-php prettyprint-override\"><code>// We remove the unecessary links from the left menu\n// while keeping the plugin menu selected\nadd_action( 'admin_head', function() {\n remove_submenu_page( 'books', 'edit-book' ); // 'parent-slug', 'subpage-slug'\n} );\n</code></pre>\n<p>Hope it will help someone else in the future.\nHappy Coding :)</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260416",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110467/"
]
| I'm trying to find a way to get my posts with different look depending on their category.
I have first tried to do it using the [template hierarchy](https://developer.wordpress.org/files/2014/10/template-hierarchy.png) but it seems there is no pattern for the category posts. (ie single-cat-mycategory.php)
So then within single.php I tried the conditional tagging using `is_category()` but my understanding it's only working for the `archive` pages.
Finally, I'm now trying to use the `is_single()` conditional tagging where first I'm looking for all the posts corresponding to my category and pass it as a parameter of `is_single()`
**In functions.php**
```
function get_post_id_by_cat(){
$args = [
'post_type' => 'post',
'post_status' => 'publish',
'category_name' => 'my_category',
];
$cat_query = new WP_Query( $args );
if ($cat_query -> have_posts()){
while ($cat_query -> have_posts()){
$cat_query -> the_post();
$post_ids[] = get_the_ID();
}
wp_reset_postdata();
}
```
**In single.php**
```
$my_cat_posts = get_post_id_by_cat();
if (is_single($my_cat_posts)) {
while ( have_posts() ) : the_post();
//do my stuff here
endwhile;
}
```
**My first question** is this in term of Wordpress design a good way to do this or is there a better way as my concern is mainly for performance, with this method.
**If it's ok,**
My issue is that `$post_ids` is storing the data in a php object format and not an array so `is_single()` doesn't get the posts ids properly as parameter.
And i don't get how I can get it converted to an array.
`$post_ids[] = to_array(get_the_ID());` return
>
> Uncaught Error: Call to undefined function to\_array()
>
>
>
or
`$post_ids[] = (array)get_the_ID();` return each post ids stil has object but within a array like this:
```
array(8) {
[0]=>
array(1) {
[0]=>
int(5415)
}…
```
or
`$post_ids[] = get_object_vars(get_the_ID());` return
>
> get\_object\_vars() expects parameter 1 to be object, integer given
>
>
>
But if pass this array it does work properly:
```
$array = ['5415','5413','5411','5401'];
```
Hope this is clear enough,
Thanks for any input!
Matth. | The solution is based on the ideas provided by @Ian. Thanks.
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// The Edit Book menu page and display it as the All Books page
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
And we must hide the first menu item
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
---
**TL;DR**
To understand how all this works, here is a step-by-step explanation.
**Step 1:** We add the main menu item (the *books* menu item) to display the list of books
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
}
```
**Step 2:** We add the *add-book* menu item as a submenu to the main *books* menu item
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 3:** Finishing Step 2 above adds the books menu item, The menu list on the left side would look like this:
```
Books <---------- This is the main top level menu names
Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
However, we should fix this. The intended list should look like this
```
Books <---------- This is the main top level menu names
All Books <---------- This is the first sub-menu
Add New <---------- This is the second sub-menu
```
To do this, we have to modify our code as follows:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
**Step 4:** Next we should add a sub menu to edit books (the *edit-book* menu item). After adding his submenu, and when we are at the *edit-book* page, the menu on the left should look like this:
```
Books
All Books <---------- When we are in the 'edit-book' page, this menu item is selected and is highlighted (typically white in color), and also clicking on "All Books" would return us back to the "All Books" page.
Add New
```
The solution I tried first was what I posted in my original question, which did not work exactly. So, based on discussions with @Ian and looking at his proposed solution, I came up with this:
```
add_action( 'admin_menu', 'add_the_menus' );
function add_the_menus() {
// Top level menu
add_menu_page ('Books', 'Books', 'publish_posts', 'books', 'render_books_page', '', 17);
// Adding this function to make the first submenu have a different name than the main menu
add_submenu_page('books', 'Books', 'All Books', 'publish_posts', 'books', 'render_books_page' );
// If we are in the 'edit-book' page, then display the 'edit-book' submenu, otherwise, display the regular 'books' menu
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Display the 'edit-book' menu page and display it as the 'all-books' page
// Notice that the slug is 'edit-book', but the display name is 'All Books'
add_submenu_page('books', 'Edit Book', 'All Books', 'publish_posts', 'edit-book', 'render_edit_book_page' );
}
// The add-book menu page
add_submenu_page('books', 'Add New Book', 'Add New', 'publish_posts', 'add-book', 'render_add_book_page' );
}
```
Now, if we click on the 'books' menu item, or the 'add-book' menu item, then everything is fine. However, if we try to edit an existing book then the following menu list will be displayed
```
Books
All Books <---------- This is the first sub-menu (due to the first submenu call)
All Books <---------- This is the 'edit-book' page (HIGHLIGHTED)
Add New
```
**Step 5:** Now we notice the following: By clicking on the first submenu, the "All Books" page will be rendered, and clicking on the second submenu will render the "Edit" page; and in our case, we want to render the "All Books" page.
Therefore, we have to hide the SECOND submenu and make the first submenu highlighted. This is done as follows:
```
add_action( 'admin_enqueue_scripts', function () {
if ((isset($_GET['page'])) && ($_GET['page'] === 'edit-book')) {
// Load CSS file
wp_enqueue_style('book-edit', 'path/to/css/menu.css');
// Load jQuery
wp_enqueue_script('jquery');
// Load
wp_enqueue_script('book-edit-script', 'path/to/js/menu.js');
}
});
```
And the content of `menu.css` is:
```
#toplevel_page_books li.current {
display: none;
}
#toplevel_page_books li.wp-first-item {
display: list-item;
}
```
Also the content of 'menu.js' is:
```
jQuery(document).ready(function($) {
$('#toplevel_page_books li.wp-first-item').addClass('current');
});
```
And now everything works like a charm. |
260,427 | <p>Hi I am trying to understand when and why I should use these esc-alternatives and so far I think I understand that it is needed to secure that input is not containing wrong characters and in that causing errors/security threats.</p>
<p>What I still wonder is should I always use esc_attr in HTML fields, or example the input fields of a contact form? And should I always use esc_url for all my own urls, for example image src paths? </p>
<p>And what about the_title()?
Should I use one of these escapes to all echos in my code or only where there are possible input from users?</p>
| [
{
"answer_id": 260430,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>If the values that are in need of escaping are generate fully from your code, as it is usually in admin screens, then yes, always escape. </p>\n\n<p>Things get more complex when you need to output a result of a core API as they are not consistent and it is better to dig into the code to see if the values returned by the API are already escaped, <code>the_title</code> is probably escaped, but if you use API to get a a tag name, you will need to escape it. </p>\n\n<p>An even harder situation is when your output is just an input to some higher layer of core, like a value you return in a filter, or widgets. Widgets are nasty as on the front end side you should escape all the values you got in the form except for the widget title.</p>\n\n<p>Rule of thumb, if there is a comparable functionality in core or a core theme, take a look how they handle escaping and do the same.</p>\n"
},
{
"answer_id": 260449,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 4,
"selected": true,
"text": "<p>Yes! You should always be escaping</p>\n\n<p>Escape Late, Escape Often</p>\n\n<p>Escaping is about intent, if you intend to output a URL, use <code>esc_url</code>, and it will definately be a URL ( if the data is malicious it will be made safe )</p>\n\n<blockquote>\n <p>What I still wonder is should I always use esc_attr in HTML fields, or example the input fields of a contact form? And should I always use esc_url for all my own urls, for example image src paths?</p>\n</blockquote>\n\n<p>If it's a hardcoded URL? E.g. <code>\"http://example.com\"</code> ? <strong>No</strong>, we know it's safe</p>\n\n<p>If it's a URL from a function or some other source? E.g. <code>echo get_permalink()</code> or <code>echo $url</code>?\n <strong>Yes, you should escape</strong> there's no way to know if it's safe</p>\n\n<p>If it's a function that outputs internally and doesn't require an <code>echo</code> statement? E.g. <code>the_permalink()</code>? <strong>No</strong> there's no way to escape this, the function needs to escape internally. Output buffers can be used in emergencies, but that path leads to madness</p>\n\n<blockquote>\n <p>And what about the_title()? Should I use one of these escapes to all echos in my code or only where there are possible input from users?</p>\n</blockquote>\n\n<p>There's no way to escape a function that outputs internally. <code>the_title</code> should be good to use, as are the others</p>\n\n<h2>With 1 Exception</h2>\n\n<p><code>bloginfo</code></p>\n\n<p>Avoid this function at all costs, for security reasons. <code>bloginfo</code> doesn't always escape internally, and as it outputs internally there's no way to add escaping.</p>\n\n<h3>The solution</h3>\n\n<p>Use <code>get_bloginfo</code> and escape the result, e.g.</p>\n\n<pre><code><a href=\"<?php echo esc_url( get_bloginfo( 'site' ) ); ?>\">\n</code></pre>\n\n<p><code>get_bloginfo</code> returns rather than outputs the value, allowing us to use escaping functions.</p>\n\n<h2>A Brief Note on Filters</h2>\n\n<p>Sometimes you want to pass things through a filter, such as <code>the_content</code>, but escaping the result will strip out tags.</p>\n\n<p>For example, this will strip any embedded videos present:</p>\n\n<pre><code>echo wp_kses_post( apply_filters( 'the_content', $stuff ) );\n</code></pre>\n\n<p>The solution is instead to do this:</p>\n\n<pre><code>echo apply_filters( 'the_content', wp_kses_post( $stuff ) );\n</code></pre>\n\n<p>The idea being that we know the input is safe, therefore the output must be safe. This assumes that any code running on that filter also escapes accordingly. Do this for these situations with WP Core filters, but avoid needing this in your own filters and code as much as possible</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260427",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114853/"
]
| Hi I am trying to understand when and why I should use these esc-alternatives and so far I think I understand that it is needed to secure that input is not containing wrong characters and in that causing errors/security threats.
What I still wonder is should I always use esc\_attr in HTML fields, or example the input fields of a contact form? And should I always use esc\_url for all my own urls, for example image src paths?
And what about the\_title()?
Should I use one of these escapes to all echos in my code or only where there are possible input from users? | Yes! You should always be escaping
Escape Late, Escape Often
Escaping is about intent, if you intend to output a URL, use `esc_url`, and it will definately be a URL ( if the data is malicious it will be made safe )
>
> What I still wonder is should I always use esc\_attr in HTML fields, or example the input fields of a contact form? And should I always use esc\_url for all my own urls, for example image src paths?
>
>
>
If it's a hardcoded URL? E.g. `"http://example.com"` ? **No**, we know it's safe
If it's a URL from a function or some other source? E.g. `echo get_permalink()` or `echo $url`?
**Yes, you should escape** there's no way to know if it's safe
If it's a function that outputs internally and doesn't require an `echo` statement? E.g. `the_permalink()`? **No** there's no way to escape this, the function needs to escape internally. Output buffers can be used in emergencies, but that path leads to madness
>
> And what about the\_title()? Should I use one of these escapes to all echos in my code or only where there are possible input from users?
>
>
>
There's no way to escape a function that outputs internally. `the_title` should be good to use, as are the others
With 1 Exception
----------------
`bloginfo`
Avoid this function at all costs, for security reasons. `bloginfo` doesn't always escape internally, and as it outputs internally there's no way to add escaping.
### The solution
Use `get_bloginfo` and escape the result, e.g.
```
<a href="<?php echo esc_url( get_bloginfo( 'site' ) ); ?>">
```
`get_bloginfo` returns rather than outputs the value, allowing us to use escaping functions.
A Brief Note on Filters
-----------------------
Sometimes you want to pass things through a filter, such as `the_content`, but escaping the result will strip out tags.
For example, this will strip any embedded videos present:
```
echo wp_kses_post( apply_filters( 'the_content', $stuff ) );
```
The solution is instead to do this:
```
echo apply_filters( 'the_content', wp_kses_post( $stuff ) );
```
The idea being that we know the input is safe, therefore the output must be safe. This assumes that any code running on that filter also escapes accordingly. Do this for these situations with WP Core filters, but avoid needing this in your own filters and code as much as possible |
260,442 | <p>I have several post types. I want to get all custom fields associated with that post type.</p>
<p>Example:</p>
<pre><code>Post
-- image
-- Featured image
-- body
</code></pre>
<p>I need to get all fields or custom fields in array. I found a solution <a href="https://wordpress.stackexchange.com/questions/18318/how-to-display-all-custom-fields-associated-with-a-post-type">from here</a>, but it does not serve my purpose:</p>
<pre><code> echo '<pre>';
print_r(get_post_custom($post_id));
echo '</pre>';
</code></pre>
| [
{
"answer_id": 261069,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 3,
"selected": true,
"text": "<p>Add the following code in the functions.php</p>\n\n<p><strong>for acf</strong></p>\n\n<pre><code>function get_all_meta($type){\n global $wpdb;\n $result = $wpdb->get_results($wpdb->prepare(\n \"SELECT post_id,meta_key,meta_value FROM wp_posts,wp_postmeta WHERE post_type = %s\n AND wp_posts.ID = wp_postmeta.post_id\", $type\n ), ARRAY_A);\n return $result;\n }\n\nfunction acf(){\n $options = array();\n $acf = get_all_meta('acf');\n foreach($acf as $key => $value){\n $options['post_type'][$value['post_id']]['post_id'] = $value['post_id'];\n $test = substr($value['meta_key'], 0, 6);\n if($test === 'field_'){\n $post_types = maybe_unserialize( $value['meta_value'] );\n $options['post_type'][$value['post_id']]['key'][] = $post_types['key'];\n $options['post_type'][$value['post_id']]['key'][] = $post_types['name'];\n $options['post_type'][$value['post_id']]['key'][] = $post_types['type'];\n }\n if($value['meta_key'] == 'rule'){\n $post_types = maybe_unserialize( $value['meta_value'] );\n\n $options['post_type'][$value['post_id']]['post_types'] = $post_types['value'];\n }\n }\n return $options;\n }\n</code></pre>\n\n<p>This will give you the array value of post meta key for acf.</p>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>foreach(acf() as $key => $value){\nupdate_post_meta(76, $value['type'], 'Steve');\n}\n</code></pre>\n\n<p><strong>For pods</strong></p>\n\n<p>function pods(){\n global $wpdb;\n //get the pods post types id.</p>\n\n<pre><code> $result = $wpdb->get_results($wpdb->prepare(\n \"SELECT ID,post_title,post_parent FROM wp_posts WHERE post_type = %s\", $type\n ), ARRAY_A);\n\n// pods each field for a post type create separate post type so again query to get the field post type result.\n $pods_field_post_type = array(); \n foreach($result as $value){\n $pods_field_post_type = $wpdb->get_results($wpdb->prepare(\n \"SELECT ID,post_title,post_name FROM wp_posts WHERE post_type = %s\n AND post_parent = %d\n \", '_pods_field',$value[\"ID\"]\n ), ARRAY_A);\n\n }\n$fields = array();\n foreach($pods_field_post_type as key => $value):\n $podsAPI = new PodsAPI();\n $pod = $podsAPI->load_pod( array( 'name' => '\n post' ));\n $fields[] = $pod['fields'][$value['post_name']]['type'];\n endforeach;\n }\nprint_r($fields);\n</code></pre>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>foreach($fields as $key => $value){\nupdate_post_meta(76, $value, 'Steve');\n}\n</code></pre>\n\n<p>function acf() and pods() give you the exact meta key of that post type.\nIf you copy and paste the code it may not work.</p>\n\n<p>Hope this answer help you and also others.</p>\n\n<p>let me know you not trouble anything.</p>\n"
},
{
"answer_id": 261316,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": false,
"text": "<h2>Post Type Features</h2>\n<p>Several options exist to obtain a list of <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#supports\" rel=\"nofollow noreferrer\">"features"</a> which a particular post type supports. The easiest is to simply use <a href=\"https://developer.wordpress.org/reference/functions/get_all_post_type_supports/\" rel=\"nofollow noreferrer\">the <code>get_all_post_type_supports()</code> function</a>:</p>\n<pre><code>$post_type_features = get_all_post_type_supports( 'post' );\n\nprint_r( $post_type_features );\n/* Array\n * (\n * [0] => author\n * [1] => editor\n * [2] => thumbnail\n * [3] => excerpt\n * [4] => trackbacks\n * [5] => custom-fields\n * [6] => comments\n * [7] => revisions\n * [8] => post-formats\n * [9] => title\n * )\n */\n</code></pre>\n<p>You can also use <a href=\"https://codex.wordpress.org/Function_Reference/post_type_supports\" rel=\"nofollow noreferrer\"><code>post_type_supports()</code></a> to see if a post type supports specific features.</p>\n<p>Another way to check a post type's features it to obtain it's post type object and simply check the <code>$supports</code> property:</p>\n<pre><code>$post_type_object = get_post_type_object( 'post' );\n\nprint_r( $post_type_object->supports );\n</code></pre>\n<hr />\n<h2>Custom Fields</h2>\n<p>Since <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow noreferrer\">custom fields</a> are <a href=\"https://codex.wordpress.org/Metadata_API\" rel=\"nofollow noreferrer\">post meta-data</a> associated on a post-by-post basis rather than a post-type, there is no direct way to retrieve a list of custom field names used by a particular post type.</p>\n<p>Rather, you would have to compile an array yourself by looping through every post of the post type in question and using <code>get_metadata( $post_id )</code> or <code>get_post_custom_keys( $post_id )</code> to retrieve every custom field stored for that post. This is potentially a <em><strong>very</strong></em> expensive operation and should be done as infrequently as possible - if this is something you are considering doing more than once every week or month, I'd highly recommend that you look into other means to accomplish your end-goal.</p>\n<p>A custom SQL query to determine this information is also possible, and would no doubt be significantly more performant than querying meta-data for every post of a post type.</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115277/"
]
| I have several post types. I want to get all custom fields associated with that post type.
Example:
```
Post
-- image
-- Featured image
-- body
```
I need to get all fields or custom fields in array. I found a solution [from here](https://wordpress.stackexchange.com/questions/18318/how-to-display-all-custom-fields-associated-with-a-post-type), but it does not serve my purpose:
```
echo '<pre>';
print_r(get_post_custom($post_id));
echo '</pre>';
``` | Add the following code in the functions.php
**for acf**
```
function get_all_meta($type){
global $wpdb;
$result = $wpdb->get_results($wpdb->prepare(
"SELECT post_id,meta_key,meta_value FROM wp_posts,wp_postmeta WHERE post_type = %s
AND wp_posts.ID = wp_postmeta.post_id", $type
), ARRAY_A);
return $result;
}
function acf(){
$options = array();
$acf = get_all_meta('acf');
foreach($acf as $key => $value){
$options['post_type'][$value['post_id']]['post_id'] = $value['post_id'];
$test = substr($value['meta_key'], 0, 6);
if($test === 'field_'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['key'][] = $post_types['key'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['name'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['type'];
}
if($value['meta_key'] == 'rule'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['post_types'] = $post_types['value'];
}
}
return $options;
}
```
This will give you the array value of post meta key for acf.
**How to use**
```
foreach(acf() as $key => $value){
update_post_meta(76, $value['type'], 'Steve');
}
```
**For pods**
function pods(){
global $wpdb;
//get the pods post types id.
```
$result = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_parent FROM wp_posts WHERE post_type = %s", $type
), ARRAY_A);
// pods each field for a post type create separate post type so again query to get the field post type result.
$pods_field_post_type = array();
foreach($result as $value){
$pods_field_post_type = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_name FROM wp_posts WHERE post_type = %s
AND post_parent = %d
", '_pods_field',$value["ID"]
), ARRAY_A);
}
$fields = array();
foreach($pods_field_post_type as key => $value):
$podsAPI = new PodsAPI();
$pod = $podsAPI->load_pod( array( 'name' => '
post' ));
$fields[] = $pod['fields'][$value['post_name']]['type'];
endforeach;
}
print_r($fields);
```
**How to use**
```
foreach($fields as $key => $value){
update_post_meta(76, $value, 'Steve');
}
```
function acf() and pods() give you the exact meta key of that post type.
If you copy and paste the code it may not work.
Hope this answer help you and also others.
let me know you not trouble anything. |
260,445 | <p>I am currently developing a theme where I want to add two permalinks.<br/>
One is redirecting to the index.php with some custom parameters and values (rule stored in the wp_options table), the other is redirecting to a file in my template which offers the admin-ajax.php functionality (rule stored in .htaccess file).</p>
<pre><code>add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$',
'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]',
'top'
);
add_rewrite_rule(
'ajax-api/?$',
str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' )
);
flush_rewrite_rules( true );
} );
</code></pre>
<p>As I am in developement mode I am flushing the rules by executing on the 'init' hook as well <br/>(<em>I know this is bad practice but this seems to be the best method for me to check if there is any change in the .htaccess file.</em>).
<p></p><strong>The Problem:</strong><br/>
Even though <code>flush_rewrite_rules()</code> resets hard flushing by default I set the parameter to true just to make sure. My first rewrite rule is perfoming very well whereas the .htaccess file is not regenerated until I visit the options-permalink.php page in the backend (where the flush-function is called as well and works?!).</p>
<p></p>
<p>I already tried excecuting <code>flush_rewrite_rules()</code> on another hooks as proposed in the Reference.</p>
<p></p>
<p>Thanks in advance for your help!</p>
<p></p>
<p><strong>Edit:</strong><br/>
Even changing the code to the following did behave the same way…</p>
<pre><code>global $wp_rewrite;
$wp_rewrite->add_rule( '^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$', 'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]', 'top' );
$wp_rewrite->add_external_rule( 'ajax-api/?$', str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' ) );
$wp_rewrite->flush_rules( true );
</code></pre>
| [
{
"answer_id": 261069,
"author": "Faysal Mahamud",
"author_id": 83752,
"author_profile": "https://wordpress.stackexchange.com/users/83752",
"pm_score": 3,
"selected": true,
"text": "<p>Add the following code in the functions.php</p>\n\n<p><strong>for acf</strong></p>\n\n<pre><code>function get_all_meta($type){\n global $wpdb;\n $result = $wpdb->get_results($wpdb->prepare(\n \"SELECT post_id,meta_key,meta_value FROM wp_posts,wp_postmeta WHERE post_type = %s\n AND wp_posts.ID = wp_postmeta.post_id\", $type\n ), ARRAY_A);\n return $result;\n }\n\nfunction acf(){\n $options = array();\n $acf = get_all_meta('acf');\n foreach($acf as $key => $value){\n $options['post_type'][$value['post_id']]['post_id'] = $value['post_id'];\n $test = substr($value['meta_key'], 0, 6);\n if($test === 'field_'){\n $post_types = maybe_unserialize( $value['meta_value'] );\n $options['post_type'][$value['post_id']]['key'][] = $post_types['key'];\n $options['post_type'][$value['post_id']]['key'][] = $post_types['name'];\n $options['post_type'][$value['post_id']]['key'][] = $post_types['type'];\n }\n if($value['meta_key'] == 'rule'){\n $post_types = maybe_unserialize( $value['meta_value'] );\n\n $options['post_type'][$value['post_id']]['post_types'] = $post_types['value'];\n }\n }\n return $options;\n }\n</code></pre>\n\n<p>This will give you the array value of post meta key for acf.</p>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>foreach(acf() as $key => $value){\nupdate_post_meta(76, $value['type'], 'Steve');\n}\n</code></pre>\n\n<p><strong>For pods</strong></p>\n\n<p>function pods(){\n global $wpdb;\n //get the pods post types id.</p>\n\n<pre><code> $result = $wpdb->get_results($wpdb->prepare(\n \"SELECT ID,post_title,post_parent FROM wp_posts WHERE post_type = %s\", $type\n ), ARRAY_A);\n\n// pods each field for a post type create separate post type so again query to get the field post type result.\n $pods_field_post_type = array(); \n foreach($result as $value){\n $pods_field_post_type = $wpdb->get_results($wpdb->prepare(\n \"SELECT ID,post_title,post_name FROM wp_posts WHERE post_type = %s\n AND post_parent = %d\n \", '_pods_field',$value[\"ID\"]\n ), ARRAY_A);\n\n }\n$fields = array();\n foreach($pods_field_post_type as key => $value):\n $podsAPI = new PodsAPI();\n $pod = $podsAPI->load_pod( array( 'name' => '\n post' ));\n $fields[] = $pod['fields'][$value['post_name']]['type'];\n endforeach;\n }\nprint_r($fields);\n</code></pre>\n\n<p><strong>How to use</strong></p>\n\n<pre><code>foreach($fields as $key => $value){\nupdate_post_meta(76, $value, 'Steve');\n}\n</code></pre>\n\n<p>function acf() and pods() give you the exact meta key of that post type.\nIf you copy and paste the code it may not work.</p>\n\n<p>Hope this answer help you and also others.</p>\n\n<p>let me know you not trouble anything.</p>\n"
},
{
"answer_id": 261316,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": false,
"text": "<h2>Post Type Features</h2>\n<p>Several options exist to obtain a list of <a href=\"https://codex.wordpress.org/Function_Reference/register_post_type#supports\" rel=\"nofollow noreferrer\">"features"</a> which a particular post type supports. The easiest is to simply use <a href=\"https://developer.wordpress.org/reference/functions/get_all_post_type_supports/\" rel=\"nofollow noreferrer\">the <code>get_all_post_type_supports()</code> function</a>:</p>\n<pre><code>$post_type_features = get_all_post_type_supports( 'post' );\n\nprint_r( $post_type_features );\n/* Array\n * (\n * [0] => author\n * [1] => editor\n * [2] => thumbnail\n * [3] => excerpt\n * [4] => trackbacks\n * [5] => custom-fields\n * [6] => comments\n * [7] => revisions\n * [8] => post-formats\n * [9] => title\n * )\n */\n</code></pre>\n<p>You can also use <a href=\"https://codex.wordpress.org/Function_Reference/post_type_supports\" rel=\"nofollow noreferrer\"><code>post_type_supports()</code></a> to see if a post type supports specific features.</p>\n<p>Another way to check a post type's features it to obtain it's post type object and simply check the <code>$supports</code> property:</p>\n<pre><code>$post_type_object = get_post_type_object( 'post' );\n\nprint_r( $post_type_object->supports );\n</code></pre>\n<hr />\n<h2>Custom Fields</h2>\n<p>Since <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow noreferrer\">custom fields</a> are <a href=\"https://codex.wordpress.org/Metadata_API\" rel=\"nofollow noreferrer\">post meta-data</a> associated on a post-by-post basis rather than a post-type, there is no direct way to retrieve a list of custom field names used by a particular post type.</p>\n<p>Rather, you would have to compile an array yourself by looping through every post of the post type in question and using <code>get_metadata( $post_id )</code> or <code>get_post_custom_keys( $post_id )</code> to retrieve every custom field stored for that post. This is potentially a <em><strong>very</strong></em> expensive operation and should be done as infrequently as possible - if this is something you are considering doing more than once every week or month, I'd highly recommend that you look into other means to accomplish your end-goal.</p>\n<p>A custom SQL query to determine this information is also possible, and would no doubt be significantly more performant than querying meta-data for every post of a post type.</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260445",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115634/"
]
| I am currently developing a theme where I want to add two permalinks.
One is redirecting to the index.php with some custom parameters and values (rule stored in the wp\_options table), the other is redirecting to a file in my template which offers the admin-ajax.php functionality (rule stored in .htaccess file).
```
add_action( 'init', 'custom_rewrite_rules' );
function custom_rewrite_rules() {
add_rewrite_rule(
'^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$',
'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]',
'top'
);
add_rewrite_rule(
'ajax-api/?$',
str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' )
);
flush_rewrite_rules( true );
} );
```
As I am in developement mode I am flushing the rules by executing on the 'init' hook as well
(*I know this is bad practice but this seems to be the best method for me to check if there is any change in the .htaccess file.*).
**The Problem:**
Even though `flush_rewrite_rules()` resets hard flushing by default I set the parameter to true just to make sure. My first rewrite rule is perfoming very well whereas the .htaccess file is not regenerated until I visit the options-permalink.php page in the backend (where the flush-function is called as well and works?!).
I already tried excecuting `flush_rewrite_rules()` on another hooks as proposed in the Reference.
Thanks in advance for your help!
**Edit:**
Even changing the code to the following did behave the same way…
```
global $wp_rewrite;
$wp_rewrite->add_rule( '^(activate|reset)/([0-9]*)sfa([A-Za-z0-9]*)/?$', 'index.php?sfa_user=$matches[2]&sfa_password_reset=$matches[3]', 'top' );
$wp_rewrite->add_external_rule( 'ajax-api/?$', str_replace( ABSPATH, '', dirname( dirname( __FILE__ ) ) . '/api/ajax-api.php' ) );
$wp_rewrite->flush_rules( true );
``` | Add the following code in the functions.php
**for acf**
```
function get_all_meta($type){
global $wpdb;
$result = $wpdb->get_results($wpdb->prepare(
"SELECT post_id,meta_key,meta_value FROM wp_posts,wp_postmeta WHERE post_type = %s
AND wp_posts.ID = wp_postmeta.post_id", $type
), ARRAY_A);
return $result;
}
function acf(){
$options = array();
$acf = get_all_meta('acf');
foreach($acf as $key => $value){
$options['post_type'][$value['post_id']]['post_id'] = $value['post_id'];
$test = substr($value['meta_key'], 0, 6);
if($test === 'field_'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['key'][] = $post_types['key'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['name'];
$options['post_type'][$value['post_id']]['key'][] = $post_types['type'];
}
if($value['meta_key'] == 'rule'){
$post_types = maybe_unserialize( $value['meta_value'] );
$options['post_type'][$value['post_id']]['post_types'] = $post_types['value'];
}
}
return $options;
}
```
This will give you the array value of post meta key for acf.
**How to use**
```
foreach(acf() as $key => $value){
update_post_meta(76, $value['type'], 'Steve');
}
```
**For pods**
function pods(){
global $wpdb;
//get the pods post types id.
```
$result = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_parent FROM wp_posts WHERE post_type = %s", $type
), ARRAY_A);
// pods each field for a post type create separate post type so again query to get the field post type result.
$pods_field_post_type = array();
foreach($result as $value){
$pods_field_post_type = $wpdb->get_results($wpdb->prepare(
"SELECT ID,post_title,post_name FROM wp_posts WHERE post_type = %s
AND post_parent = %d
", '_pods_field',$value["ID"]
), ARRAY_A);
}
$fields = array();
foreach($pods_field_post_type as key => $value):
$podsAPI = new PodsAPI();
$pod = $podsAPI->load_pod( array( 'name' => '
post' ));
$fields[] = $pod['fields'][$value['post_name']]['type'];
endforeach;
}
print_r($fields);
```
**How to use**
```
foreach($fields as $key => $value){
update_post_meta(76, $value, 'Steve');
}
```
function acf() and pods() give you the exact meta key of that post type.
If you copy and paste the code it may not work.
Hope this answer help you and also others.
let me know you not trouble anything. |
260,465 | <p>I'm really new to wordpress and now I have to do a plugin that creates a HTML table from file and prints it to the page, and add more functionality to the table using DataTables jquery addon. This all has to happen when i call shortcode in the page. I have managed to get the html table to the page, but i have no idea how to run jquery script to modify it.
So, in short: how to run jquery script after shortcode.
Any input is appreciated!</p>
| [
{
"answer_id": 260468,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function your_css_and_js() {\n wp_register_style('your_css_and_js', plugins_url('style.css',__FILE__ ));\n wp_enqueue_style('your_css_and_js');\n wp_register_script( 'your_css_and_js', plugins_url('your_script.js',__FILE__ ));\n wp_enqueue_script('your_css_and_js');\n}\n\n//adds to the admin dasboard if needed\nadd_action( 'admin_init','your_css_and_js');\n\n//adds to frontend\nadd_action('wp_enqueue_scripts', 'your_css_and_js');\n</code></pre>\n"
},
{
"answer_id": 260471,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>Your question is a little unclear. I'm interpreting it to mean that you want to enqueue a jQuery script to be run by the user's browser only on public pages that contain the shortcode.</p>\n\n<p>There are (at least) three ways of running a jQuery script only on pages that have a specific shortcode. The first way is to use the <code>add_shortcode()</code> function to add a hook to <code>get_footer</code> which then enqueues the jQuery script in the footer.</p>\n\n<pre><code>//* Enqueue script in the footer\nfunction wpse_260465_enqueue_script() {\n wp_enqueue_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );\n}\n\n//* Add action to enqueue script in the footer and return shortcode value\nfunction wpse_260465_shortcode( $atts ) {\n add_action( 'get_footer', 'wpse_260465_enqueue_script' );\n return 'your shortcode content';\n}\n\nadd_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );\n</code></pre>\n\n<p>The second way registers the script on every page, but only enqueues it when the specific shortcode is called on a page.</p>\n\n<pre><code>//* Enqueue previously registered script and return shortcode value\nfunction wpse_260465_shortcode( $atts ) {\n wp_enqueue_script( 'your-style-id' );\n return 'your shortcode content';\n}\nadd_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );\n\n//* Register our script to maybe enqueue later\nadd_action( 'wp_enqueue_scripts', 'wpse_260465_enqueue_scripts' );\nfunction wpse_260465_enqueue_scripts() {\n wp_register_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );\n}\n</code></pre>\n\n<p>The third way is to simply use the <code>add_shortcode()</code> function to write the jQuery inline.</p>\n\n<pre><code>//* Return inline jQuery script with shortcode value\nfunction wpse_260465_shortcode( $atts ) {\n $your_shortcode_content = 'your shortcode content';\n $your_shortcode_content .= $your_inline_jquery;\n return $your_shortcode_content;\n}\nadd_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );\n</code></pre>\n\n<p>The first and second methods are more the \"WordPress way\", and the third is the easiest to understand, but all three should work.</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260465",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115640/"
]
| I'm really new to wordpress and now I have to do a plugin that creates a HTML table from file and prints it to the page, and add more functionality to the table using DataTables jquery addon. This all has to happen when i call shortcode in the page. I have managed to get the html table to the page, but i have no idea how to run jquery script to modify it.
So, in short: how to run jquery script after shortcode.
Any input is appreciated! | Your question is a little unclear. I'm interpreting it to mean that you want to enqueue a jQuery script to be run by the user's browser only on public pages that contain the shortcode.
There are (at least) three ways of running a jQuery script only on pages that have a specific shortcode. The first way is to use the `add_shortcode()` function to add a hook to `get_footer` which then enqueues the jQuery script in the footer.
```
//* Enqueue script in the footer
function wpse_260465_enqueue_script() {
wp_enqueue_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
//* Add action to enqueue script in the footer and return shortcode value
function wpse_260465_shortcode( $atts ) {
add_action( 'get_footer', 'wpse_260465_enqueue_script' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The second way registers the script on every page, but only enqueues it when the specific shortcode is called on a page.
```
//* Enqueue previously registered script and return shortcode value
function wpse_260465_shortcode( $atts ) {
wp_enqueue_script( 'your-style-id' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
//* Register our script to maybe enqueue later
add_action( 'wp_enqueue_scripts', 'wpse_260465_enqueue_scripts' );
function wpse_260465_enqueue_scripts() {
wp_register_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
```
The third way is to simply use the `add_shortcode()` function to write the jQuery inline.
```
//* Return inline jQuery script with shortcode value
function wpse_260465_shortcode( $atts ) {
$your_shortcode_content = 'your shortcode content';
$your_shortcode_content .= $your_inline_jquery;
return $your_shortcode_content;
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The first and second methods are more the "WordPress way", and the third is the easiest to understand, but all three should work. |
260,488 | <p>I have a normal WordPress settings page. It POSTs to options.php.</p>
<p>In options.php it uses wp_get_referer to redirect back to the page it came from.</p>
<p>I need to use remove_query_arg to remove an argument from the URL. Example:</p>
<pre><code>https://www.example.com/wp-admin/admin.php?page=plugin_settings_page&tab=90
</code></pre>
<p>I need to remove the tab=90 part. How can I do this via options.php?</p>
| [
{
"answer_id": 260468,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<pre><code>function your_css_and_js() {\n wp_register_style('your_css_and_js', plugins_url('style.css',__FILE__ ));\n wp_enqueue_style('your_css_and_js');\n wp_register_script( 'your_css_and_js', plugins_url('your_script.js',__FILE__ ));\n wp_enqueue_script('your_css_and_js');\n}\n\n//adds to the admin dasboard if needed\nadd_action( 'admin_init','your_css_and_js');\n\n//adds to frontend\nadd_action('wp_enqueue_scripts', 'your_css_and_js');\n</code></pre>\n"
},
{
"answer_id": 260471,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>Your question is a little unclear. I'm interpreting it to mean that you want to enqueue a jQuery script to be run by the user's browser only on public pages that contain the shortcode.</p>\n\n<p>There are (at least) three ways of running a jQuery script only on pages that have a specific shortcode. The first way is to use the <code>add_shortcode()</code> function to add a hook to <code>get_footer</code> which then enqueues the jQuery script in the footer.</p>\n\n<pre><code>//* Enqueue script in the footer\nfunction wpse_260465_enqueue_script() {\n wp_enqueue_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );\n}\n\n//* Add action to enqueue script in the footer and return shortcode value\nfunction wpse_260465_shortcode( $atts ) {\n add_action( 'get_footer', 'wpse_260465_enqueue_script' );\n return 'your shortcode content';\n}\n\nadd_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );\n</code></pre>\n\n<p>The second way registers the script on every page, but only enqueues it when the specific shortcode is called on a page.</p>\n\n<pre><code>//* Enqueue previously registered script and return shortcode value\nfunction wpse_260465_shortcode( $atts ) {\n wp_enqueue_script( 'your-style-id' );\n return 'your shortcode content';\n}\nadd_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );\n\n//* Register our script to maybe enqueue later\nadd_action( 'wp_enqueue_scripts', 'wpse_260465_enqueue_scripts' );\nfunction wpse_260465_enqueue_scripts() {\n wp_register_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );\n}\n</code></pre>\n\n<p>The third way is to simply use the <code>add_shortcode()</code> function to write the jQuery inline.</p>\n\n<pre><code>//* Return inline jQuery script with shortcode value\nfunction wpse_260465_shortcode( $atts ) {\n $your_shortcode_content = 'your shortcode content';\n $your_shortcode_content .= $your_inline_jquery;\n return $your_shortcode_content;\n}\nadd_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );\n</code></pre>\n\n<p>The first and second methods are more the \"WordPress way\", and the third is the easiest to understand, but all three should work.</p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260488",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112235/"
]
| I have a normal WordPress settings page. It POSTs to options.php.
In options.php it uses wp\_get\_referer to redirect back to the page it came from.
I need to use remove\_query\_arg to remove an argument from the URL. Example:
```
https://www.example.com/wp-admin/admin.php?page=plugin_settings_page&tab=90
```
I need to remove the tab=90 part. How can I do this via options.php? | Your question is a little unclear. I'm interpreting it to mean that you want to enqueue a jQuery script to be run by the user's browser only on public pages that contain the shortcode.
There are (at least) three ways of running a jQuery script only on pages that have a specific shortcode. The first way is to use the `add_shortcode()` function to add a hook to `get_footer` which then enqueues the jQuery script in the footer.
```
//* Enqueue script in the footer
function wpse_260465_enqueue_script() {
wp_enqueue_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
//* Add action to enqueue script in the footer and return shortcode value
function wpse_260465_shortcode( $atts ) {
add_action( 'get_footer', 'wpse_260465_enqueue_script' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The second way registers the script on every page, but only enqueues it when the specific shortcode is called on a page.
```
//* Enqueue previously registered script and return shortcode value
function wpse_260465_shortcode( $atts ) {
wp_enqueue_script( 'your-style-id' );
return 'your shortcode content';
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
//* Register our script to maybe enqueue later
add_action( 'wp_enqueue_scripts', 'wpse_260465_enqueue_scripts' );
function wpse_260465_enqueue_scripts() {
wp_register_script( 'your-style-id', PATH_TO . 'script.js', [ 'jquery' ], false, true );
}
```
The third way is to simply use the `add_shortcode()` function to write the jQuery inline.
```
//* Return inline jQuery script with shortcode value
function wpse_260465_shortcode( $atts ) {
$your_shortcode_content = 'your shortcode content';
$your_shortcode_content .= $your_inline_jquery;
return $your_shortcode_content;
}
add_shortcode( 'wpse_260465', 'wpse_260465_shortcode' );
```
The first and second methods are more the "WordPress way", and the third is the easiest to understand, but all three should work. |
260,500 | <p>I am trying to insert this meta information into the cart and checkout page for woocommerce. It will hide a specific plugin on those pages. However i know if i edit the plugin files for woocommerce it will be overwritten on woocommerce update.</p>
<p>How would i do that correctly? Jquery? Or even function.php function? </p>
<pre><code>if (wc_get_page_id( 'cart' ) == get_the_ID()) {
<meta name="yo:active" content="false">
}
</code></pre>
<p>or</p>
<pre><code>if !is_page(array('cart', 'checkout')) {
$('#yoHolder').attr("style", "display: none !important");
}
</code></pre>
<p>i tried this too to achieve same outcome of hiding it but didnt work. </p>
<p>Thanks for any help!</p>
| [
{
"answer_id": 260765,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 1,
"selected": false,
"text": "<p>Add the code to the file functions.php</p>\n\n<pre><code>/**\n * add data in cart \n * \n */\nfunction add_custom_data_in_cart() {\n echo '<meta name=\"yo:active\" content=\"false\">'; \n}\n\nadd_action('woocommerce_cart_is_empty', 'add_custom_data_in_cart');\n\n/**\n * add data in checkout \n * \n */\nfunction add_custom_data_in_checkout() {\n echo '<meta name=\"yo:active\" content=\"false\">'; \n}\n\nadd_action('woocommerce_before_checkout_form', 'add_custom_data_in_checkout');\n</code></pre>\n"
},
{
"answer_id": 260804,
"author": "Jermain Newman",
"author_id": 115376,
"author_profile": "https://wordpress.stackexchange.com/users/115376",
"pm_score": 3,
"selected": true,
"text": "<p>If your goal is to put it in the <code><head>IM INSIDE THE HEAD</head></code> tag than just put it inside the head tag in the <code>theme_header.php</code> or <code>header.php</code> of your theme – if it's not a child theme.</p>\n\n<p>Place this snippet of code directly above the closing <code></head></code> tag in your header.php file. </p>\n\n<pre><code><?php\nif ( is_checkout() || is_cart() ) {\n // Add meta tag here\necho '<meta name=\"yo:active\" content=\"false\">';\n}\n?>\n</code></pre>\n\n<p>Should work fine for you. </p>\n"
}
]
| 2017/03/17 | [
"https://wordpress.stackexchange.com/questions/260500",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
]
| I am trying to insert this meta information into the cart and checkout page for woocommerce. It will hide a specific plugin on those pages. However i know if i edit the plugin files for woocommerce it will be overwritten on woocommerce update.
How would i do that correctly? Jquery? Or even function.php function?
```
if (wc_get_page_id( 'cart' ) == get_the_ID()) {
<meta name="yo:active" content="false">
}
```
or
```
if !is_page(array('cart', 'checkout')) {
$('#yoHolder').attr("style", "display: none !important");
}
```
i tried this too to achieve same outcome of hiding it but didnt work.
Thanks for any help! | If your goal is to put it in the `<head>IM INSIDE THE HEAD</head>` tag than just put it inside the head tag in the `theme_header.php` or `header.php` of your theme – if it's not a child theme.
Place this snippet of code directly above the closing `</head>` tag in your header.php file.
```
<?php
if ( is_checkout() || is_cart() ) {
// Add meta tag here
echo '<meta name="yo:active" content="false">';
}
?>
```
Should work fine for you. |
260,507 | <p>I have a list of terms I'm displaying using "get_terms". Each term is linked so if the user clicks it, they go to the term archive page. </p>
<pre><code> <?php $terms = get_terms('category');t
echo '<ul>';
foreach ($terms as $term) {
echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>';
}
echo '</ul>';
?>
</code></pre>
<p>However, I would like to know if there's a way to add an "active" class to each term link if user goes to the term archive page. </p>
<p>Thanks a lot for your help,</p>
| [
{
"answer_id": 260508,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 3,
"selected": false,
"text": "<p>Run a conditional check in the <code>foreach</code> loop using <code>is_category($term-name)</code></p>\n\n<p>Assign a class variable to <code>active</code> if it's the same as <code>$term->name</code></p>\n\n<pre><code>$terms = get_terms( 'category' );\necho '<ul>';\nforeach ( $terms as $term ) {\n $class = ( is_category( $term->name ) ) ? 'active' : ''; // assign this class if we're on the same category page as $term->name\n echo '<li><a href=\"' . get_term_link( $term ) . '\" class=\"' . $class . '\">' . $term->name . '</a></li>';\n}\necho '</ul>';\n</code></pre>\n"
},
{
"answer_id": 293915,
"author": "Houndjetode Noukpo Herve",
"author_id": 131682,
"author_profile": "https://wordpress.stackexchange.com/users/131682",
"pm_score": 0,
"selected": false,
"text": "<p>I had the same problem and it was the following solution that helped me. I hope I helped </p>\n\n<pre><code>$curTerm = $wp_query->queried_object;\n$terms = get_terms( 'product-category' );\nif ( ! empty( $terms ) && ! is_wp_error( $terms ) ) {\n foreach ( $terms as $term ) {\n $classes = array();\n if ( $term->name == $curTerm->name ) {\n $classes[] = 'active';\n }\n echo '<li class=\"' . implode( ' ', $classes ) . '\"><a href=\"' . get_term_link( $term ) . '\">' . $term->name . '</a></li>';\n }\n}\n</code></pre>\n\n<p>refer to <a href=\"https://stackoverflow.com/questions/30671598/current-taxonomy-item-in-custom-taxonomy-term-page\">this source</a> for more details</p>\n"
},
{
"answer_id": 363137,
"author": "adubiel",
"author_id": 185355,
"author_profile": "https://wordpress.stackexchange.com/users/185355",
"pm_score": 1,
"selected": false,
"text": "<p>This version uses <code>is_tax</code> function that checks specifically for taxonomies.</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'video-category',\n 'hide_empty' => false\n) );\n\nif (!empty( $terms ) && ! is_wp_error($terms)){\n foreach ( $terms as $term ) {\n $class = ( is_tax('video-category', $term->slug) ) ? 'cat-item current-cat' : 'cat-item';\n echo '<li class=\"'.$class.'\"><a href=\"' . get_term_link( $term ) .'\">' . $term->name . '</a></li>';\n}\n</code></pre>\n"
}
]
| 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260507",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
]
| I have a list of terms I'm displaying using "get\_terms". Each term is linked so if the user clicks it, they go to the term archive page.
```
<?php $terms = get_terms('category');t
echo '<ul>';
foreach ($terms as $term) {
echo '<li><a href="'.get_term_link($term).'">'.$term->name.'</a></li>';
}
echo '</ul>';
?>
```
However, I would like to know if there's a way to add an "active" class to each term link if user goes to the term archive page.
Thanks a lot for your help, | Run a conditional check in the `foreach` loop using `is_category($term-name)`
Assign a class variable to `active` if it's the same as `$term->name`
```
$terms = get_terms( 'category' );
echo '<ul>';
foreach ( $terms as $term ) {
$class = ( is_category( $term->name ) ) ? 'active' : ''; // assign this class if we're on the same category page as $term->name
echo '<li><a href="' . get_term_link( $term ) . '" class="' . $class . '">' . $term->name . '</a></li>';
}
echo '</ul>';
``` |
260,512 | <p>I am somewhat new in WordPress if it is about "deeper" customization.</p>
<p>Now I am having this function:</p>
<pre><code>esc_html_e( 'Dear Guest, with Your information we not find any room at the moment. Please contact us per email [email protected].', 'awebooking' );
</code></pre>
<p>And the text is showing so far.</p>
<p>But what <em>function</em> do I need to use when I like to add an <code>a</code> <code>href</code> (HTML link)?</p>
<p>So I like to have this text:</p>
<blockquote>
<p>Dear Guest, with Your information we not find any room at the moment.</p>
<p>Please contact us on our <code><a href="http://www.whitesandsamuiresort.com/contact-us/">contact page</a></code> or per email <code>[email protected]</code>.</p>
</blockquote>
<p>I'm having problem supporting translation (internationalization / localization) and escaping HTML links at the same time.</p>
| [
{
"answer_id": 260513,
"author": "Aftab",
"author_id": 64614,
"author_profile": "https://wordpress.stackexchange.com/users/64614",
"pm_score": -1,
"selected": false,
"text": "<p>If you are using esc_html_e then this function simply says it escapes the HTML tags. So you can't be able to use HTML tags inside this esc_html_e.</p>\n"
},
{
"answer_id": 260536,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<p>Since <a href=\"https://developer.wordpress.org/reference/functions/esc_html_e/\" rel=\"noreferrer\"><code>esc_html_e</code></a> will escape HTML link (hence will show the HTML anchor as plain text), you'll need to segment the text and escape the non-HTML part with <code>esc_html_e</code> or <a href=\"https://developer.wordpress.org/reference/functions/esc_html__/\" rel=\"noreferrer\"><code>esc_html__</code></a>, and print the HTML LINK part without HTML escaping.</p>\n\n<h1>Method-1 (just for your understanding):</h1>\n\n<p>You may do it in parts, like this:</p>\n\n<pre><code>esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );\necho \"<br><br>\";\n\nprintf(\n esc_html__( '%1$s %2$s', 'text-domain' ),\n esc_html__( 'Please contact us on our', 'text-domain' ),\n sprintf(\n '<a href=\"%s\">%s</a>',\n esc_url( 'http://www.example.com/contact-us/' ),\n esc_html__( 'Contact Page', 'text-domain' )\n )\n);\n\nprintf(\n ' or <a href=\"%s\">%s</a>',\n esc_url( 'mailto:[email protected]', array( 'mailto' ) ),\n esc_html__( 'Email', 'text-domain' )\n);\n</code></pre>\n\n<h1>Method-2 (just for your understanding):</h1>\n\n<p>Obviously, different languages will have different ordering of texts, so to give translators more flexibility (with escaping and ordering of text), you may do it in the following way instead:</p>\n\n<pre><code>printf(\n esc_html__( '%1$s%2$s%3$s%4$s%5$s', 'text-domain' ),\n esc_html__( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' ),\n nl2br( esc_html__( \"\\n\\n\", 'text-domain' ) ),\n sprintf(\n esc_html__( '%1$s %2$s', 'text-domain' ),\n esc_html__( 'Please contact us on our', 'text-domain' ),\n sprintf(\n '<a href=\"%s\">%s</a>',\n esc_url( 'http://www.example.com/contact-us/' ),\n esc_html__( 'Contact Page', 'text-domain' )\n )\n ),\n esc_html__( ' or ', 'text-domain' ),\n sprintf(\n '<a href=\"%s\">%s</a>',\n esc_url( 'mailto:[email protected]', array( 'mailto' ) ),\n esc_html__( 'Email', 'text-domain' )\n )\n);\n</code></pre>\n\n<p>This way of doing it will:</p>\n\n<ol>\n<li><p>Escape all the necessary translated texts.</p></li>\n<li><p>Allow the HTML for link, email (with <code>mailto:</code> syntax) etc.</p></li>\n<li><p>Allow translators to have all sorts of different ordering of texts for different languages. The <a href=\"http://php.net/manual/en/function.sprintf.php#example-5474\" rel=\"noreferrer\">argument swapping notation</a> (<code>%1$s</code>, <code>%2$s</code> etc.) is used so that the translators may reorder the translated text where needed.</p></li>\n</ol>\n\n<hr>\n\n<h1>Method-3 (Updated & Recommended):</h1>\n\n<p>As <a href=\"https://wordpress.stackexchange.com/a/261374/110572\">@shea rightly pointed out</a>, <strong>Method-2</strong> above works fine, but it may be difficult for the translators to add support for different languages. So we need a solution that:</p>\n\n<ol>\n<li><p>Keeps the sentences intact (doesn't break sentences).</p></li>\n<li><p>Does proper escaping.</p></li>\n<li><p>Provides ways to have different ordering for contact & email links (or anything similar) within the translated sentence.</p></li>\n</ol>\n\n<p>So to avoid the complication of <strong>method-2</strong>, the solution below keeps the translatable sentences intact and does the proper URL escaping & argument swapping at the same time (more notes within CODE comments):</p>\n\n<pre><code>// sample contact url (may be from an unsafe place like user input)\n$contact_url = 'http://www.example.com/contact-us/';\n// escaping $contact_url\n$contact_url = esc_url( $contact_url );\n\n// sample contact email (may be from an unsafe place like user input)\n$contact_email = '[email protected]';\n// escaping, sanitizing & hiding $contact_email.\n// Yes, you may still need to sanitize & escape email while using antispambot() function\n$contact_email = esc_url( sprintf( 'mailto:%s', antispambot( sanitize_email( $contact_email ) ) ), array( 'mailto' ) );\n\nesc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );\necho \"<br><br>\";\n\nprintf(\n esc_html__( 'Please contact us on our %1$s or per %2$s.', 'text-domain' ),\n sprintf(\n '<a href=\"%s\">%s</a>',\n $contact_url,\n esc_html__( 'Contact Page', 'text-domain' )\n ),\n sprintf(\n '<a href=\"%s\">%s</a>',\n $contact_email,\n esc_html__( 'Email', 'text-domain' )\n )\n );\n</code></pre>\n\n<p>This way of doing it will give translators two full sentences & two separate words to translate. So a translators will only have to worry about the following simple lines (while the CODE takes care of the rest):</p>\n\n<pre><code>esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );\n// ...\nesc_html__( 'Please contact us on our %1$s or per %2$s', 'text-domain' )\n// ...\nesc_html__( 'Contact Page', 'text-domain' )\n// ...\nesc_html__( 'Email', 'text-domain' )\n</code></pre>\n\n<p>That's it, simple structure and does proper escaping and argument swapping as well.</p>\n\n<hr>\n\n<p>Read more about <a href=\"https://developer.wordpress.org/themes/functionality/internationalization/\" rel=\"noreferrer\">internationalization for themes</a> & <a href=\"https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/\" rel=\"noreferrer\">internationalization for plugins</a>. </p>\n"
},
{
"answer_id": 261374,
"author": "shea",
"author_id": 19726,
"author_profile": "https://wordpress.stackexchange.com/users/19726",
"pm_score": 2,
"selected": false,
"text": "<p>I think the answer by @Fayaz is very good; they are definitely on the right path in that you should use sprintf() wrapped around translations to include things such as HTML and links.</p>\n\n<p>However, I don't believe that it is a good idea to split sentences into parts for translation, as many languages have different sentence structures that are not at all compatible with English. By splitting out individual words, a great deal of the context in which a specific word is translated is lot, potentially leading to ambiguity and translation errors.</p>\n\n<p>Instead, I recommend translating phrases and sentences as a whole, and then using <code>sprintf</code> or different esccaping functions where appropriate.</p>\n\n<p>For your text, the first part can simply be translated by itself with <code>esc_html_e</code>:</p>\n\n<pre><code>esc_html_e( 'Dear Guest, with your information we not find any room at the moment. ', 'text-domain' );\n</code></pre>\n\n<p>The second part is slightly harder. Now, I assume that you are retrieving the page URL and email from the database somehow, probably using <code>get_the_permalink()</code> or <code>get_option()</code> or some other function. So I'm going to assume they are stored in <code>$contact_page_url</code> and <code>$contact_email</code> variables.</p>\n\n<p>The first step is to translate the string, without the links. Note that we need to use <code>__()</code> without escaping at this point - that will come later.</p>\n\n<pre><code>__( 'Please contact us on our <a href=\"%1$s\">contact page</a> or by email %2$s.', text-domain' );\n</code></pre>\n\n<p>This way the translator is free to word the sentence as necessary and place the link URL and email where they need to.</p>\n\n<p>The next step is to use <code>sprintf()</code> to insert the link URL and email. Note that we use <code>esc_url()</code> here to escape the URL, and also the <code>antispambot()</code> to encode the email address to provide a minimal protection against scrapers:</p>\n\n<pre><code>$text = sprintf(\n __( 'Please contact us on our <a href=\"%1$s\">contact page</a> or by email %2$s.', 'text-domain' );\n esc_url( $contact_page_url ),\n sprintf( '<a href=\"mailto:%1$s\">%1$s</a>', antispambot( $contact_email ) );\n);\n</code></pre>\n\n<p>Finally, rather than using <code>esc_html()</code> , we need to use <code>wp_kses()</code> to only allow link elements in the translated HTML:</p>\n\n<pre><code>echo wp_kses( $text, array( 'a' => array( 'href' => array() ) ) );\n</code></pre>\n\n<p>And that's it! The final code is:</p>\n\n<pre><code>esc_html_e( 'Dear Guest, with your information we not find any room at the moment. ', 'text-domain' )\n\n$text = sprintf(\n __( 'Please contact us on our <a href=\"%1$s\">contact page</a> or by email %2$s.', 'text-domain' );\n esc_url( $contact_page_url ),\n sprintf( '<a href=\"mailto:%1$s\">%1$s</a>', antispambot( $contact_email ) );\n);\n\necho wp_kses( $text, array( 'a' => array( 'href' => array() ) ) );\n</code></pre>\n"
}
]
| 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260512",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115691/"
]
| I am somewhat new in WordPress if it is about "deeper" customization.
Now I am having this function:
```
esc_html_e( 'Dear Guest, with Your information we not find any room at the moment. Please contact us per email [email protected].', 'awebooking' );
```
And the text is showing so far.
But what *function* do I need to use when I like to add an `a` `href` (HTML link)?
So I like to have this text:
>
> Dear Guest, with Your information we not find any room at the moment.
>
>
> Please contact us on our `<a href="http://www.whitesandsamuiresort.com/contact-us/">contact page</a>` or per email `[email protected]`.
>
>
>
I'm having problem supporting translation (internationalization / localization) and escaping HTML links at the same time. | Since [`esc_html_e`](https://developer.wordpress.org/reference/functions/esc_html_e/) will escape HTML link (hence will show the HTML anchor as plain text), you'll need to segment the text and escape the non-HTML part with `esc_html_e` or [`esc_html__`](https://developer.wordpress.org/reference/functions/esc_html__/), and print the HTML LINK part without HTML escaping.
Method-1 (just for your understanding):
=======================================
You may do it in parts, like this:
```
esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );
echo "<br><br>";
printf(
esc_html__( '%1$s %2$s', 'text-domain' ),
esc_html__( 'Please contact us on our', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
esc_url( 'http://www.example.com/contact-us/' ),
esc_html__( 'Contact Page', 'text-domain' )
)
);
printf(
' or <a href="%s">%s</a>',
esc_url( 'mailto:[email protected]', array( 'mailto' ) ),
esc_html__( 'Email', 'text-domain' )
);
```
Method-2 (just for your understanding):
=======================================
Obviously, different languages will have different ordering of texts, so to give translators more flexibility (with escaping and ordering of text), you may do it in the following way instead:
```
printf(
esc_html__( '%1$s%2$s%3$s%4$s%5$s', 'text-domain' ),
esc_html__( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' ),
nl2br( esc_html__( "\n\n", 'text-domain' ) ),
sprintf(
esc_html__( '%1$s %2$s', 'text-domain' ),
esc_html__( 'Please contact us on our', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
esc_url( 'http://www.example.com/contact-us/' ),
esc_html__( 'Contact Page', 'text-domain' )
)
),
esc_html__( ' or ', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
esc_url( 'mailto:[email protected]', array( 'mailto' ) ),
esc_html__( 'Email', 'text-domain' )
)
);
```
This way of doing it will:
1. Escape all the necessary translated texts.
2. Allow the HTML for link, email (with `mailto:` syntax) etc.
3. Allow translators to have all sorts of different ordering of texts for different languages. The [argument swapping notation](http://php.net/manual/en/function.sprintf.php#example-5474) (`%1$s`, `%2$s` etc.) is used so that the translators may reorder the translated text where needed.
---
Method-3 (Updated & Recommended):
=================================
As [@shea rightly pointed out](https://wordpress.stackexchange.com/a/261374/110572), **Method-2** above works fine, but it may be difficult for the translators to add support for different languages. So we need a solution that:
1. Keeps the sentences intact (doesn't break sentences).
2. Does proper escaping.
3. Provides ways to have different ordering for contact & email links (or anything similar) within the translated sentence.
So to avoid the complication of **method-2**, the solution below keeps the translatable sentences intact and does the proper URL escaping & argument swapping at the same time (more notes within CODE comments):
```
// sample contact url (may be from an unsafe place like user input)
$contact_url = 'http://www.example.com/contact-us/';
// escaping $contact_url
$contact_url = esc_url( $contact_url );
// sample contact email (may be from an unsafe place like user input)
$contact_email = '[email protected]';
// escaping, sanitizing & hiding $contact_email.
// Yes, you may still need to sanitize & escape email while using antispambot() function
$contact_email = esc_url( sprintf( 'mailto:%s', antispambot( sanitize_email( $contact_email ) ) ), array( 'mailto' ) );
esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );
echo "<br><br>";
printf(
esc_html__( 'Please contact us on our %1$s or per %2$s.', 'text-domain' ),
sprintf(
'<a href="%s">%s</a>',
$contact_url,
esc_html__( 'Contact Page', 'text-domain' )
),
sprintf(
'<a href="%s">%s</a>',
$contact_email,
esc_html__( 'Email', 'text-domain' )
)
);
```
This way of doing it will give translators two full sentences & two separate words to translate. So a translators will only have to worry about the following simple lines (while the CODE takes care of the rest):
```
esc_html_e( 'Dear Guest, with Your information we could not find any room at the moment.', 'text-domain' );
// ...
esc_html__( 'Please contact us on our %1$s or per %2$s', 'text-domain' )
// ...
esc_html__( 'Contact Page', 'text-domain' )
// ...
esc_html__( 'Email', 'text-domain' )
```
That's it, simple structure and does proper escaping and argument swapping as well.
---
Read more about [internationalization for themes](https://developer.wordpress.org/themes/functionality/internationalization/) & [internationalization for plugins](https://developer.wordpress.org/plugins/internationalization/how-to-internationalize-your-plugin/). |
260,519 | <p>I want to be able to detect if a file at a certain path is a WordPress generated thumbnail. The only distinguishing feature of the WordPress thumbnail, as far as individual files are concerned, is that it would end with two or three numbers, 'x', another two or three numbers and then the file extension. The only way I can think of doing this would be to use a regex to literally detect that pattern in the file name. Is there a better way that I'm not thinking of? If not can someone help me with the regex?</p>
| [
{
"answer_id": 260543,
"author": "Irene Mitchell",
"author_id": 108769,
"author_profile": "https://wordpress.stackexchange.com/users/108769",
"pm_score": 2,
"selected": false,
"text": "<p>You need to know your site's current thumbnail dimension settings in order for you to detect if the $url is of thumbnail size.</p>\n\n<pre><code>$thumbnail_width = get_option( 'thumbnail_size_w' );\n$thumbnail_height = get_option( 'thumbnail_size_h' );\n\n// The do detection\n// Assuming you have the image $url\n\n$pattern = '%' . $thumbnail_width . 'x' . $thumbnail_height . '%';\n\nif ( preg_match( $pattern, $url ) ) {\n // do your stuff here ...\n}\n</code></pre>\n"
},
{
"answer_id": 260635,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p><em>Here are another two approaches that might or might not be suitable for your case:</em></p>\n\n<h2>Approach #1</h2>\n\n<p>Let's take the 300x200 size for example:</p>\n\n<pre><code>https://example.tld/wp-content/2017/03/vatnajokull-300x200.jpg\n</code></pre>\n\n<p>then here's one way how we can check if it's really part of the media library:</p>\n\n<ol>\n<li><p>Strip out the <code>-\\d+x\\d+</code> part from the filename so it becomes:</p>\n\n<pre><code>$url = 'https://example.tld/wp-content/2017/03/vatnajokull.jpg';\n</code></pre></li>\n<li><p>Use the core <a href=\"https://developer.wordpress.org/reference/functions/attachment_url_to_postid/\" rel=\"nofollow noreferrer\"><code>$attachment_id = attachment_url_to_postid( $url )</code></a> function to get the possible attachment ID.</p></li>\n<li>Use the attachment ID from part 2. to fetch the metadata with <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"nofollow noreferrer\"><code>$meta = wp_get_attachment_metadata( $attahcment_id )</code></a> that contains all generated image sizes. It fetches the <code>_wp_attachment_metadata</code> meta value.</li>\n<li>Check if the <code>300x200</code> size has been generated by peeking into the sizes metadata array ( i.e. <code>$meta['sizes']</code> ) and e.g. <code>file_exists( $path )</code> to be sure it really exists. </li>\n</ol>\n\n<p>Hope you can fill in the missing parts ;-)</p>\n\n<h2>Approach #2</h2>\n\n<p>The core uses a wildcard <code>LIKE</code> search on the <code>_wp_attachment_metadata</code> meta values, within <code>wp_delete_attachment()</code> (<a href=\"https://github.com/WordPress/WordPress/blob/cde61269235ba33355cc96b8eaff2a0164aee3c0/wp-includes/post.php#L4919-L4927\" rel=\"nofollow noreferrer\">source</a>), to see if other attachments use it as a thumb, before deleting it. This could work here but would be less accurate as it searches through serialized arrays. It looks like this in core:</p>\n\n<pre><code>if ( ! $wpdb->get_row( \n $wpdb->prepare( \n \"SELECT meta_id FROM $wpdb->postmeta \n WHERE meta_key = '_wp_attachment_metadata' \n AND meta_value LIKE %s \n AND post_id <> %d\", \n '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', \n $post_id\n )\n) ) {\n</code></pre>\n"
},
{
"answer_id": 261065,
"author": "heller_benjamin",
"author_id": 96964,
"author_profile": "https://wordpress.stackexchange.com/users/96964",
"pm_score": 0,
"selected": false,
"text": "<p>Ok here's how I did it. First I checked if it had supported image file extensions because we can save a DB query if not. Then I simply checked the database for an attachment id. If there is no attachment ID then I'm assuming this is a thumbnail. Maybe not perfect for every solution but will work for my application. Thanks for the suggestions they got my mind flowing in the right direction. </p>\n\n<pre><code>function is_not_thumbnail( $url ) {\n $result = true;\n $ext = substr( $url, -4 );\n\n if ( \n $ext === '.jpg' || \n $ext === '.JPG' ||\n $ext === 'jpeg' ||\n $ext === 'JPEG' ||\n $ext === '.png' ||\n $ext === '.PNG' ||\n $ext === '.gif' ||\n $ext === '.GIF' ||\n $ext === '.ico' ||\n $ext === '.ICO' \n ) {\n if ( get_attachment_id_from_url( $url ) === 'null' ) {\n $result = false;\n }\n }\n\n return $result;\n\n}\n\nfunction get_attachment_id_from_url( $url ) {\n global $wpdb;\n\n $result = $wpdb->get_results( 'SELECT ID FROM ' . $wpdb->prefix . 'posts WHERE guid = \"' . $url . '\"' );\n\n\n if ( !empty( $result[0] ) ) {\n return $result[0]->ID; \n } else {\n return false;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 331129,
"author": "Kameron Zach",
"author_id": 162793,
"author_profile": "https://wordpress.stackexchange.com/users/162793",
"pm_score": 0,
"selected": false,
"text": "<p>I cloned my media library and ran this node script against my nested Wordpress Media Files and looped through the files / folders. Put some logic inside the loop to rest the file name against a regular expression for the thumbnail naming convention filename-SIZExSIZE.ext. I used node file system and path to move the files around appropriately.</p>\n\n<pre><code>const glob = require(\"glob\");\nconst fs = require('fs');\nconst { resolve, basename } = require('path');\n\nglob(\"./../media/**/*.png\", {}, function (er, files) {\n\n var count = 0;\n for (const file of files) {\n if(/\\b\\d{2,4}[x.]?\\d{2,4}[..]([a-z\\.]{3})\\b/.test(file) === false){\n\n let oldFileNamePath = resolve(file);\n let newFileNamePath = resolve('./../media-new/'+ basename(file));\n\n fs.rename(oldFileNamePath, newFileNamePath, function (err) {\n if (err) throw err;\n console.log(count, 'renamed complete', newFileNamePath);\n });\n\n count++;\n }\n\n }\n\n});\n</code></pre>\n"
}
]
| 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260519",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96964/"
]
| I want to be able to detect if a file at a certain path is a WordPress generated thumbnail. The only distinguishing feature of the WordPress thumbnail, as far as individual files are concerned, is that it would end with two or three numbers, 'x', another two or three numbers and then the file extension. The only way I can think of doing this would be to use a regex to literally detect that pattern in the file name. Is there a better way that I'm not thinking of? If not can someone help me with the regex? | You need to know your site's current thumbnail dimension settings in order for you to detect if the $url is of thumbnail size.
```
$thumbnail_width = get_option( 'thumbnail_size_w' );
$thumbnail_height = get_option( 'thumbnail_size_h' );
// The do detection
// Assuming you have the image $url
$pattern = '%' . $thumbnail_width . 'x' . $thumbnail_height . '%';
if ( preg_match( $pattern, $url ) ) {
// do your stuff here ...
}
``` |
260,523 | <p>It is possible set display name from entered string into nickname registration field? I trying do this with simple hook, but after all it is not work.</p>
<pre><code>function set_default_display_name( $user_id ) {
$user = get_userdata( $user_id );
$name = $user->nickname;
$args = array(
'ID' => $user_id,
'display_name' => $name
);
wp_update_user( $args );
}
add_action( 'user_register', 'set_default_display_name' );
</code></pre>
<p>By default, immediately after registration, display name was set from WP username (login) not nickname. Can sombody help me to set a display name from nickname?</p>
| [
{
"answer_id": 260543,
"author": "Irene Mitchell",
"author_id": 108769,
"author_profile": "https://wordpress.stackexchange.com/users/108769",
"pm_score": 2,
"selected": false,
"text": "<p>You need to know your site's current thumbnail dimension settings in order for you to detect if the $url is of thumbnail size.</p>\n\n<pre><code>$thumbnail_width = get_option( 'thumbnail_size_w' );\n$thumbnail_height = get_option( 'thumbnail_size_h' );\n\n// The do detection\n// Assuming you have the image $url\n\n$pattern = '%' . $thumbnail_width . 'x' . $thumbnail_height . '%';\n\nif ( preg_match( $pattern, $url ) ) {\n // do your stuff here ...\n}\n</code></pre>\n"
},
{
"answer_id": 260635,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p><em>Here are another two approaches that might or might not be suitable for your case:</em></p>\n\n<h2>Approach #1</h2>\n\n<p>Let's take the 300x200 size for example:</p>\n\n<pre><code>https://example.tld/wp-content/2017/03/vatnajokull-300x200.jpg\n</code></pre>\n\n<p>then here's one way how we can check if it's really part of the media library:</p>\n\n<ol>\n<li><p>Strip out the <code>-\\d+x\\d+</code> part from the filename so it becomes:</p>\n\n<pre><code>$url = 'https://example.tld/wp-content/2017/03/vatnajokull.jpg';\n</code></pre></li>\n<li><p>Use the core <a href=\"https://developer.wordpress.org/reference/functions/attachment_url_to_postid/\" rel=\"nofollow noreferrer\"><code>$attachment_id = attachment_url_to_postid( $url )</code></a> function to get the possible attachment ID.</p></li>\n<li>Use the attachment ID from part 2. to fetch the metadata with <a href=\"https://developer.wordpress.org/reference/functions/wp_get_attachment_metadata/\" rel=\"nofollow noreferrer\"><code>$meta = wp_get_attachment_metadata( $attahcment_id )</code></a> that contains all generated image sizes. It fetches the <code>_wp_attachment_metadata</code> meta value.</li>\n<li>Check if the <code>300x200</code> size has been generated by peeking into the sizes metadata array ( i.e. <code>$meta['sizes']</code> ) and e.g. <code>file_exists( $path )</code> to be sure it really exists. </li>\n</ol>\n\n<p>Hope you can fill in the missing parts ;-)</p>\n\n<h2>Approach #2</h2>\n\n<p>The core uses a wildcard <code>LIKE</code> search on the <code>_wp_attachment_metadata</code> meta values, within <code>wp_delete_attachment()</code> (<a href=\"https://github.com/WordPress/WordPress/blob/cde61269235ba33355cc96b8eaff2a0164aee3c0/wp-includes/post.php#L4919-L4927\" rel=\"nofollow noreferrer\">source</a>), to see if other attachments use it as a thumb, before deleting it. This could work here but would be less accurate as it searches through serialized arrays. It looks like this in core:</p>\n\n<pre><code>if ( ! $wpdb->get_row( \n $wpdb->prepare( \n \"SELECT meta_id FROM $wpdb->postmeta \n WHERE meta_key = '_wp_attachment_metadata' \n AND meta_value LIKE %s \n AND post_id <> %d\", \n '%' . $wpdb->esc_like( $meta['thumb'] ) . '%', \n $post_id\n )\n) ) {\n</code></pre>\n"
},
{
"answer_id": 261065,
"author": "heller_benjamin",
"author_id": 96964,
"author_profile": "https://wordpress.stackexchange.com/users/96964",
"pm_score": 0,
"selected": false,
"text": "<p>Ok here's how I did it. First I checked if it had supported image file extensions because we can save a DB query if not. Then I simply checked the database for an attachment id. If there is no attachment ID then I'm assuming this is a thumbnail. Maybe not perfect for every solution but will work for my application. Thanks for the suggestions they got my mind flowing in the right direction. </p>\n\n<pre><code>function is_not_thumbnail( $url ) {\n $result = true;\n $ext = substr( $url, -4 );\n\n if ( \n $ext === '.jpg' || \n $ext === '.JPG' ||\n $ext === 'jpeg' ||\n $ext === 'JPEG' ||\n $ext === '.png' ||\n $ext === '.PNG' ||\n $ext === '.gif' ||\n $ext === '.GIF' ||\n $ext === '.ico' ||\n $ext === '.ICO' \n ) {\n if ( get_attachment_id_from_url( $url ) === 'null' ) {\n $result = false;\n }\n }\n\n return $result;\n\n}\n\nfunction get_attachment_id_from_url( $url ) {\n global $wpdb;\n\n $result = $wpdb->get_results( 'SELECT ID FROM ' . $wpdb->prefix . 'posts WHERE guid = \"' . $url . '\"' );\n\n\n if ( !empty( $result[0] ) ) {\n return $result[0]->ID; \n } else {\n return false;\n }\n\n}\n</code></pre>\n"
},
{
"answer_id": 331129,
"author": "Kameron Zach",
"author_id": 162793,
"author_profile": "https://wordpress.stackexchange.com/users/162793",
"pm_score": 0,
"selected": false,
"text": "<p>I cloned my media library and ran this node script against my nested Wordpress Media Files and looped through the files / folders. Put some logic inside the loop to rest the file name against a regular expression for the thumbnail naming convention filename-SIZExSIZE.ext. I used node file system and path to move the files around appropriately.</p>\n\n<pre><code>const glob = require(\"glob\");\nconst fs = require('fs');\nconst { resolve, basename } = require('path');\n\nglob(\"./../media/**/*.png\", {}, function (er, files) {\n\n var count = 0;\n for (const file of files) {\n if(/\\b\\d{2,4}[x.]?\\d{2,4}[..]([a-z\\.]{3})\\b/.test(file) === false){\n\n let oldFileNamePath = resolve(file);\n let newFileNamePath = resolve('./../media-new/'+ basename(file));\n\n fs.rename(oldFileNamePath, newFileNamePath, function (err) {\n if (err) throw err;\n console.log(count, 'renamed complete', newFileNamePath);\n });\n\n count++;\n }\n\n }\n\n});\n</code></pre>\n"
}
]
| 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260523",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84343/"
]
| It is possible set display name from entered string into nickname registration field? I trying do this with simple hook, but after all it is not work.
```
function set_default_display_name( $user_id ) {
$user = get_userdata( $user_id );
$name = $user->nickname;
$args = array(
'ID' => $user_id,
'display_name' => $name
);
wp_update_user( $args );
}
add_action( 'user_register', 'set_default_display_name' );
```
By default, immediately after registration, display name was set from WP username (login) not nickname. Can sombody help me to set a display name from nickname? | You need to know your site's current thumbnail dimension settings in order for you to detect if the $url is of thumbnail size.
```
$thumbnail_width = get_option( 'thumbnail_size_w' );
$thumbnail_height = get_option( 'thumbnail_size_h' );
// The do detection
// Assuming you have the image $url
$pattern = '%' . $thumbnail_width . 'x' . $thumbnail_height . '%';
if ( preg_match( $pattern, $url ) ) {
// do your stuff here ...
}
``` |
260,535 | <p>I am trying to add theme support for custom background using the following code in functions.php file:</p>
<pre><code>function supp_custom_bg() {
$defaults = array(
'default-color' => '',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults );
}
add_action( 'after_setup_theme', 'supp_custom_bg', 20 );
</code></pre>
<p>and the options now are activated in the customizer but no effect on the theme.</p>
<p>Note: The <code>wp_head</code> is added to the <code><head></code> tag</p>
| [
{
"answer_id": 260541,
"author": "Irene Mitchell",
"author_id": 108769,
"author_profile": "https://wordpress.stackexchange.com/users/108769",
"pm_score": 0,
"selected": false,
"text": "<p>If you intend to customize how background image is implemented in your theme then do share the code of your <code>_custom_background_cb</code> callback function. If not and simply wanted to add background image then remove <code>wp-head-callback</code>.</p>\n"
},
{
"answer_id": 260561,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": true,
"text": "<p>The simplest way to use this feature:</p>\n\n<ol>\n<li>Add <code>add_theme_support( 'custom-background' );</code> to <code>functions.php</code></li>\n<li>Use <code>body_class()</code> in your <code>body</code> tag like this: <code><body <?php body_class(); ?>></code></li>\n<li>use <code><?php wp_head(); ?></code> in your <code>head</code> tag</li>\n</ol>\n\n<p>if you go to the customizer should look like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/59c9D.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/59c9D.png\" alt=\"enter image description here\"></a> </p>\n"
}
]
| 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260535",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109616/"
]
| I am trying to add theme support for custom background using the following code in functions.php file:
```
function supp_custom_bg() {
$defaults = array(
'default-color' => '',
'default-image' => '',
'wp-head-callback' => '_custom_background_cb',
'admin-head-callback' => '',
'admin-preview-callback' => ''
);
add_theme_support( 'custom-background', $defaults );
}
add_action( 'after_setup_theme', 'supp_custom_bg', 20 );
```
and the options now are activated in the customizer but no effect on the theme.
Note: The `wp_head` is added to the `<head>` tag | The simplest way to use this feature:
1. Add `add_theme_support( 'custom-background' );` to `functions.php`
2. Use `body_class()` in your `body` tag like this: `<body <?php body_class(); ?>>`
3. use `<?php wp_head(); ?>` in your `head` tag
if you go to the customizer should look like this:
[](https://i.stack.imgur.com/59c9D.png) |
260,553 | <p>I'm trying to add url query parameters to all internal links inside a WordPress blog. For example, client lands on the blog with this link:</p>
<pre><code>www.example.com/?p1=test&p2=test
</code></pre>
<p>I want the links inside the blog, for example a link to a post, to still have the query strings:</p>
<pre><code>www.example.com/post1/?p1=test&p2=test
</code></pre>
<p>Is there is a way to do it?</p>
| [
{
"answer_id": 260554,
"author": "AppError",
"author_id": 113811,
"author_profile": "https://wordpress.stackexchange.com/users/113811",
"pm_score": 0,
"selected": false,
"text": "<p>So you want to \"keep\" the variable value? Maybe you're best to set a cookie? This would probably make things much easier and cleaner. Have a look at this article, it seems to have everything you need to set a cookie: <a href=\"https://premium.wpmudev.org/blog/set-get-delete-cookies/\" rel=\"nofollow noreferrer\">https://premium.wpmudev.org/blog/set-get-delete-cookies/</a> and you should be able to use get_query_var to get the variable from the URL: <a href=\"https://codex.wordpress.org/Function_Reference/get_query_var\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_query_var</a></p>\n"
},
{
"answer_id": 260555,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 1,
"selected": false,
"text": "<p>You can access the query string with the global variable <a href=\"http://php.net/manual/en/reserved.variables.server.php\" rel=\"nofollow noreferrer\"><code>$_SERVER</code></a>, with <code>$_SERVER['QUERY_STRING']</code>. The next step is to append this to all internal links in your blog. This is slightly more difficult, because the links may be hiding anywhere.</p>\n\n<p>Links that are hiding in post content can be tracked down and adapted with <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow noreferrer\"><code>the_content</code></a> filter. <a href=\"https://wordpress.stackexchange.com/questions/156186/add-class-to-internal-links-in-content\">Here</a> is an example for a slightly different use of that filter only on internal links.</p>\n\n<p>Permalinks in themes and plugins should pass the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/post_link\" rel=\"nofollow noreferrer\"><code>post_link</code></a> filter, which you can also use to append the string.</p>\n"
},
{
"answer_id": 260579,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 3,
"selected": true,
"text": "<p>The following is <strong>not</strong> a <em>complete</em> solution (i.e., as @cjbj mentioned, it won't handle links in post content), but it will achieve what you want for any link whose URL is obtained (in WP Core, a theme or a plugin) via <a href=\"https://developer.wordpress.org/reference/functions/get_permalink/\" rel=\"nofollow noreferrer\">get_permalink()</a> (including the output of <a href=\"https://developer.wordpress.org/reference/functions/wp_page_menu/\" rel=\"nofollow noreferrer\">wp_page_menu()</a>, and kin).</p>\n\n<pre><code>$filters = array (\n 'post_link', // when post_type == 'post'\n 'page_link', // when post_type == 'page'\n 'attachment_link', // when post_type == 'attachment'\n 'post_type_link', // when post_type is not one of the above\n ) ;\nforeach ($filters as $filter) {\n add_filter ($filter, 'wpse_add_current_requests_query_args', 10, 3) ;\n }\n\nfunction\nwpse_add_current_requests_query_args ($permalink, $post, $leavename)\n{\n if (!is_admin ()) {\n // we only want to modify the permalink URL on the front-end\n return ;\n }\n\n // for the purposes of this answer, we ignore the $post & $leavename\n // params, but they are there in case you want to do conditional\n // processing based on their value\n return (esc_url (add_query_arg ($_GET, $permalink))) ;\n}\n</code></pre>\n\n<h2>Explanation</h2>\n\n<p>Before returning it's result, <code>get_permalink()</code> applies one of 4 filters (named in the <code>$filters</code> array above) on the permalink it has generated. So, we hook into each of those filters.</p>\n\n<p>The function we hook to these filters calls <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\">add_query_arg()</a> to add any query args present in the current request (i.e., <code>$_GET</code>).</p>\n\n<h2>Important Security Consideration</h2>\n\n<p>As mentioned in <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow noreferrer\">add_query_arg()</a>:</p>\n\n<blockquote>\n <p>Important: The return value of add_query_arg() is not escaped by default. Output should be late-escaped with esc_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.</p>\n</blockquote>\n\n<p>Calling esc_url() in <code>wpse_add_current_requests_query_args()</code> is not what I would call \"late-escaped\" in all cases. But unfortunately, a number of WP Core funcs (e.g. <a href=\"https://developer.wordpress.org/reference/classes/walker_page/start_el/\" rel=\"nofollow noreferrer\">Walker_Page::start_el()</a>, which is ultimately called by <code>wp_page_menu()</code>), don't call <code>esc_url()</code> on the return value of <code>get_permalink()</code>, so we have to call it in our filter hook to be safe.</p>\n"
}
]
| 2017/03/18 | [
"https://wordpress.stackexchange.com/questions/260553",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115654/"
]
| I'm trying to add url query parameters to all internal links inside a WordPress blog. For example, client lands on the blog with this link:
```
www.example.com/?p1=test&p2=test
```
I want the links inside the blog, for example a link to a post, to still have the query strings:
```
www.example.com/post1/?p1=test&p2=test
```
Is there is a way to do it? | The following is **not** a *complete* solution (i.e., as @cjbj mentioned, it won't handle links in post content), but it will achieve what you want for any link whose URL is obtained (in WP Core, a theme or a plugin) via [get\_permalink()](https://developer.wordpress.org/reference/functions/get_permalink/) (including the output of [wp\_page\_menu()](https://developer.wordpress.org/reference/functions/wp_page_menu/), and kin).
```
$filters = array (
'post_link', // when post_type == 'post'
'page_link', // when post_type == 'page'
'attachment_link', // when post_type == 'attachment'
'post_type_link', // when post_type is not one of the above
) ;
foreach ($filters as $filter) {
add_filter ($filter, 'wpse_add_current_requests_query_args', 10, 3) ;
}
function
wpse_add_current_requests_query_args ($permalink, $post, $leavename)
{
if (!is_admin ()) {
// we only want to modify the permalink URL on the front-end
return ;
}
// for the purposes of this answer, we ignore the $post & $leavename
// params, but they are there in case you want to do conditional
// processing based on their value
return (esc_url (add_query_arg ($_GET, $permalink))) ;
}
```
Explanation
-----------
Before returning it's result, `get_permalink()` applies one of 4 filters (named in the `$filters` array above) on the permalink it has generated. So, we hook into each of those filters.
The function we hook to these filters calls [add\_query\_arg()](https://developer.wordpress.org/reference/functions/add_query_arg/) to add any query args present in the current request (i.e., `$_GET`).
Important Security Consideration
--------------------------------
As mentioned in [add\_query\_arg()](https://developer.wordpress.org/reference/functions/add_query_arg/):
>
> Important: The return value of add\_query\_arg() is not escaped by default. Output should be late-escaped with esc\_url() or similar to help prevent vulnerability to cross-site scripting (XSS) attacks.
>
>
>
Calling esc\_url() in `wpse_add_current_requests_query_args()` is not what I would call "late-escaped" in all cases. But unfortunately, a number of WP Core funcs (e.g. [Walker\_Page::start\_el()](https://developer.wordpress.org/reference/classes/walker_page/start_el/), which is ultimately called by `wp_page_menu()`), don't call `esc_url()` on the return value of `get_permalink()`, so we have to call it in our filter hook to be safe. |
260,586 | <p>I am trying to figure out a way to make a sum of all the posts displayed in a loop. For example:</p>
<pre><code><?php if (have_posts()) :
$total_count = 1;
while (have_posts()) : the_post();
echo $total_count;
endwhile;
endif;
?>
</code></pre>
<p>Returns: 1 1 1 1 1 1 1</p>
<p>Since there are 7 posts in my loop. However, I would like to make a sum of all those 1's in order to get 7 as a result.</p>
<p>Any ideas?</p>
| [
{
"answer_id": 260587,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 2,
"selected": false,
"text": "<p>If <code>have_posts()</code> is <code>true</code>, there is a global <code>WP_Query</code> object available. And that has a post count already:</p>\n\n<pre><code>if ( have_posts() )\n{\n print $GLOBALS['wp_query']->post_count;\n}\n</code></pre>\n\n<p>There is no need for a custom count.</p>\n"
},
{
"answer_id": 260590,
"author": "Abdul Awal Uzzal",
"author_id": 31449,
"author_profile": "https://wordpress.stackexchange.com/users/31449",
"pm_score": 1,
"selected": false,
"text": "<p>I think you're looking for something like this:</p>\n\n<pre><code><?php\n$total_count = 0;\nif (have_posts()) : while (have_posts()) : the_post(); \n $total_count++;\nendwhile;\nendif;\necho 'Total Posts in loop:'. $total_count;\n?>\n</code></pre>\n"
}
]
| 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
]
| I am trying to figure out a way to make a sum of all the posts displayed in a loop. For example:
```
<?php if (have_posts()) :
$total_count = 1;
while (have_posts()) : the_post();
echo $total_count;
endwhile;
endif;
?>
```
Returns: 1 1 1 1 1 1 1
Since there are 7 posts in my loop. However, I would like to make a sum of all those 1's in order to get 7 as a result.
Any ideas? | If `have_posts()` is `true`, there is a global `WP_Query` object available. And that has a post count already:
```
if ( have_posts() )
{
print $GLOBALS['wp_query']->post_count;
}
```
There is no need for a custom count. |
260,596 | <p>Is this possible with a tinymce plugin? I think other ways to access the iframe are not working or not recommended.</p>
<p>I have <a href="https://www.tinymce.com/docs/api/tinymce.dom/tinymce.dom.domquery/" rel="nofollow noreferrer">found this</a> And tried that in the printing mce plugin <a href="https://plugins.trac.wordpress.org/browser/tinymce-advanced/tags/4.4.3/mce/print/plugin.js" rel="nofollow noreferrer">inside the TinyMCE Advanced plugin but it does not work</a>.</p>
<pre><code>var $ = tinymce.dom.DomQuery;
$('p').attr('attr', 'value').addClass('class');
</code></pre>
<p>I have installed the tinymce advanced plugin and tryed adding this lines to the print plugin. The plugin gets executed, the print dialog opens but it just does not to anything to the dom. Does WP has the full version of tinymce?</p>
<pre><code>/**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
tinymce.PluginManager.add('print', function(editor) {
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
editor.addCommand('mcePrint', function() {
editor.getWin().print();
});
editor.addButton('print', {
title: 'Print',
cmd: 'mcePrint'
});
editor.addShortcut('Meta+P', '', 'mcePrint');
editor.addMenuItem('print', {
text: 'Print',
cmd: 'mcePrint',
icon: 'print',
shortcut: 'Meta+P',
context: 'file'
});
});
</code></pre>
| [
{
"answer_id": 262238,
"author": "Abhishek Pandey",
"author_id": 114826,
"author_profile": "https://wordpress.stackexchange.com/users/114826",
"pm_score": 3,
"selected": true,
"text": "<p>Hope You can use fallowing </p>\n\n<pre><code>// Sets class attribute on all paragraphs in the active editor\ntinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass');\n\n// Sets class attribute on a specific element in the current page\ntinymce.dom.setAttrib('mydiv', 'class', 'myclass');\n</code></pre>\n\n<p>or You can add Id by jquery like this</p>\n\n<p><code>$('div').find('p').attr('id', 'myid');</code></p>\n"
},
{
"answer_id": 262243,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>(answer based on the discussion in the comments to the question) Fighting with other plugins for dominance on a global scope is a pointless battle, especially in the context of CSS, that you just can't win. Just because you have an <code>id=\"me\"</code> on the body do not prevent a plugin to have a more specific identification of an element and \"win\" over your your. For example <code>#me p</code> will always lose to <code>#myplugin .content p</code>.</p>\n\n<p>The answer is to use unique class names and be as specific as possible in you style rules.</p>\n\n<p>A different approach is to rely on the customizer to let the user have a (almost) true front end experience while changing shortcodes/settings whatever. Obviously this is not as good as applying style during edit, but there is only so much that can be done as long as wordpress do not have a true front end editing experience.</p>\n\n<p>(the \"breaking\" example was edited due to the discussion in the comments)</p>\n\n<p>And last and not least thought - This approach do not scale in any way as due to the fact that there can be only one value to the ID of the html and body elements, only one plugin can take this approach and if there would be two plugins doing that the result will be chaos.</p>\n"
}
]
| 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260596",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38602/"
]
| Is this possible with a tinymce plugin? I think other ways to access the iframe are not working or not recommended.
I have [found this](https://www.tinymce.com/docs/api/tinymce.dom/tinymce.dom.domquery/) And tried that in the printing mce plugin [inside the TinyMCE Advanced plugin but it does not work](https://plugins.trac.wordpress.org/browser/tinymce-advanced/tags/4.4.3/mce/print/plugin.js).
```
var $ = tinymce.dom.DomQuery;
$('p').attr('attr', 'value').addClass('class');
```
I have installed the tinymce advanced plugin and tryed adding this lines to the print plugin. The plugin gets executed, the print dialog opens but it just does not to anything to the dom. Does WP has the full version of tinymce?
```
/**
* plugin.js
*
* Released under LGPL License.
* Copyright (c) 1999-2015 Ephox Corp. All rights reserved
*
* License: http://www.tinymce.com/license
* Contributing: http://www.tinymce.com/contributing
*/
/*global tinymce:true */
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
tinymce.PluginManager.add('print', function(editor) {
var mce_dom = tinymce.dom.DomQuery;
mce_dom('p').attr('id', 'arve').addClass('arve-html-class');
mce_dom('html').attr('id', 'arve').addClass('arve-html-class');
editor.addCommand('mcePrint', function() {
editor.getWin().print();
});
editor.addButton('print', {
title: 'Print',
cmd: 'mcePrint'
});
editor.addShortcut('Meta+P', '', 'mcePrint');
editor.addMenuItem('print', {
text: 'Print',
cmd: 'mcePrint',
icon: 'print',
shortcut: 'Meta+P',
context: 'file'
});
});
``` | Hope You can use fallowing
```
// Sets class attribute on all paragraphs in the active editor
tinymce.activeEditor.dom.setAttrib(tinymce.activeEditor.dom.select('p'), 'class', 'myclass');
// Sets class attribute on a specific element in the current page
tinymce.dom.setAttrib('mydiv', 'class', 'myclass');
```
or You can add Id by jquery like this
`$('div').find('p').attr('id', 'myid');` |
260,615 | <p>I have on my page section with randomly selected posts via <code>new WP_Query</code>. The problem is that <code>'posts_per_page'</code> attribute don't work. Here is my code:</p>
<pre><code><div id="featured">
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 4,
'nopaging' => true,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div style="table full">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<div class="featcell" style="background: url(<?php the_post_thumbnail_url(); ?>) center center">
<a class="featartlink" href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
</div>
<?php
}
echo '</div>';
wp_reset_postdata();
}
?>
</div>
</code></pre>
<p>The result of script above is that script loading all posts from database. Script is placed under post on single post page. What i doing wrong? It appears that all is OK, but it is not! Thank You for help.</p>
| [
{
"answer_id": 260617,
"author": "X9DESIGN",
"author_id": 84343,
"author_profile": "https://wordpress.stackexchange.com/users/84343",
"pm_score": 1,
"selected": false,
"text": "<p>I dont why, but after some tests i trying to use also <code>get_posts()</code> function and all is works fine now. I just wonder why <code>new WP_Query</code> don't want to work.</p>\n\n<p>Here is the correct code with the use <code>get_posts()</code> function.</p>\n\n<pre><code><div id=\"featured\">\n\n <?php \n\n global $post;\n\n $args = array( \n\n 'post_type' => 'post', \n 'posts_per_page' => 4, \n 'orderby' => 'rand',\n\n );\n\n $rand_posts = get_posts( $args );\n if ( $rand_posts ) : \n\n echo '<div style=\"table full\">';\n\n foreach ( $rand_posts as $post ) : setup_postdata( $post ); ?>\n\n <div class=\"featcell\" style=\"background: url(<?php the_post_thumbnail_url(); ?>) center center\">\n <a class=\"featartlink\" href=\"<?php echo get_permalink(); ?>\"><?php echo get_the_title(); ?></a>\n </div>\n\n <?php endforeach; wp_reset_postdata(); \n\n echo '</div>';\n\n endif;\n\n ?>\n\n</div>\n</code></pre>\n"
},
{
"answer_id": 260618,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p><code>nopaging</code> disables pagination, and <code>posts_per_page</code> is a pagination parameter. You are telling it to ignore pagination and return all posts.</p>\n"
}
]
| 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84343/"
]
| I have on my page section with randomly selected posts via `new WP_Query`. The problem is that `'posts_per_page'` attribute don't work. Here is my code:
```
<div id="featured">
<?php
$args = array(
'post_type' => 'post',
'orderby' => 'rand',
'posts_per_page' => 4,
'nopaging' => true,
);
$the_query = new WP_Query( $args );
if ( $the_query->have_posts() ) {
echo '<div style="table full">';
while ( $the_query->have_posts() ) {
$the_query->the_post();
?>
<div class="featcell" style="background: url(<?php the_post_thumbnail_url(); ?>) center center">
<a class="featartlink" href="<?php echo get_permalink(); ?>"><?php echo get_the_title(); ?></a>
</div>
<?php
}
echo '</div>';
wp_reset_postdata();
}
?>
</div>
```
The result of script above is that script loading all posts from database. Script is placed under post on single post page. What i doing wrong? It appears that all is OK, but it is not! Thank You for help. | `nopaging` disables pagination, and `posts_per_page` is a pagination parameter. You are telling it to ignore pagination and return all posts. |
260,620 | <p>I'm trying to add a CSS class to a comment and everything seems to work if the comment id was hard coded in. However it's not working because I don't know how to get the comment id and then from there, get the comment meta stored in the database.</p>
<p>in <code>wp_commentmeta</code> I have the following data:</p>
<pre><code>meta_id
1
comment_id
10
meta_key
score
meta_value
0.25
</code></pre>
<p>I then have this code using a filter hook to add the class to the list of comment classes. However, this is in a standalone plugin in the /wp-content/plugins folder and I need to loop through all the comments for that post.</p>
<pre><code>function add_comments_class( $classes, $class, $comment_ID, $comment, $post_id ) {
$meta_data = get_comment_meta( $comment_ID, 'score', true );
$meta_data = round((float)$meta_data * 100 );
$classes[] = $meta_data;
return $classes;
} add_filter( 'comment_class', 'add_comments_class' );
</code></pre>
<p>I've looked at <a href="https://codex.wordpress.org/Function_Reference/get_comment_meta" rel="nofollow noreferrer">the Codex</a> but that doesn't seem to identify how to get the ID when viewing a post etc.</p>
<p>The variables in the function were taken from <a href="https://wordpress.stackexchange.com/a/259336/111400">this answer here</a> although it doesn't explain why those specific variables are used or where they are from.</p>
| [
{
"answer_id": 260617,
"author": "X9DESIGN",
"author_id": 84343,
"author_profile": "https://wordpress.stackexchange.com/users/84343",
"pm_score": 1,
"selected": false,
"text": "<p>I dont why, but after some tests i trying to use also <code>get_posts()</code> function and all is works fine now. I just wonder why <code>new WP_Query</code> don't want to work.</p>\n\n<p>Here is the correct code with the use <code>get_posts()</code> function.</p>\n\n<pre><code><div id=\"featured\">\n\n <?php \n\n global $post;\n\n $args = array( \n\n 'post_type' => 'post', \n 'posts_per_page' => 4, \n 'orderby' => 'rand',\n\n );\n\n $rand_posts = get_posts( $args );\n if ( $rand_posts ) : \n\n echo '<div style=\"table full\">';\n\n foreach ( $rand_posts as $post ) : setup_postdata( $post ); ?>\n\n <div class=\"featcell\" style=\"background: url(<?php the_post_thumbnail_url(); ?>) center center\">\n <a class=\"featartlink\" href=\"<?php echo get_permalink(); ?>\"><?php echo get_the_title(); ?></a>\n </div>\n\n <?php endforeach; wp_reset_postdata(); \n\n echo '</div>';\n\n endif;\n\n ?>\n\n</div>\n</code></pre>\n"
},
{
"answer_id": 260618,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p><code>nopaging</code> disables pagination, and <code>posts_per_page</code> is a pagination parameter. You are telling it to ignore pagination and return all posts.</p>\n"
}
]
| 2017/03/19 | [
"https://wordpress.stackexchange.com/questions/260620",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
]
| I'm trying to add a CSS class to a comment and everything seems to work if the comment id was hard coded in. However it's not working because I don't know how to get the comment id and then from there, get the comment meta stored in the database.
in `wp_commentmeta` I have the following data:
```
meta_id
1
comment_id
10
meta_key
score
meta_value
0.25
```
I then have this code using a filter hook to add the class to the list of comment classes. However, this is in a standalone plugin in the /wp-content/plugins folder and I need to loop through all the comments for that post.
```
function add_comments_class( $classes, $class, $comment_ID, $comment, $post_id ) {
$meta_data = get_comment_meta( $comment_ID, 'score', true );
$meta_data = round((float)$meta_data * 100 );
$classes[] = $meta_data;
return $classes;
} add_filter( 'comment_class', 'add_comments_class' );
```
I've looked at [the Codex](https://codex.wordpress.org/Function_Reference/get_comment_meta) but that doesn't seem to identify how to get the ID when viewing a post etc.
The variables in the function were taken from [this answer here](https://wordpress.stackexchange.com/a/259336/111400) although it doesn't explain why those specific variables are used or where they are from. | `nopaging` disables pagination, and `posts_per_page` is a pagination parameter. You are telling it to ignore pagination and return all posts. |
260,652 | <p>I originally installed wordpress in a subdirectory called /blog. Today I decided to change the URL of my site to remove the /blog element from the URL e.g. from www.mywebsite.com/blog to www.mywebsite.com. Here is what I did:</p>
<ol>
<li>went to settings > general and changed the site address:</li>
</ol>
<p>WordPress Address (URL): www.mywebsite.com/blog</p>
<p>Site Address (URL): www.mywebsite.com</p>
<ol start="2">
<li><p>deleted my original homepage (index.html)</p></li>
<li><p>downloaded the index.php file from the /blog directory, and uploaded a copy into the root directory</p></li>
<li><p>opened the index.php file from the root directory and changed the following line of code:</p></li>
</ol>
<p><strike>require( dirname( <strong>FILE</strong> ) . '/wp-blog-header.php' );</strike></p>
<pre><code> require( dirname( __FILE__ ) . '/blog/wp-blog-header.php' );
</code></pre>
<p>This worked in that I now landed directly on my wordpress blog when I typed in www.mywebsite.com, but all my internal links resulted in 404 errors. So I changed my permalinks to plain (e.g. wwww.mywebsite.com/?p=123), which fixed the broken links. However, I prefer to use the post name structure (e.g. wwww.mywebsite.com/name-of-post) so tried to fix this by doing the following:</p>
<ol start="5">
<li><p>created a file called .htaccess in the root directory, and typed in the following code:</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></li>
</ol>
<p>This went horribly wrong, resulting in 500 errors that locked my out of the WP dashboard for some time. I can't remember exactly how I fixed this, but the only other change I made was as follows:</p>
<ol start="6">
<li><p>edited web.config file in /blog directory:</p>
<pre><code><?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress Rule" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>"
</code></pre></li>
</ol>
<p>This still didn't allow post name permalinks, so I set permalinks back to plain. However, I now have a weird situation where about half of my internal links work okay, and the other half result in 404's. I don't really understand how this is possible, as I would have thought it would be all or nothing!</p>
<p>Can anyone please help?</p>
<p>UPDATE - NOW RESOLVED (YAY!):
After struggling to fix this, I contacted the support helpline for the company that provides my web hosting. They said that the fact I was on a windows server was problematic, as it is not really compatible with WordPress. So this is what I / they did:</p>
<ol>
<li>phoned my web host providers and changed to a LINUX server</li>
<li>downloaded the free FTP application FileZilla, and imported all of my wordpress files onto my computer. I then transferred them via FTP to the new LINUX server, into the root directory (public_html).</li>
<li>exported my WordPress database from the old windows server and saved onto my computer. I then created a new database in the new LINUX server and imported the WordPress database (I have to admit something went wrong here, so the support guys ended up doing this for me)</li>
<li>my web host provider then pushed the LINUX site live (again, something went wrong here so another phone call was involved in getting them to fix the problem).</li>
<li>Used the plug-in 'Velvet Blues Update URLs' to update all instances of www.mywebsite.com/blog to www.mywebsite.com in posts, links and attachments (i.e. images were not displayed until I did this)</li>
<li>turned on permalinks and checked it worked</li>
</ol>
<p>This was a bit of a palava, but got there in the end. I'm sure there are much easier ways to achieve this, but I'm posting this solution just so non-technical people like myself realise they can call the helpline for their web hosting platform rather than trying to struggle through.</p>
| [
{
"answer_id": 260656,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update all the links in your database as well</p>\n\n<p>You need to use something like <a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\"><code>Search-Replace-DB</code></a> to accomplish this, <strong>do not modify the database manually</strong></p>\n\n<p>when you use the software, you would try to search for strings like</p>\n\n<p><code>http://www.example.com/blog/</code> and replace it with <code>http://www.example.com/</code></p>\n\n<p>you would also try to find your absolute directory path and update that as well</p>\n\n<p><code>/var/www/mysite/html/blog/</code> to <code>/var/www/mysite/html/</code></p>\n\n<p>you shouldn't have to mess with your template files, or any other PHP file for that matter. But that would be a case specific scenario.</p>\n\n<p><strong>Disclaimer</strong></p>\n\n<p>Be careful and always have a good backup of your DB (and your files) when using <code>Search-Replace-DB</code> messing something in your replace string and you could badly mess up your database... if that happens, just restore your DB backup and try again.</p>\n\n<p><strong>Be sure to delete the folder containing <code>Search-Replace-DB</code> when you're done for security reasons</strong></p>\n"
},
{
"answer_id": 260667,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 1,
"selected": false,
"text": "<p>Please use this query in your Database using PhpMyAdmin </p>\n\n<p><code>UPDATE wp_options SET option_value = REPLACE(option_value, 'oldsite.com', 'newsite.com');\nUPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'oldsite.com', 'newsite.com');\nUPDATE wp_posts SET post_content = REPLACE(post_content, 'oldsite.com', 'newsite.com');\nUPDATE wp_posts SET post_excerpt = REPLACE(post_excerpt, 'oldsite.com', 'newsite.com');\nUPDATE wp_posts SET guid = REPLACE(guid, 'oldsite.com', 'newsite.com');</code></p>\n\n<p>This will change all your URL's to new ones.</p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260652",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115767/"
]
| I originally installed wordpress in a subdirectory called /blog. Today I decided to change the URL of my site to remove the /blog element from the URL e.g. from www.mywebsite.com/blog to www.mywebsite.com. Here is what I did:
1. went to settings > general and changed the site address:
WordPress Address (URL): www.mywebsite.com/blog
Site Address (URL): www.mywebsite.com
2. deleted my original homepage (index.html)
3. downloaded the index.php file from the /blog directory, and uploaded a copy into the root directory
4. opened the index.php file from the root directory and changed the following line of code:
require( dirname( **FILE** ) . '/wp-blog-header.php' );
```
require( dirname( __FILE__ ) . '/blog/wp-blog-header.php' );
```
This worked in that I now landed directly on my wordpress blog when I typed in www.mywebsite.com, but all my internal links resulted in 404 errors. So I changed my permalinks to plain (e.g. wwww.mywebsite.com/?p=123), which fixed the broken links. However, I prefer to use the post name structure (e.g. wwww.mywebsite.com/name-of-post) so tried to fix this by doing the following:
5. created a file called .htaccess in the root directory, and typed in the following 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
```
This went horribly wrong, resulting in 500 errors that locked my out of the WP dashboard for some time. I can't remember exactly how I fixed this, but the only other change I made was as follows:
6. edited web.config file in /blog directory:
```
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="WordPress Rule" stopProcessing="true">
<match url=".*" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
</conditions>
<action type="Rewrite" url="index.php" />
</rule>
</rules>
</rewrite>
</system.webServer>
</configuration>"
```
This still didn't allow post name permalinks, so I set permalinks back to plain. However, I now have a weird situation where about half of my internal links work okay, and the other half result in 404's. I don't really understand how this is possible, as I would have thought it would be all or nothing!
Can anyone please help?
UPDATE - NOW RESOLVED (YAY!):
After struggling to fix this, I contacted the support helpline for the company that provides my web hosting. They said that the fact I was on a windows server was problematic, as it is not really compatible with WordPress. So this is what I / they did:
1. phoned my web host providers and changed to a LINUX server
2. downloaded the free FTP application FileZilla, and imported all of my wordpress files onto my computer. I then transferred them via FTP to the new LINUX server, into the root directory (public\_html).
3. exported my WordPress database from the old windows server and saved onto my computer. I then created a new database in the new LINUX server and imported the WordPress database (I have to admit something went wrong here, so the support guys ended up doing this for me)
4. my web host provider then pushed the LINUX site live (again, something went wrong here so another phone call was involved in getting them to fix the problem).
5. Used the plug-in 'Velvet Blues Update URLs' to update all instances of www.mywebsite.com/blog to www.mywebsite.com in posts, links and attachments (i.e. images were not displayed until I did this)
6. turned on permalinks and checked it worked
This was a bit of a palava, but got there in the end. I'm sure there are much easier ways to achieve this, but I'm posting this solution just so non-technical people like myself realise they can call the helpline for their web hosting platform rather than trying to struggle through. | Please use this query in your Database using PhpMyAdmin
`UPDATE wp_options SET option_value = REPLACE(option_value, 'oldsite.com', 'newsite.com');
UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_excerpt = REPLACE(post_excerpt, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET guid = REPLACE(guid, 'oldsite.com', 'newsite.com');`
This will change all your URL's to new ones. |
260,665 | <p>I am working on custom plugin. I need to insert currency names and symbols in table on plugin activation. Right now my database insertion code is :</p>
<pre><code> global $wpdb;
$table_name1 = $wpdb->prefix . "woo_currency";
$curr_name = array('Dollars', 'Ruble', 'Riel');
$curr_symbol = array('$', 'p.', '៛');
$insert = $wpdb->insert($table_name1,
array(
'name' => $curr_name,
'symbol' => $curr_symbol,
),array('%s', '%s'));
</code></pre>
<p>Everthing is working fine except this database insertion on plugin activation. Have you guys any idea. How to do it?</p>
<p>This code gave me error</p>
<blockquote>
<p>The plugin generated 416 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.</p>
</blockquote>
<p>I want to add <a href="http://blog.smarttutorials.net/2017/01/List-Of-Country-Names-with-Currency-Symbol-SQL-Query-For-MySQL.html" rel="nofollow noreferrer">Currencies name & symbols</a> these all.</p>
| [
{
"answer_id": 260656,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 0,
"selected": false,
"text": "<p>You need to update all the links in your database as well</p>\n\n<p>You need to use something like <a href=\"https://github.com/interconnectit/Search-Replace-DB\" rel=\"nofollow noreferrer\"><code>Search-Replace-DB</code></a> to accomplish this, <strong>do not modify the database manually</strong></p>\n\n<p>when you use the software, you would try to search for strings like</p>\n\n<p><code>http://www.example.com/blog/</code> and replace it with <code>http://www.example.com/</code></p>\n\n<p>you would also try to find your absolute directory path and update that as well</p>\n\n<p><code>/var/www/mysite/html/blog/</code> to <code>/var/www/mysite/html/</code></p>\n\n<p>you shouldn't have to mess with your template files, or any other PHP file for that matter. But that would be a case specific scenario.</p>\n\n<p><strong>Disclaimer</strong></p>\n\n<p>Be careful and always have a good backup of your DB (and your files) when using <code>Search-Replace-DB</code> messing something in your replace string and you could badly mess up your database... if that happens, just restore your DB backup and try again.</p>\n\n<p><strong>Be sure to delete the folder containing <code>Search-Replace-DB</code> when you're done for security reasons</strong></p>\n"
},
{
"answer_id": 260667,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 1,
"selected": false,
"text": "<p>Please use this query in your Database using PhpMyAdmin </p>\n\n<p><code>UPDATE wp_options SET option_value = REPLACE(option_value, 'oldsite.com', 'newsite.com');\nUPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'oldsite.com', 'newsite.com');\nUPDATE wp_posts SET post_content = REPLACE(post_content, 'oldsite.com', 'newsite.com');\nUPDATE wp_posts SET post_excerpt = REPLACE(post_excerpt, 'oldsite.com', 'newsite.com');\nUPDATE wp_posts SET guid = REPLACE(guid, 'oldsite.com', 'newsite.com');</code></p>\n\n<p>This will change all your URL's to new ones.</p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260665",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/88892/"
]
| I am working on custom plugin. I need to insert currency names and symbols in table on plugin activation. Right now my database insertion code is :
```
global $wpdb;
$table_name1 = $wpdb->prefix . "woo_currency";
$curr_name = array('Dollars', 'Ruble', 'Riel');
$curr_symbol = array('$', 'p.', '៛');
$insert = $wpdb->insert($table_name1,
array(
'name' => $curr_name,
'symbol' => $curr_symbol,
),array('%s', '%s'));
```
Everthing is working fine except this database insertion on plugin activation. Have you guys any idea. How to do it?
This code gave me error
>
> The plugin generated 416 characters of unexpected output during activation. If you notice “headers already sent” messages, problems with syndication feeds or other issues, try deactivating or removing this plugin.
>
>
>
I want to add [Currencies name & symbols](http://blog.smarttutorials.net/2017/01/List-Of-Country-Names-with-Currency-Symbol-SQL-Query-For-MySQL.html) these all. | Please use this query in your Database using PhpMyAdmin
`UPDATE wp_options SET option_value = REPLACE(option_value, 'oldsite.com', 'newsite.com');
UPDATE wp_postmeta SET meta_value = REPLACE(meta_value, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_content = REPLACE(post_content, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET post_excerpt = REPLACE(post_excerpt, 'oldsite.com', 'newsite.com');
UPDATE wp_posts SET guid = REPLACE(guid, 'oldsite.com', 'newsite.com');`
This will change all your URL's to new ones. |
260,669 | <p>I would like to limit the +New admin menu to only show the single sub menu Event ("Veranstaltung").
Basically the users are allowed to create other items as well but not from that +New menu. </p>
<p><a href="https://i.stack.imgur.com/mNFRB.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/mNFRB.png" alt="+New Admin Menu"></a></p>
<p>I already tried it with "Adminimize" plugin as this can remove the other items but it will leave the new media link intact once you click directly "+New". </p>
<p><a href="https://i.stack.imgur.com/DENRg.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DENRg.png" alt="+New Admin Menu - link still there"></a></p>
<p>I already added some other logic to remove items from the left admin menu like:</p>
<pre><code>function remove_menus() {
remove_menu_page('edit.php?post_type=mdocs-posts');
}
add_action('admin_menu', 'remove_menus');
</code></pre>
<p>But I can't get how to modify the +New. Any hints? </p>
<p>Thank you!</p>
| [
{
"answer_id": 260671,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 4,
"selected": true,
"text": "<p><strong>To hide everything (menu and submenu)-</strong></p>\n\n<pre><code>function wpse_260669_remove_new_content(){\n global $wp_admin_bar;\n $wp_admin_bar->remove_menu( 'new-content' );\n}\nadd_action( 'wp_before_admin_bar_render', 'wpse_260669_remove_new_content' );\n</code></pre>\n\n<p><strong>To hide specific menu/submenu item(s)-</strong></p>\n\n<pre><code>function wpse_260669_remove_new_content_items(){\n global $wp_admin_bar;\n $wp_admin_bar->remove_menu( 'new-post' ); // hides post CPT\n $wp_admin_bar->remove_menu( 'new-product' ); // hides product CPT\n $wp_admin_bar->remove_menu( 'new-page' ); // hides page CPT\n $wp_admin_bar->remove_menu( 'new-media' ); // hides media\n}\nadd_action( 'wp_before_admin_bar_render', 'wpse_260669_remove_new_content_items' );\n</code></pre>\n\n<p><strong>So, the basic rule is-</strong></p>\n\n<pre><code>function your_boo_bar_function() {\n global $wp_admin_bar;\n $wp_admin_bar->remove_menu( 'your-unique-menu-id' );\n}\nadd_action( 'wp_before_admin_bar_render', 'your_boo_bar_function' );\n</code></pre>\n\n<p><strong>Add a new menu-</strong></p>\n\n<pre><code>function wpse_260669_add_menu(){\n global $wp_admin_bar;\n $wp_admin_bar->add_node(\n array(\n 'id' => 'google-menu',\n 'title' => 'Google',\n 'href' => 'http://google.com',\n 'parent' => 'new-content', // so, it'll be set as a child of 'new-content'. remove this to use this as a parent menu\n 'meta' => array( 'class' => 'my-custom-class' ),\n )\n );\n\n}\nadd_action( 'wp_before_admin_bar_render', 'wpse_260669_add_menu' );\n</code></pre>\n\n<p><strong>Update an existing menu-</strong></p>\n\n<p>If you want to update an existing menu item, just add a new item using the ID of your desired menu.</p>\n\n<p>To update +New ('content-new'), use this code-</p>\n\n<pre><code>function wpse_260669_update_menu(){\n global $wp_admin_bar;\n $wp_admin_bar->add_node(\n array(\n 'id' => 'new-content', // id of an existing menu\n 'href' => 'your_new_url_goes_here', // set new URL\n )\n );\n\n}\nadd_action( 'wp_before_admin_bar_render', 'wpse_260669_update_menu' );\n</code></pre>\n\n<p><strong>How to get menu ID-</strong></p>\n\n<p>The easiest way is to inspect element with Firebug and take the ID. See this screenshot-</p>\n\n<p><a href=\"https://i.stack.imgur.com/X4DMA.jpg\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/X4DMA.jpg\" alt=\"How to get menu ID\"></a></p>\n\n<p>Navigate to your desired menu item and get the string next to <code>wp-admin-bar-</code></p>\n"
},
{
"answer_id": 260719,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 1,
"selected": false,
"text": "<p>To follow up on @mukto90's answer, the following adds a menu to the toolbar that lists the node id (what you need to pass to <code>$wp_admin_bar->remove_node()</code>) of all <em>other</em> nodes in the toolbar.</p>\n\n<pre><code>add_action ('wp_before_admin_bar_render', 'add_all_node_ids_to_toolbar'), 99999) ;\n\nfunction\nadd_all_node_ids_to_toolbar ()\n{\n global $wp_admin_bar ;\n\n if (!current_user_can ('manage_options')) {\n // allow only \"admins\" to have our menu\n return ;\n }\n\n $all_toolbar_nodes = $wp_admin_bar->get_nodes () ;\n\n if (empty ($all_toolbar_nodes)) {\n // there are no top-level nodes, so bail\n return ;\n }\n\n // add our top-level menu to the toolbar\n $our_node_id = 'node_ids' ;\n $args = array (\n 'id' => $our_node_id,\n 'title' => \"Node ID's\",\n ) ;\n $wp_admin_bar->add_node ($args) ;\n\n // add all current Toolbar items to their parent node or to our top-level menu\n foreach ($all_toolbar_nodes as $node) {\n $args = array (\n 'id' => \"{$our_node_id}_{$node->id}\", // prefix id with \"node_id_\" to make it a unique id\n 'title' => $node->id,\n ) ;\n\n if (!(isset ($node->parent) && $node->parent)) {\n // the node has no parent, so add it to our top-level menu\n $args['parent'] = $our_node_id ;\n }\n else {\n // the node has a parent, so add it as a child to appropriate node in our menu\n $args['parent'] = \"{$our_node_id}_{$node->parent}\" ;\n }\n\n $wp_admin_bar->add_node ($args) ;\n }\n\n return ;\n}\n</code></pre>\n"
},
{
"answer_id": 260724,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 1,
"selected": false,
"text": "<p>Another approach is to take advantage of the <code>show_in_admin_bar</code> property of post types. When post types are registered (both built-ins and custom post types) they declare whether they \"want\" to be included in the \"New\" toolbar menu, ala</p>\n\n<pre><code>$args = array (\n 'show_in_admin_bar' => true|false,\n ) ;\nregister_post_type ('post_type_name', $args) ;\n</code></pre>\n\n<p>So, for CPTs you register, if you don't want them to appear in the \"New\" toolbar menu, just set <code>'show_in_admin_bar' => false,</code>. If <code>show_in_admin_bar</code> is not specified in <code>$args</code>, then it defaults to the value of <code>show_in_menu</code>. See <a href=\"https://developer.wordpress.org/reference/functions/register_post_type/\" rel=\"nofollow noreferrer\">register_post_type()</a> for details.</p>\n\n<p>How about the built-ins? You can remove those that you don't want with the following:</p>\n\n<pre><code>add_action ('wp_before_admin_bar_render', 'remove_from_toolbar_new') ;\n\nfunction\nremove_from_toolbar_new ()\n{\n $allow_in_toolbar_new = array (\n 'page', // if you don't want any built-ins, just make this an empty array\n ) ;\n\n $args = array (\n '_builtin' => true,\n 'show_in_admin_bar' => true,\n ) ;\n foreach (get_post_types ($args, 'objects') as $post_type) {\n if (in_array ($post_type->name, $allow_in_toolbar_new)) {\n continue ;\n }\n\n $post_type->set_props (array ('show_in_admin_bar' => false)) ;\n }\n\n return ;\n}\n</code></pre>\n\n<p>See <a href=\"https://developer.wordpress.org/reference/functions/get_post_types/\" rel=\"nofollow noreferrer\">get_post_types()</a> and <a href=\"https://developer.wordpress.org/reference/classes/wp_post_type/set_props/\" rel=\"nofollow noreferrer\">WP_Post_Type::set_props()</a> for details.</p>\n\n<p>As far as I know, the only way to remove the \"Users\" item from the \"New\" toolbar menu is with the technique that @mukto90 mentions.</p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260669",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115781/"
]
| I would like to limit the +New admin menu to only show the single sub menu Event ("Veranstaltung").
Basically the users are allowed to create other items as well but not from that +New menu.
[](https://i.stack.imgur.com/mNFRB.png)
I already tried it with "Adminimize" plugin as this can remove the other items but it will leave the new media link intact once you click directly "+New".
[](https://i.stack.imgur.com/DENRg.png)
I already added some other logic to remove items from the left admin menu like:
```
function remove_menus() {
remove_menu_page('edit.php?post_type=mdocs-posts');
}
add_action('admin_menu', 'remove_menus');
```
But I can't get how to modify the +New. Any hints?
Thank you! | **To hide everything (menu and submenu)-**
```
function wpse_260669_remove_new_content(){
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'new-content' );
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_remove_new_content' );
```
**To hide specific menu/submenu item(s)-**
```
function wpse_260669_remove_new_content_items(){
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'new-post' ); // hides post CPT
$wp_admin_bar->remove_menu( 'new-product' ); // hides product CPT
$wp_admin_bar->remove_menu( 'new-page' ); // hides page CPT
$wp_admin_bar->remove_menu( 'new-media' ); // hides media
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_remove_new_content_items' );
```
**So, the basic rule is-**
```
function your_boo_bar_function() {
global $wp_admin_bar;
$wp_admin_bar->remove_menu( 'your-unique-menu-id' );
}
add_action( 'wp_before_admin_bar_render', 'your_boo_bar_function' );
```
**Add a new menu-**
```
function wpse_260669_add_menu(){
global $wp_admin_bar;
$wp_admin_bar->add_node(
array(
'id' => 'google-menu',
'title' => 'Google',
'href' => 'http://google.com',
'parent' => 'new-content', // so, it'll be set as a child of 'new-content'. remove this to use this as a parent menu
'meta' => array( 'class' => 'my-custom-class' ),
)
);
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_add_menu' );
```
**Update an existing menu-**
If you want to update an existing menu item, just add a new item using the ID of your desired menu.
To update +New ('content-new'), use this code-
```
function wpse_260669_update_menu(){
global $wp_admin_bar;
$wp_admin_bar->add_node(
array(
'id' => 'new-content', // id of an existing menu
'href' => 'your_new_url_goes_here', // set new URL
)
);
}
add_action( 'wp_before_admin_bar_render', 'wpse_260669_update_menu' );
```
**How to get menu ID-**
The easiest way is to inspect element with Firebug and take the ID. See this screenshot-
[](https://i.stack.imgur.com/X4DMA.jpg)
Navigate to your desired menu item and get the string next to `wp-admin-bar-` |
260,678 | <p>I have "Color Filters for WooCommerce" plugin and "color" taxonomy.</p>
<p>Each taxonomy have one custom field - color picker.</p>
<p>I want to display on archive page current color picker value of each product's.</p>
<p>I can call </p>
<pre><code>get_option( 'nm_taxonomy_colors' );
</code></pre>
<p>And I'll get all values from this field, but I need only current.</p>
<p>This plugin have <a href="https://www.elementous.com/documentation/color-filters-for-woocommerce/modifications-and-development/" rel="nofollow noreferrer">doc</a>, but I don't know how I can use this filters</p>
<pre><code>elm_cf_get_terms_args
elm_cf_color_style_attribute
</code></pre>
| [
{
"answer_id": 260711,
"author": "1naveengiri",
"author_id": 114894,
"author_profile": "https://wordpress.stackexchange.com/users/114894",
"pm_score": 0,
"selected": false,
"text": "<p>you can use it like this.</p>\n\n<pre><code>$saved_colors = get_option( 'nm_taxonomy_colors' );\n//just use current term_id here.\n$color = @$saved_colors[$current_term_id];\necho $color //anywhere you want on single product page.\n</code></pre>\n"
},
{
"answer_id": 260721,
"author": "Frunky",
"author_id": 98449,
"author_profile": "https://wordpress.stackexchange.com/users/98449",
"pm_score": 1,
"selected": false,
"text": "<p>The author of plugin help me with that. Thanks all.</p>\n\n<pre><code>global $post;\n $product_colors = get_the_terms( $post, 'product_color' );\n $saved_colors = get_option( 'nm_taxonomy_colors' );\n\n if(isset($product_colors) && is_array($product_colors)){\n foreach($product_colors as $color){\n $term_id = $color->term_id;\n\n $hex_code = $saved_colors[$term_id];\n\n echo $hex_code . '<br />';\n }\n }\n</code></pre>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260678",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/98449/"
]
| I have "Color Filters for WooCommerce" plugin and "color" taxonomy.
Each taxonomy have one custom field - color picker.
I want to display on archive page current color picker value of each product's.
I can call
```
get_option( 'nm_taxonomy_colors' );
```
And I'll get all values from this field, but I need only current.
This plugin have [doc](https://www.elementous.com/documentation/color-filters-for-woocommerce/modifications-and-development/), but I don't know how I can use this filters
```
elm_cf_get_terms_args
elm_cf_color_style_attribute
``` | The author of plugin help me with that. Thanks all.
```
global $post;
$product_colors = get_the_terms( $post, 'product_color' );
$saved_colors = get_option( 'nm_taxonomy_colors' );
if(isset($product_colors) && is_array($product_colors)){
foreach($product_colors as $color){
$term_id = $color->term_id;
$hex_code = $saved_colors[$term_id];
echo $hex_code . '<br />';
}
}
``` |
260,682 | <p>Hi I am using a Ubuntu system. I am using a shell script to download wordpress from wget, update config and run it from nginx server. </p>
<p>Now I want to update this shell script so that when we install a fresh copy of WordPress, I get some plugins pre-installed.
So I installed wp-cli and ran the command</p>
<pre><code>wp plugin install w3-total-cache --activate --allow-root
</code></pre>
<p>This command says the plugin has been activated successfully. But when I go to the site URL in the plugins section, it gives the following error</p>
<p><code>The plugin w3-total-cache/w3-total-cache.php has been deactivated due to an error: Plugin file does not exist.</code></p>
<p>This is true for any plugin that I try to install.</p>
<p>When I go to the plugins folder inside wp-content, I can see that plugin files exist. But still I get the error. </p>
<p>How to resolve this. Please help </p>
| [
{
"answer_id": 260691,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Caching plugins usually require some additional manual work in moving some files from the plugin directory to the root of the <code>wp-content</code> directory and maybe some <code>wp-config.php</code> changes. It is possible that the plugin fails to initialize due to that.</p>\n"
},
{
"answer_id": 386658,
"author": "thomasberends",
"author_id": 204945,
"author_profile": "https://wordpress.stackexchange.com/users/204945",
"pm_score": 0,
"selected": false,
"text": "<p>I've had this exact issue, and I found the very specific issue.</p>\n<p>WP-CLI was running in another directory (with another Wordpress installation) which pointed to the same database.</p>\n<p>What happens:</p>\n<ol>\n<li>WP-CLI succesfully executes the command on the wrong Wordpress installation</li>\n<li>You then open the correct Wordpress installation, and go to Plugins.</li>\n<li>That installation cannot find the file so it deactivates the plugin.</li>\n</ol>\n<p>The issue for me was caused by using a setup script which used the --path= option, and this path was wrong. The setup script fully installed Wordpress in the wrong directory with the same database credentials.</p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115798/"
]
| Hi I am using a Ubuntu system. I am using a shell script to download wordpress from wget, update config and run it from nginx server.
Now I want to update this shell script so that when we install a fresh copy of WordPress, I get some plugins pre-installed.
So I installed wp-cli and ran the command
```
wp plugin install w3-total-cache --activate --allow-root
```
This command says the plugin has been activated successfully. But when I go to the site URL in the plugins section, it gives the following error
`The plugin w3-total-cache/w3-total-cache.php has been deactivated due to an error: Plugin file does not exist.`
This is true for any plugin that I try to install.
When I go to the plugins folder inside wp-content, I can see that plugin files exist. But still I get the error.
How to resolve this. Please help | Caching plugins usually require some additional manual work in moving some files from the plugin directory to the root of the `wp-content` directory and maybe some `wp-config.php` changes. It is possible that the plugin fails to initialize due to that. |
260,701 | <p>In my theme, jQuery is loaded in the header by default. I even dequed it in my <code>functions.php</code> but still in the header I have the jquery : </p>
<pre><code>function remove_jquery_migrate( &$scripts){
if(!is_admin()){
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1' );
}
}
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
</code></pre>
<p>but this is printed in the header: </p>
<pre><code><script type='text/javascript' src='...wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
</code></pre>
<p>I don't know if a plugin is causing this but I want to remove this as I am already loading the jquery using Google CDN in the footer. </p>
| [
{
"answer_id": 260704,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 2,
"selected": true,
"text": "<p>An example on how to deregister a WordPress built-in library and load your own:</p>\n\n<pre><code>function load_custom_scripts() {\n wp_deregister_script( 'jquery' );\n wp_register_script('jquery', '//code.jquery.com/jquery-2.2.4.min.js', array(), '2.2.4', true); // true will place script in the footer\n wp_enqueue_script( 'jquery' );\n}\nif(!is_admin()) {\n add_action('wp_enqueue_scripts', 'load_custom_scripts', 99);\n}\n</code></pre>\n"
},
{
"answer_id": 260708,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 0,
"selected": false,
"text": "<p>First of all: is your Google jquery <a href=\"https://developer.wordpress.org/reference/functions/wp_enqueue_script/\" rel=\"nofollow noreferrer\">enqueued properly</a>? If you just dump the script link in the footer, WP won't know jquery is loaded and plugins that need it will enqueue it regardless of whether you dequeued it in your theme.</p>\n\n<p>Secondly, are you sure you are enqueueing <a href=\"https://wordpress.stackexchange.com/questions/244537/why-does-wordpress-use-outdated-jquery-v1-12-4/244543#244543\">the right jquery version</a>? If you enqueue an older version of jquery, a smart plugin might detect that and enqueue a later version to make itself work.</p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115810/"
]
| In my theme, jQuery is loaded in the header by default. I even dequed it in my `functions.php` but still in the header I have the jquery :
```
function remove_jquery_migrate( &$scripts){
if(!is_admin()){
$scripts->remove( 'jquery');
$scripts->add( 'jquery', false, array( 'jquery-core' ), '1.2.1' );
}
}
add_filter( 'wp_default_scripts', 'remove_jquery_migrate' );
function wpdocs_dequeue_script() {
wp_dequeue_script( 'jquery' );
}
add_action( 'wp_print_scripts', 'wpdocs_dequeue_script', 100 );
```
but this is printed in the header:
```
<script type='text/javascript' src='...wp-includes/js/jquery/jquery.js?ver=1.12.4'></script>
```
I don't know if a plugin is causing this but I want to remove this as I am already loading the jquery using Google CDN in the footer. | An example on how to deregister a WordPress built-in library and load your own:
```
function load_custom_scripts() {
wp_deregister_script( 'jquery' );
wp_register_script('jquery', '//code.jquery.com/jquery-2.2.4.min.js', array(), '2.2.4', true); // true will place script in the footer
wp_enqueue_script( 'jquery' );
}
if(!is_admin()) {
add_action('wp_enqueue_scripts', 'load_custom_scripts', 99);
}
``` |
260,713 | <p>Working on a site that has a lot of posts, I need to display 3 posts from a particular category, but all of them need to be from the latest 10 published on the site. I can either grab 3 completely random posts (which tends to pull posts that are very old) or grab 10 posts (but I don't know how to then randomize the order and only display 3).</p>
<p>So far, I have this query:</p>
<pre><code>$args = array(
'post_type' => 'post',
'category_name' => 'mycategory',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
'meta_key' => '_thumbnail_id',
'no_found_rows' => 'true'
);
$query = new WP_Query( $args );
</code></pre>
<p>along with this attempt to get 3 random posts from the 10 queried:</p>
<pre><code>$randomPosts = shuffle( $query );
$randomPosts = array_slice( $randomPosts, 0, 3 );
</code></pre>
<p>But treating the results as an array doesn't work, since it's actually an object.<br />
My only other thought is to use <code>'posts_per_page' = 3</code> with <code>'orderby' => 'rand'</code> to grab 3 random posts and add a <code>'date_query'</code> to restrict it to the past 6 months. That would be close, but it would be preferable to restrict the query to the 10 most recent posts (they may all be published 3 days ago or 5 months ago, they are published together in uneven spurts).</p>
<p>What is the best approach?<br />
Query the 10 latest posts as I'm doing, then convert the object to an array, shuffle, and slice, and convert it back to an object, or is there a simpler, more efficient way to accomplish the goal?</p>
| [
{
"answer_id": 260720,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 5,
"selected": true,
"text": "<p>There's one way with:</p>\n\n<pre><code>$args = [\n 'post_type' => 'post',\n 'posts_per_page' => 10,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'no_found_rows' => 'true',\n '_shuffle_and_pick' => 3 // <-- our custom argument\n];\n\n$query = new \\WP_Query( $args );\n</code></pre>\n\n<p>where the custom <code>_shuffle_and_pick</code> attribute is supported by this demo plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Support for the _shuffle_and_pick WP_Query argument.\n */\nadd_filter( 'the_posts', function( $posts, \\WP_Query $query )\n{\n if( $pick = $query->get( '_shuffle_and_pick' ) )\n {\n shuffle( $posts );\n $posts = array_slice( $posts, 0, (int) $pick );\n }\n return $posts;\n}, 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 260877,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": false,
"text": "<p>You can obviously take all the posts and randomize the result with PHP <a href=\"https://wordpress.stackexchange.com/a/260720/110572\">like shown in this answer</a>. Or, you can do the randomization with SQL as well.</p>\n\n<h2>Handling the randomization in Database:</h2>\n\n<p>There is no built in WordPress function (or argument) to achieve that, however, you may use the <code>posts_request</code> filter to alter the original SQL query set by <code>WP_Query</code> to achieve the randomization from the database alone.</p>\n\n<p>You may use the following CODE in the active theme's <code>functions.php</code> file or as a new custom plugin:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Randomize Posts\n * Plugin URI: https://wordpress.stackexchange.com/a/260877/110572\n * Description: Randomize posts basd on '_randomize_posts_count' query argument\n * Author: Fayaz\n * Version: 1.0\n * Author URI: http://fmy.me/\n */\n\nfunction wpse260713_randomize_posts( $sql_query, $query ) {\n $rand = (int) $query->get( '_randomize_posts_count' );\n if( $rand ) {\n $found_rows = '';\n if( stripos( $sql_query, 'SQL_CALC_FOUND_ROWS' ) !== FALSE ) {\n $found_rows = 'SQL_CALC_FOUND_ROWS';\n $sql_query = str_replace( 'SQL_CALC_FOUND_ROWS ', '', $sql_query );\n }\n $sql_query = sprintf( 'SELECT %s wp_posts.* from ( %s ) wp_posts ORDER BY rand() LIMIT %d', $found_rows, $sql_query, $rand );\n }\n return $sql_query;\n}\nadd_filter( 'posts_request', 'wpse260713_randomize_posts', 10, 2 );\n</code></pre>\n\n<p>Then you may use the query as follows:</p>\n\n<pre><code>$args = array(\n 'post_type' => 'post',\n 'posts_per_page' => 10,\n 'orderby' => 'date',\n 'order' => 'DESC',\n 'meta_key' => '_thumbnail_id',\n 'no_found_rows' => 'true',\n '_randomize_posts_count' => 3\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<h2>Comparative analysis:</h2>\n\n<ul>\n<li><p>This method will bring only the maximum number of posts defined by <code>_randomize_posts_count</code> from the database, as opposed to bringing all the results and randomizing on the PHP end. So it's better optimized for data communication with the database. This is better if your database server is separate from your web server.</p></li>\n<li><p><strong>If query cache is not enabled</strong>, then this solution will be much faster when the difference between the number of random posts shown vs. total posts selection is big. For example: if you are showing 3 random posts from most recent 200 posts, then this method will be a lot faster.</p></li>\n<li><p><strong>If query cache is enabled</strong>, then <a href=\"https://wordpress.stackexchange.com/a/260720/110572\">Birgire's method</a> will be faster as it'll avoid later SQL requests. However, for bigger sample size it may still be slower since you'll have to store a lot of information in the query cache.</p></li>\n<li><p>Best if you consider the sample size carefully and select the solution that suits your use case better.</p></li>\n</ul>\n\n<blockquote>\n <p><strong>Note:</strong> Random methods are very slow (and often non-scalable) compared to general CODE, so no matter what method you choose, be extra cautious when your sample size of randomisation is considerably large (like thousands). </p>\n</blockquote>\n"
},
{
"answer_id": 260908,
"author": "CK MacLeod",
"author_id": 35923,
"author_profile": "https://wordpress.stackexchange.com/users/35923",
"pm_score": 2,
"selected": false,
"text": "<p>Great work by Fayaz and birgire - much more expert than I might have come up with - but I think there is an easier way, unless I don't understand the question (quite possible!): 1) use get_posts() or, easiest, wp_get_recent_posts(), both of which return arrays by default, accept WP Query $args, and also use no_found_rows=true by default, 2) shuffle the array, 3) then slice off three.</p>\n\n<p>That's how I solved a problem similar to this one for myself, at a point at which I understood close to nothing, as compared to my current state of understanding how close to nothing I understood then. However, birgire and Fayaz's code is cool, so please feel free to go with one or the other!</p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260713",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102815/"
]
| Working on a site that has a lot of posts, I need to display 3 posts from a particular category, but all of them need to be from the latest 10 published on the site. I can either grab 3 completely random posts (which tends to pull posts that are very old) or grab 10 posts (but I don't know how to then randomize the order and only display 3).
So far, I have this query:
```
$args = array(
'post_type' => 'post',
'category_name' => 'mycategory',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
'meta_key' => '_thumbnail_id',
'no_found_rows' => 'true'
);
$query = new WP_Query( $args );
```
along with this attempt to get 3 random posts from the 10 queried:
```
$randomPosts = shuffle( $query );
$randomPosts = array_slice( $randomPosts, 0, 3 );
```
But treating the results as an array doesn't work, since it's actually an object.
My only other thought is to use `'posts_per_page' = 3` with `'orderby' => 'rand'` to grab 3 random posts and add a `'date_query'` to restrict it to the past 6 months. That would be close, but it would be preferable to restrict the query to the 10 most recent posts (they may all be published 3 days ago or 5 months ago, they are published together in uneven spurts).
What is the best approach?
Query the 10 latest posts as I'm doing, then convert the object to an array, shuffle, and slice, and convert it back to an object, or is there a simpler, more efficient way to accomplish the goal? | There's one way with:
```
$args = [
'post_type' => 'post',
'posts_per_page' => 10,
'orderby' => 'date',
'order' => 'DESC',
'no_found_rows' => 'true',
'_shuffle_and_pick' => 3 // <-- our custom argument
];
$query = new \WP_Query( $args );
```
where the custom `_shuffle_and_pick` attribute is supported by this demo plugin:
```
<?php
/**
* Plugin Name: Support for the _shuffle_and_pick WP_Query argument.
*/
add_filter( 'the_posts', function( $posts, \WP_Query $query )
{
if( $pick = $query->get( '_shuffle_and_pick' ) )
{
shuffle( $posts );
$posts = array_slice( $posts, 0, (int) $pick );
}
return $posts;
}, 10, 2 );
``` |
260,739 | <pre><code>$args = array(
//'post_type' => 'article',
'posts_per_page' => 5,
'category' => 'starter',
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query($args);
while($query->have_posts()){
the_content();
}
</code></pre>
| [
{
"answer_id": 260742,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 1,
"selected": false,
"text": "<p>Your question is <strong>very</strong> unclear (given that you don't actually ask a question), but there are 2 problems with your code, both of which are corrected below:</p>\n\n<pre><code> $args = array (\n //'post_type' => 'article',\n 'posts_per_page' => 5,\n 'category_name' => 'starter', // changed from 'category' to 'category_name'\n 'meta_query' => array (\n array (\n 'key' => 'recommended_article',\n 'value' => '1',\n 'compare' => '=', // changed from '==' to '='\n ),\n ),\n ) ;\n$query = new WP_Query ($args) ;\nwhile ($query->have_posts ()) {\n the_content () ;\n }\n</code></pre>\n\n<p>For the details of <em>why</em> these changes are necessary, see <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters\" rel=\"nofollow noreferrer\">WP_Query, Category Parameters</a> and <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters\" rel=\"nofollow noreferrer\">WP_Query, Custom Field Parameters</a>.</p>\n"
},
{
"answer_id": 305503,
"author": "Kishan Chauhan",
"author_id": 63564,
"author_profile": "https://wordpress.stackexchange.com/users/63564",
"pm_score": 0,
"selected": false,
"text": "<p>I have try this way and worked for me</p>\n\n<pre><code>$terms = get_terms( array(\n 'taxonomy' => 'category',\n 'hide_empty' => true,\n 'orderby'=> 'name',\n 'order'=>'ASC'\n ));\n\n foreach( $terms as $term){\n $termChildren = get_term_children($term->term_id, 'category');\n $args = array('post_type' => 'mycustompost',\n 'post_status' => 'publish',\n 'posts_per_page' => '-1',\n 'orderby' => 'ID',\n 'order' => 'ASC',\n 'tax_query' => array(\n array(\n 'taxonomy' => 'category',\n 'field' => 'slug',\n 'terms' => $term->slug\n ), \n )\n );\n $query = new WP_Query($args);\n while ($query->have_posts()): $query->the_post();\n the_title(); the_content();\n endwhile;\n }\n</code></pre>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115834/"
]
| ```
$args = array(
//'post_type' => 'article',
'posts_per_page' => 5,
'category' => 'starter',
'meta_query' => array(
array(
'key' => 'recommended_article',
'value' => '1',
'compare' => '=='
)
)
);
$query = new WP_Query($args);
while($query->have_posts()){
the_content();
}
``` | Your question is **very** unclear (given that you don't actually ask a question), but there are 2 problems with your code, both of which are corrected below:
```
$args = array (
//'post_type' => 'article',
'posts_per_page' => 5,
'category_name' => 'starter', // changed from 'category' to 'category_name'
'meta_query' => array (
array (
'key' => 'recommended_article',
'value' => '1',
'compare' => '=', // changed from '==' to '='
),
),
) ;
$query = new WP_Query ($args) ;
while ($query->have_posts ()) {
the_content () ;
}
```
For the details of *why* these changes are necessary, see [WP\_Query, Category Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Category_Parameters) and [WP\_Query, Custom Field Parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Custom_Field_Parameters). |
260,756 | <p>Does anyone know how I would automatically add <code><div class="table-responsive"></code> before every instance of a <code><table></code> on a WordPress site using filter referencing? I would also need to add a <code></div></code> to every instance of <code></table></code> as well.</p>
| [
{
"answer_id": 260758,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 2,
"selected": false,
"text": "<p>You can filter <code>the_content</code> and use <code>preg_replace()</code> to look for instances of <code><table></table></code> and then surround them with your <code><div></code>.</p>\n\n<pre><code>add_action( 'the_content', 'wpse_260756_the_content', 10, 1 );\nfunction wpse_260756_the_content( $content ) {\n $pattern = \"/<table(.*?)>(.*?)<\\/table>/i\";\n $replacement = '<div class=\"table-responsive\"><table$1>$2</table></div>';\n\n return preg_replace( $pattern, $replacement, $content );\n}\n</code></pre>\n"
},
{
"answer_id": 365108,
"author": "Karthick",
"author_id": 186872,
"author_profile": "https://wordpress.stackexchange.com/users/186872",
"pm_score": 0,
"selected": false,
"text": "<p>Will this work for you? Make sure to enable jQuery before execute it.</p>\n\n<pre><code><?php add_action( 'wp_footer', 'add_js_to_wp_footer' );\nfunction add_js_to_wp_footer(){ ?>\n<script type=\"text/javascript\">\n$(function() {\n $('table').wrap('<div class=\"table-responsive\"></div>');\n})\n</script>\n<?php } ?>\n</code></pre>\n"
},
{
"answer_id": 414320,
"author": "Devendra",
"author_id": 230452,
"author_profile": "https://wordpress.stackexchange.com/users/230452",
"pm_score": 0,
"selected": false,
"text": "<p>I'm assuming you want this type of behavior to set a horizontal scroll onto the table.</p>\n<p>If that was the case then here's what you can do.</p>\n<pre><code><div class="w-[200px] overflow-hidden">\n <!-- \n # Hack: Apply styles directly on the table.\n\n .table {\n display: block;\n overflow: auto;\n }\n -->\n <table class="table">\n <tbody>\n <tr>\n <td>+xx xxxxxxxxxx</td>\n <td>+xx xxxxxxxxxx</td>\n <td>+xx xxxxxxxxxx</td>\n </tr>\n </tbody>\n </table>\n</div>\n</code></pre>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260756",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94729/"
]
| Does anyone know how I would automatically add `<div class="table-responsive">` before every instance of a `<table>` on a WordPress site using filter referencing? I would also need to add a `</div>` to every instance of `</table>` as well. | You can filter `the_content` and use `preg_replace()` to look for instances of `<table></table>` and then surround them with your `<div>`.
```
add_action( 'the_content', 'wpse_260756_the_content', 10, 1 );
function wpse_260756_the_content( $content ) {
$pattern = "/<table(.*?)>(.*?)<\/table>/i";
$replacement = '<div class="table-responsive"><table$1>$2</table></div>';
return preg_replace( $pattern, $replacement, $content );
}
``` |
260,773 | <p>I'm inexperienced with ajax. I'm building a form that will allow the user to grab a custom post type from the first field that will return the value of the post ID. Then, I'd like ajax to take that post ID and build a second dropdown based on some custom fields for that post. </p>
<p>Here's what I have so far, which was adapted from the first answer on this question: <a href="https://wordpress.stackexchange.com/questions/177141/filter-a-second-dropdown-list-when-a-value-is-chosen-in-the-first-one">Filter a second dropdown list when a value is chosen in the first one</a></p>
<p>In functions.php:</p>
<pre><code>if ( is_admin() ) {
add_action( 'wp_ajax_dynamic_dropdown', 'dynamic_dropdown_func' );
add_action( 'wp_ajax_nopriv_dynamic_dropdown', 'dynamic_dropdown_func' );
}
function dynamic_dropdown_func () {
global $wpdb;
if (isset($_POST['event'])) {
$event_id = $_POST['event'];
$first = get_field('first_day',$event_id);
$last = get_field('last_day',$event_id);
$event_dates = '<option value="" disabled selected>Choose Date</option>';
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
while($first<$last) :
$first = $first + 1;
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
endwhile;
}
ob_clean();
return $event_dates;
wp_die();
}
</code></pre>
<p>(I'm aware the code to build the dates still needs some work to display proper dates.)</p>
<p>And then, in the page template:</p>
<pre><code><?php function date_chooser () {
$ajax_url = admin_url( 'admin-ajax.php' );
$grabDates = "
<script>
var ajaxUrl = '{$ajax_url}',
dropdownEvent = jQuery('#chooseEvent'),
dropdownDate = jQuery('#chooseDate');
dropdownEvent.on('change', function (e) {
var value = e.target.selectedOptions[0].value,
success,
data;
if (!!value) {
data = {
'event' : value,
'action' : 'dynamic_dropdown'
};
success = function ( response ) {
dropdownDate.html( response );
};
jQuery.post( ajaxUrl, data, success );
}
});
</script>";
return $grabDates;
}
echo date_chooser(); ?>
</code></pre>
<p>This code is getting me part of the way. Once the #chooseEvent dropdown has a selection, it is capture the proper post ID, and then the #chooseDate dropdown just empties itself from my placeholder but never loads anything else. </p>
<p>I've tried just having the dynamic_dropdown_func() just return a "Hello world!" and it doesn't do that either, so somehow I think I'm not triggering and returning the ajax function properly.</p>
| [
{
"answer_id": 261162,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": true,
"text": "<p>In <code>dynamic_dropdown_func()</code>, at the end try <code>echo $event_dates;</code> instead of <code>return $event_dates;</code>.</p>\n\n<p>Also, I'm wondering why you declare <code>global $wpdb;</code> when you don't seem to use it?</p>\n"
},
{
"answer_id": 261166,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 0,
"selected": false,
"text": "<p>I prefer to use <a href=\"http://api.jquery.com/jQuery.ajax/\" rel=\"nofollow noreferrer\">jQuery.ajax()</a> over <a href=\"http://api.jquery.com/jQuery.post/\" rel=\"nofollow noreferrer\">jQuery.post()</a>, as I seem to have more control over error processing.</p>\n\n<p>In your page template, do the following:</p>\n\n<pre><code>function\ndate_chooser ()\n{\n $ajax_url = admin_url( 'admin-ajax.php' );\n $grabDates = \"\n <script>\n var ajaxUrl = '{$ajax_url}',\n dropdownEvent = jQuery('#chooseEvent'),\n dropdownDate = jQuery('#chooseDate');\n dropdownEvent.on('change', function (e) {\n var value = e.target.selectedOptions[0].value,\n success,\n data;\n if (!!value) {\n var data = {\n action: 'dynamic_dropdown',\n event: value\n } ;\n\n jQuery.ajax ({\n type: 'POST',\n async: true,\n url: ajaxUrl,\n data: data,\n dataType: 'JSON',\n success: function (response) {\n // handle ajax success\n if (response.success) {\n // handle success, returned with wp_send_json_success ()\n dropdownDate.html (response.data) ;\n }\n else {\n // handle errors, returned with wp_send_json_error ()\n }\n },\n error: function (xhr, ajaxOptions, thrownError) {\n // handle ajax errors\n }\n }) ;\n }\n });\n </script>\";\n echo $grabDates;\n}\n</code></pre>\n\n<p>In your <code>functions.php</code>, do the following:</p>\n\n<pre><code>add_action( 'wp_ajax_dynamic_dropdown', array ($this, 'dynamic_dropdown_func' ));\nadd_action( 'wp_ajax_nopriv_dynamic_dropdown', array ($this, 'dynamic_dropdown_func' ));\n\nfunction\ndynamic_dropdown_func ()\n{\n if (!isset($_POST['event'])) {\n wp_send_json_error ('event not set') ;\n }\n\n $event_id = $_POST['event'];\n $first = get_field('first_day',$event_id);\n $last = get_field('last_day',$event_id);\n $event_dates = '<option value=\"\" disabled selected>Choose Date</option>';\n $event_dates .= '<option value=\"'.$first.'\">'.$first.'</option>';\n while($first<$last) :\n $first = $first + 1;\n $event_dates .= '<option value=\"'.$first.'\">'.$first.'</option>';\n endwhile;\n\n ob_clean () ;\n\n wp_send_json_success ($event_dates) ;\n}\n</code></pre>\n\n<p>Note the use of <a href=\"https://developer.wordpress.org/reference/functions/wp_send_json_success/\" rel=\"nofollow noreferrer\">wp_send_json_success()</a> and <a href=\"https://developer.wordpress.org/reference/functions/wp_send_json_error/\" rel=\"nofollow noreferrer\">wp_send_json_error()</a></p>\n"
}
]
| 2017/03/20 | [
"https://wordpress.stackexchange.com/questions/260773",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/2041/"
]
| I'm inexperienced with ajax. I'm building a form that will allow the user to grab a custom post type from the first field that will return the value of the post ID. Then, I'd like ajax to take that post ID and build a second dropdown based on some custom fields for that post.
Here's what I have so far, which was adapted from the first answer on this question: [Filter a second dropdown list when a value is chosen in the first one](https://wordpress.stackexchange.com/questions/177141/filter-a-second-dropdown-list-when-a-value-is-chosen-in-the-first-one)
In functions.php:
```
if ( is_admin() ) {
add_action( 'wp_ajax_dynamic_dropdown', 'dynamic_dropdown_func' );
add_action( 'wp_ajax_nopriv_dynamic_dropdown', 'dynamic_dropdown_func' );
}
function dynamic_dropdown_func () {
global $wpdb;
if (isset($_POST['event'])) {
$event_id = $_POST['event'];
$first = get_field('first_day',$event_id);
$last = get_field('last_day',$event_id);
$event_dates = '<option value="" disabled selected>Choose Date</option>';
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
while($first<$last) :
$first = $first + 1;
$event_dates .= '<option value="'.$first.'">'.$first.'</option>';
endwhile;
}
ob_clean();
return $event_dates;
wp_die();
}
```
(I'm aware the code to build the dates still needs some work to display proper dates.)
And then, in the page template:
```
<?php function date_chooser () {
$ajax_url = admin_url( 'admin-ajax.php' );
$grabDates = "
<script>
var ajaxUrl = '{$ajax_url}',
dropdownEvent = jQuery('#chooseEvent'),
dropdownDate = jQuery('#chooseDate');
dropdownEvent.on('change', function (e) {
var value = e.target.selectedOptions[0].value,
success,
data;
if (!!value) {
data = {
'event' : value,
'action' : 'dynamic_dropdown'
};
success = function ( response ) {
dropdownDate.html( response );
};
jQuery.post( ajaxUrl, data, success );
}
});
</script>";
return $grabDates;
}
echo date_chooser(); ?>
```
This code is getting me part of the way. Once the #chooseEvent dropdown has a selection, it is capture the proper post ID, and then the #chooseDate dropdown just empties itself from my placeholder but never loads anything else.
I've tried just having the dynamic\_dropdown\_func() just return a "Hello world!" and it doesn't do that either, so somehow I think I'm not triggering and returning the ajax function properly. | In `dynamic_dropdown_func()`, at the end try `echo $event_dates;` instead of `return $event_dates;`.
Also, I'm wondering why you declare `global $wpdb;` when you don't seem to use it? |
260,789 | <p>So i'm adding a script into my site via <code>functions.php</code> that lives in the plugins directory. The code is pretty straightforward:</p>
<pre><code>function add_jq_script() {
wp_register_script('r_footer', plugins_url('/responsiveFooter.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('r_footer');
}
add_action( 'wp_enqueue_scripts', 'add_jq_script', 999 );
</code></pre>
<p>the plugins seem to be working on local site, but in dev console, i'm getting a 404 that seems to be concatting my site-url and the absolute url for my plugins:
<code>http://localhost/~thisuser/wordpress/wp-content/plugins/Users/thisuser/Sites/wordpress/wp-content/themes/liberty/responsiveFooter.js?ver=1.1</code></p>
<p>i'm a bit new to wordpress, the url should be <code>http://localhost/~thisuser/wordpress/wp-content/plugins/responsiveFooter.js</code></p>
<p>is there some wp-option i need to change or some plugin setting somewhere to fix this?</p>
| [
{
"answer_id": 260790,
"author": "mukto90",
"author_id": 57944,
"author_profile": "https://wordpress.stackexchange.com/users/57944",
"pm_score": 0,
"selected": false,
"text": "<p>You have used wrong callable function in <code>add_action()</code>. Your code should be something like this-</p>\n\n<pre><code>function add_jq_script() {\n wp_register_script('r_footer', plugins_url('/responsiveFooter.js', __FILE__), array('jquery'),'1.1', true);\n wp_enqueue_script('r_footer');\n } \n\nadd_action( 'wp_enqueue_scripts', 'add_jq_script', 999 ); \n</code></pre>\n\n<p>Additionally, according to your code, you need to keep <code>responsiveFooter.js</code> and <code>functions.php</code> files in the same directory.</p>\n\n<p><strong>UPDATE:</strong></p>\n\n<p>Use this code instead. Paste in your <code>functions.php</code>-</p>\n\n<pre><code>function add_jq_script() {\n wp_register_script('r_footer', plugins_url( '/responsiveFooter.js' ), array( 'jquery' ), '1.1', true );\n wp_enqueue_script('r_footer');\n } \n\nadd_action( 'wp_enqueue_scripts', 'add_jq_script', 999 );\n</code></pre>\n"
},
{
"answer_id": 260794,
"author": "Ian",
"author_id": 11583,
"author_profile": "https://wordpress.stackexchange.com/users/11583",
"pm_score": 2,
"selected": true,
"text": "<p><code>plugins_url</code> will output the absolute file path of the plugins directory in your WordPress install.</p>\n\n<p>This of course won't work for a client (browser) calling a script.</p>\n\n<p>To access scripts from the plugins directory, you'll want to use <code>plugin_dir_url()</code> which will get you the url of the plugin directory. </p>\n\n<p><strong>Some things to note about <code>plugin_dir_url()</code></strong></p>\n\n<ul>\n<li>You need to specify the directory of the plugin name your script is located</li>\n<li>The function output contains a trailing slash, so you won't need to concatenate a slash.</li>\n</ul>\n\n<p>Lets say your plugin is called \"my_plugin\" and the script is located in a \"js\" directory, your script registration would look something like this:</p>\n\n<pre><code>wp_register_script('r_footer', plugins_dir_url() . 'my_plugin/js/responsiveFooter.js', array('jquery'),'1.1', true);\n</code></pre>\n\n<p>Note the omission of <code>__FILE__</code> which will output the absolute path of the current file (not what you want).</p>\n\n<hr>\n\n<p>If your script is in your active theme, you'll want to use a different function: <code>get_stylesheet_directory_uri</code></p>\n\n<p><strong>Some things to note about <code>get_stylesheet_directory_uri</code></strong></p>\n\n<ul>\n<li>It requires a trailing slash unlike <code>plugin_dir_url()</code></li>\n<li>You will need to specify the directory path in the theme where your script is located.</li>\n<li>This function works especially well if you are working with child themes, but a child theme is not required. If you are working with a child theme, this function will get the path to the style.css file in your child theme rather than the parent theme.</li>\n<li>Note that the function is ur<strong>i</strong> NOT ur<strong>l</strong></li>\n</ul>\n\n<p>So lets say your theme is called \"my_theme\" and the javascript is located in a \"js\" file, your registration script would look something like this:</p>\n\n<pre><code>wp_register_script('r_footer', get_stylesheet_directory_uri() . '/my_theme/js/responsiveFooter.js', array('jquery'),'1.1', true);\n</code></pre>\n\n<hr>\n\n<p><strong>Links to documentation:</strong></p>\n\n<ul>\n<li>plugin_dir_url - <a href=\"https://codex.wordpress.org/Function_Reference/plugin_dir_url\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/plugin_dir_url</a></li>\n<li>get_stylesheet_uri - <a href=\"https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri</a></li>\n<li>get_template_directory_uri (which is an alternative function to get_stylesheet_uri, but isn't advised for child themes) - <a href=\"https://developer.wordpress.org/reference/functions/get_template_directory_uri/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_template_directory_uri/</a></li>\n<li>plugins_url - <a href=\"https://codex.wordpress.org/Function_Reference/plugins_url\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/plugins_url</a></li>\n</ul>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260789",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106975/"
]
| So i'm adding a script into my site via `functions.php` that lives in the plugins directory. The code is pretty straightforward:
```
function add_jq_script() {
wp_register_script('r_footer', plugins_url('/responsiveFooter.js', __FILE__), array('jquery'),'1.1', true);
wp_enqueue_script('r_footer');
}
add_action( 'wp_enqueue_scripts', 'add_jq_script', 999 );
```
the plugins seem to be working on local site, but in dev console, i'm getting a 404 that seems to be concatting my site-url and the absolute url for my plugins:
`http://localhost/~thisuser/wordpress/wp-content/plugins/Users/thisuser/Sites/wordpress/wp-content/themes/liberty/responsiveFooter.js?ver=1.1`
i'm a bit new to wordpress, the url should be `http://localhost/~thisuser/wordpress/wp-content/plugins/responsiveFooter.js`
is there some wp-option i need to change or some plugin setting somewhere to fix this? | `plugins_url` will output the absolute file path of the plugins directory in your WordPress install.
This of course won't work for a client (browser) calling a script.
To access scripts from the plugins directory, you'll want to use `plugin_dir_url()` which will get you the url of the plugin directory.
**Some things to note about `plugin_dir_url()`**
* You need to specify the directory of the plugin name your script is located
* The function output contains a trailing slash, so you won't need to concatenate a slash.
Lets say your plugin is called "my\_plugin" and the script is located in a "js" directory, your script registration would look something like this:
```
wp_register_script('r_footer', plugins_dir_url() . 'my_plugin/js/responsiveFooter.js', array('jquery'),'1.1', true);
```
Note the omission of `__FILE__` which will output the absolute path of the current file (not what you want).
---
If your script is in your active theme, you'll want to use a different function: `get_stylesheet_directory_uri`
**Some things to note about `get_stylesheet_directory_uri`**
* It requires a trailing slash unlike `plugin_dir_url()`
* You will need to specify the directory path in the theme where your script is located.
* This function works especially well if you are working with child themes, but a child theme is not required. If you are working with a child theme, this function will get the path to the style.css file in your child theme rather than the parent theme.
* Note that the function is ur**i** NOT ur**l**
So lets say your theme is called "my\_theme" and the javascript is located in a "js" file, your registration script would look something like this:
```
wp_register_script('r_footer', get_stylesheet_directory_uri() . '/my_theme/js/responsiveFooter.js', array('jquery'),'1.1', true);
```
---
**Links to documentation:**
* plugin\_dir\_url - <https://codex.wordpress.org/Function_Reference/plugin_dir_url>
* get\_stylesheet\_uri - <https://codex.wordpress.org/Function_Reference/get_stylesheet_directory_uri>
* get\_template\_directory\_uri (which is an alternative function to get\_stylesheet\_uri, but isn't advised for child themes) - <https://developer.wordpress.org/reference/functions/get_template_directory_uri/>
* plugins\_url - <https://codex.wordpress.org/Function_Reference/plugins_url> |
260,800 | <p>I want to save my form data via jquery but i can't able to access it in my script.Can anyone help me.
URL access in script: <strong>url: 'admin.php?page=insert.php',</strong></p>
<p>My script</p>
<pre><code>$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var schema_key = $("#schema_key").val();
$.ajax({
type: 'post',
url: 'admin.php?page=insert.php',
data: schema_key,
success: function () {
alert('form was submitted');
}
});
});
});
</code></pre>
| [
{
"answer_id": 260793,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>Prefixes are used to avoid conflicts. If your framework is used to build a theme, the chances are high that there isn't a second theme framework in use at the same time. So there is no conflict, and therefore no need for a prefix.</p>\n\n<p>The exception are CSS classes generated by the WordPress core, for example in the comment form. If you are using the same class names for an entirely different purpose, you need a prefix, or better class names for your use case. </p>\n"
},
{
"answer_id": 260802,
"author": "Nathan Powell",
"author_id": 27196,
"author_profile": "https://wordpress.stackexchange.com/users/27196",
"pm_score": 2,
"selected": false,
"text": "<p>NO!!! Do no prefix everything, it will be crazy for anyone to deal with. What you should do is add a <a href=\"https://en.wikipedia.org/wiki/Namespace\" rel=\"nofollow noreferrer\">body_class</a> to <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow noreferrer\">namespace</a> the special theme CSS.</p>\n\n<p>If I wrote a theme today, something I would do in my <code>function.php</code> file is:</p>\n\n<pre><code>add_filter( 'body_class', function( $classes ){\n $classes[] = 'my-bad-ass-theme';\n return $classes;\n }); \n</code></pre>\n\n<p>Then overriding anything I need is accessible, yet also easy to read and specific. For example, I like headers to be different font than the rest of the site, I would put this in the CSS file:</p>\n\n<pre><code>.my-bad-ass-theme{\n font-family: Verdana;\n}\n.my-bad-ass-theme h1,\n.my-bad-ass-theme h2,\n.my-bad-ass-theme h3,\n.my-bad-ass-theme h4,\n.my-bad-ass-theme h5,\n.my-bad-ass-theme h6 {\n font-family: Lucida-Grande;\n}\n</code></pre>\n\n<p>I can still have a nice style to my original font but for paragraphs such as:</p>\n\n<pre><code>p {\n color: #333;\n}\n</code></pre>\n\n<p>This leaves paragraphs open to be styled by plugins or child themes alike, without getting in the way.</p>\n\n<p>Don't get carried away with the <code>namespace</code>, but also look into CSS preprocessors like SAAS and LESS (I suggest <a href=\"http://sass-lang.com/\" rel=\"nofollow noreferrer\">SASS</a>), to take advantage of nesting and other functions.</p>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260800",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114992/"
]
| I want to save my form data via jquery but i can't able to access it in my script.Can anyone help me.
URL access in script: **url: 'admin.php?page=insert.php',**
My script
```
$(function () {
$('form').on('submit', function (e) {
e.preventDefault();
var schema_key = $("#schema_key").val();
$.ajax({
type: 'post',
url: 'admin.php?page=insert.php',
data: schema_key,
success: function () {
alert('form was submitted');
}
});
});
});
``` | Prefixes are used to avoid conflicts. If your framework is used to build a theme, the chances are high that there isn't a second theme framework in use at the same time. So there is no conflict, and therefore no need for a prefix.
The exception are CSS classes generated by the WordPress core, for example in the comment form. If you are using the same class names for an entirely different purpose, you need a prefix, or better class names for your use case. |
260,813 | <p>I'm working to optimize a site that I've recently taken management of, and it appears to me that there are a fair few unused templates. I want to remove all the unused and redundant template files so that we can focus our developments on those templates we do support, however there are 100+ pages and posts on this site, so I can't just do a spot check, I need a robust query.</p>
<p>I've established how to query which page template is being called from joining wp_posts and wp_postmeta, and I've sussed out which post formats are being used by querying wp_posts and wp_terms via wp_term_relationships BUT... this still doesn't seem to tell me whether the index.php is ever used (and I don't think it is).</p>
<p>I'm probably missing something obvious, but is there a way to see which of the normal Wordpress theme files are actually being called? OR is it that I have all the information already and 'index.php' just isn't being used. </p>
<p>Any help would be much appreciated!</p>
<p>Thanks</p>
| [
{
"answer_id": 260836,
"author": "Netanel Perez",
"author_id": 114386,
"author_profile": "https://wordpress.stackexchange.com/users/114386",
"pm_score": -1,
"selected": false,
"text": "<p>You mean something like this?</p>\n\n<pre><code>$args = array(\n 'meta_key' => '_wp_page_template',\n 'meta_value' => 'page-special.php'\n);\n\nwp_count_posts( $args );\n</code></pre>\n"
},
{
"answer_id": 260851,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>There is no query that will identify all of the theme files that are actively in use, or not in use. The only query I'm aware of which will identify some theme files is:</p>\n\n<p><code>SELECT * FROM wp_postmeta WHERE meta_key = '_wp_page_template';</code></p>\n\n<p>which will identify all custom Page templates which are in use. It won't identify standard theme files such as index.php, single.php, header.php, footer.php, because those are not custom Page templates. And it's best practice to include index.php, since it is a default/fallback if there is ever a problem with more specific theme files. In many cases the file is never used, but it's always good to have it there, and it usually shows you the barebones HTML structure of the site, which can be a helpful cue before you dive into more customized files.</p>\n\n<p>If you want to continue down the reverse-engineering path, I would suggest including your theme-file-identifier code in the (as a comment if it's a live site) and manually go through each URL. If you use a plugin that generates an XML sitemap it can help you ensure that you hit every URL. Just bear in mind that whatever file is identified is probably not the only file in use. For example, if your Posts use the default <code>single.php</code> it is very likely to be making use of <code>header.php</code> and <code>footer.php</code> at a minimum. Some themes use template parts or includes, so after you have your initial list of the overarching template used on each URL, you will have to look through each of those templates and determine which files they call. You'll also want to check <code>functions.php</code> for the enqueued stylesheets and JS, as well as potentially other includes.</p>\n\n<p>One alternative to this long process is to rebuild the theme from the ground up. I understand this isn't always possible, but it's the cleanest solution, and it's likely to take less time and be less risky than trying to slowly slough off parts of an old complex theme. For this process, I identify the most-used templates (if you have 50 of one CPT start there) and code those first on a dev/staging site, import or copy at least a handful of each post type and keep building from there. Once again you'll need to go through at least most of the site to make sure you don't overlook customizations, and the only way you'll be 100% certain you caught everything is to review every URL.</p>\n"
},
{
"answer_id": 260853,
"author": "Jebble",
"author_id": 81939,
"author_profile": "https://wordpress.stackexchange.com/users/81939",
"pm_score": 0,
"selected": false,
"text": "<p>Drop this code in functions.php and login with a user that has the <code>manage_options</code> capability to create a page that shows the unused templates.</p>\n\n<p>I advice against removing index.php as it's part of the <a href=\"https://developer.wordpress.org/themes/basics/template-hierarchy/\" rel=\"nofollow noreferrer\">WP Template Hierarchy</a> and is the very last backup template for anything that doesn't have anything else to use.</p>\n\n<pre><code>// Hook into admin_menu\nadd_action( 'admin_menu', function() {\n\n // Add submenu page under \"Tools\" with manage_options capabilities\n add_submenu_page( 'tools.php', 'Page Templates Statistics', 'Page Templates Statistics', 'manage_options', 'page-template-statistics', 'wpse_260813_show_satistics' );\n} );\n\n// Function that renders the page added above\nfunction wpse_260813_show_satistics() {\n\n // Get available templates within active theme\n $available_templates = get_page_templates();\n\n // Get used templates from database\n global $wpdb;\n $result = $wpdb->get_results(\n \"\n SELECT DISTINCT( meta.meta_value ) FROM {$wpdb->prefix}postmeta as meta\n JOIN {$wpdb->prefix}posts as posts ON posts.ID = meta.post_id\n WHERE meta.meta_key LIKE '_wp_page_template'\n AND posts.post_type = 'page'\n \"\n );\n\n $used_templates = array();\n foreach ( $result as $template ) {\n $used_templates[] = $template->meta_value;\n }\n\n /**\n * Compare available templates against used templates\n * Result is an array with the unused templates\n */\n $unused_templates = array_diff( $available_templates, $used_templates );\n\n // Draw page to show unused templates\n?>\n <div class=\"wrap\">\n <h1>Page Template Statistics</h1>\n The following templates are not being used:\n <table>\n <tr>\n <th>Template name</th>\n <th>Filename</th>\n </tr>\n <?php foreach ( $unused_templates as $name => $file ) : ?>\n <tr>\n <td><?php echo $name; ?></td>\n <td><?php echo $file; ?></td>\n </tr>\n <?php endforeach; ?>\n </table>\n </div>\n<?php\n}\n</code></pre>\n"
},
{
"answer_id": 260895,
"author": "Dan Knauss",
"author_id": 57078,
"author_profile": "https://wordpress.stackexchange.com/users/57078",
"pm_score": 0,
"selected": false,
"text": "<p>You could crawl the whole site and match the results for <code>get_included_files()</code> to your template files. </p>\n"
},
{
"answer_id": 311066,
"author": "Kevinleary.net",
"author_id": 1495,
"author_profile": "https://wordpress.stackexchange.com/users/1495",
"pm_score": 3,
"selected": false,
"text": "<p>Here's a rough function I use to handle this, it should work well for anyone out there wanting to do this quick and easy. Add this this your functions.php file and then visit your site with <code>?template_report</code> added onto the URL to display a report for every custom theme template.</p>\n\n<p><strong>It's rough, I'd suggest commenting/uncommenting the <code>add_action</code> call when you want to use it.</strong></p>\n\n<pre><code>/**\n * Theme Template Usage Report\n *\n * Displays a data dump to show you the pages in your WordPress\n * site that are using custom theme templates.\n */\nfunction theme_template_usage_report( $file = false ) {\n if ( ! isset( $_GET['template_report'] ) ) return;\n\n $templates = wp_get_theme()->get_page_templates();\n $report = array();\n\n echo '<h1>Page Template Usage Report</h1>';\n echo \"<p>This report will show you any pages in your WordPress site that are using one of your theme's custom templates.</p>\";\n\n foreach ( $templates as $file => $name ) {\n $q = new WP_Query( array(\n 'post_type' => 'page',\n 'posts_per_page' => -1,\n 'meta_query' => array( array(\n 'key' => '_wp_page_template',\n 'value' => $file\n ) )\n ) );\n\n $page_count = sizeof( $q->posts );\n\n if ( $page_count > 0 ) {\n echo '<p style=\"color:green\">' . $file . ': <strong>' . sizeof( $q->posts ) . '</strong> pages are using this template:</p>';\n echo \"<ul>\";\n foreach ( $q->posts as $p ) {\n echo '<li><a href=\"' . get_permalink( $p, false ) . '\">' . $p->post_title . '</a></li>';\n }\n echo \"</ul>\";\n } else {\n echo '<p style=\"color:red\">' . $file . ': <strong>0</strong> pages are using this template, you should be able to safely delete it from your theme.</p>';\n }\n\n foreach ( $q->posts as $p ) {\n $report[$file][$p->ID] = $p->post_title;\n }\n }\n\n exit;\n}\nadd_action( 'wp', 'theme_template_usage_report' );\n</code></pre>\n\n<p>The output looks like this:</p>\n\n<p><a href=\"https://i.stack.imgur.com/ezZdv.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/ezZdv.png\" alt=\"enter image description here\"></a></p>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115867/"
]
| I'm working to optimize a site that I've recently taken management of, and it appears to me that there are a fair few unused templates. I want to remove all the unused and redundant template files so that we can focus our developments on those templates we do support, however there are 100+ pages and posts on this site, so I can't just do a spot check, I need a robust query.
I've established how to query which page template is being called from joining wp\_posts and wp\_postmeta, and I've sussed out which post formats are being used by querying wp\_posts and wp\_terms via wp\_term\_relationships BUT... this still doesn't seem to tell me whether the index.php is ever used (and I don't think it is).
I'm probably missing something obvious, but is there a way to see which of the normal Wordpress theme files are actually being called? OR is it that I have all the information already and 'index.php' just isn't being used.
Any help would be much appreciated!
Thanks | Here's a rough function I use to handle this, it should work well for anyone out there wanting to do this quick and easy. Add this this your functions.php file and then visit your site with `?template_report` added onto the URL to display a report for every custom theme template.
**It's rough, I'd suggest commenting/uncommenting the `add_action` call when you want to use it.**
```
/**
* Theme Template Usage Report
*
* Displays a data dump to show you the pages in your WordPress
* site that are using custom theme templates.
*/
function theme_template_usage_report( $file = false ) {
if ( ! isset( $_GET['template_report'] ) ) return;
$templates = wp_get_theme()->get_page_templates();
$report = array();
echo '<h1>Page Template Usage Report</h1>';
echo "<p>This report will show you any pages in your WordPress site that are using one of your theme's custom templates.</p>";
foreach ( $templates as $file => $name ) {
$q = new WP_Query( array(
'post_type' => 'page',
'posts_per_page' => -1,
'meta_query' => array( array(
'key' => '_wp_page_template',
'value' => $file
) )
) );
$page_count = sizeof( $q->posts );
if ( $page_count > 0 ) {
echo '<p style="color:green">' . $file . ': <strong>' . sizeof( $q->posts ) . '</strong> pages are using this template:</p>';
echo "<ul>";
foreach ( $q->posts as $p ) {
echo '<li><a href="' . get_permalink( $p, false ) . '">' . $p->post_title . '</a></li>';
}
echo "</ul>";
} else {
echo '<p style="color:red">' . $file . ': <strong>0</strong> pages are using this template, you should be able to safely delete it from your theme.</p>';
}
foreach ( $q->posts as $p ) {
$report[$file][$p->ID] = $p->post_title;
}
}
exit;
}
add_action( 'wp', 'theme_template_usage_report' );
```
The output looks like this:
[](https://i.stack.imgur.com/ezZdv.png) |
260,826 | <p>Say I have a user meta field that is called "meta1".
I want to get posts (via get_posts or the like) who's author meta1 = true.
Any idea how I should approach this?</p>
| [
{
"answer_id": 260832,
"author": "Netanel Perez",
"author_id": 114386,
"author_profile": "https://wordpress.stackexchange.com/users/114386",
"pm_score": 0,
"selected": false,
"text": "<p>You can define it in the loop's arguments and i believe it will work with other WP functions as well</p>\n\n<pre><code>$args = array(\n 'author' => 1 // Author's ID\n); \n</code></pre>\n"
},
{
"answer_id": 260857,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 3,
"selected": false,
"text": "<p>Get for all users / authors with user meta field. <code>meta1 = true</code></p>\n\n<pre><code>$args = array(\n 'meta_key' => 'meta1',\n 'meta_value' => 'true',\n 'meta_compare' => '=',\n 'fields' => 'all',\n );\n$users = get_users( $args );\n</code></pre>\n\n<p>Store user id and login into an array <code>authors</code></p>\n\n<pre><code>$authors = array();\nforeach ( (array) $users as $user ) {\n authors[ $user->ID ] = $user->user_login;\n}\n</code></pre>\n\n<p>Now you can pass authors in your posts query.</p>\n\n<pre><code>$posts = query_posts( array( 'author__in'=> array_keys( $authors ) ) );\n</code></pre>\n\n<p><strong>Or</strong></p>\n\n<pre><code>$posts = new WP_Query( array( 'author__in' => array( array_keys( $authors ) ) );\n</code></pre>\n\n<p>Final code</p>\n\n<pre><code>$args = array(\n 'meta_key' => 'meta1',\n 'meta_value' => 'true',\n 'meta_compare' => '=',\n 'fields' => 'all',\n );\n$users = get_users( $args );\n$authors = array();\nforeach ( (array) $users as $user ) {\n $authors[ $user->ID ] = $user->user_login;\n}\n$query = new WP_Query( array( 'author__in' => array( array_keys( $authors ) ) );\n\nif ( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();\n\n//print post contents, title etc\n\nendwhile;\nendif;\nwp_reset_postdata();\n</code></pre>\n"
},
{
"answer_id": 260864,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 2,
"selected": false,
"text": "<p>This can be accomplished via the <a href=\"https://developer.wordpress.org/reference/hooks/parse_query/\" rel=\"nofollow noreferrer\">parse_query</a> filter, as follows:</p>\n\n<pre><code>add_action ('parse_query', array ($this, 'wpse_private_author_query')) ;\n\nfunction\nwpse_private_author_query ($query)\n{\n // get our private author query query_var \n $private_author_query = $query->get ('_private_author_query') ;\n if (empty ($private_author_query)) {\n // our private author query query_var is not set, so bail without modifying $query\n return ;\n }\n\n $args = array (\n 'fields' => 'ID',\n ) ;\n $args = wp_parse_args ($args, $private_author_query) ;\n // get the ID's of the users that match our private author query\n $users = get_users ($args) ;\n\n // unset our private author query query_var\n unset ($query->query_vars['_private_author_query']) ;\n\n // add the author IDs to the query\n $query->set ('author__in', $users) ;\n\n return ;\n}\n</code></pre>\n\n<p>To see this in action, we can do:</p>\n\n<pre><code>$args = array (\n 'post_type' => 'any',\n 'post_status' => 'public',\n '_private_author_query' => array (\n 'meta_key' => 'meta1',\n 'meta_value' => true,\n 'meta_compare' => '=',\n ),\n ) ;\n$posts = new WP_Query ($args) ;\n</code></pre>\n\n<p><strong>Note</strong>: the above is more general than your question. You asked just for user_meta, but the above\nwill allow searching by <em>any</em> of the characteristics supported by <a href=\"https://developer.wordpress.org/reference/classes/wp_user_query/prepare_query/\" rel=\"nofollow noreferrer\">WP_User_Query::parse_query()</a>. For example,\nwe can also do:</p>\n\n<pre><code>$args = array (\n 'post_type' => 'any',\n 'post_status' => 'public',\n '_private_author_query' => array (\n 'role' => 'editor',\n ),\n ) ;\n$posts = new WP_Query ($args) ;\n</code></pre>\n\n<p>etc.</p>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260826",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115876/"
]
| Say I have a user meta field that is called "meta1".
I want to get posts (via get\_posts or the like) who's author meta1 = true.
Any idea how I should approach this? | Get for all users / authors with user meta field. `meta1 = true`
```
$args = array(
'meta_key' => 'meta1',
'meta_value' => 'true',
'meta_compare' => '=',
'fields' => 'all',
);
$users = get_users( $args );
```
Store user id and login into an array `authors`
```
$authors = array();
foreach ( (array) $users as $user ) {
authors[ $user->ID ] = $user->user_login;
}
```
Now you can pass authors in your posts query.
```
$posts = query_posts( array( 'author__in'=> array_keys( $authors ) ) );
```
**Or**
```
$posts = new WP_Query( array( 'author__in' => array( array_keys( $authors ) ) );
```
Final code
```
$args = array(
'meta_key' => 'meta1',
'meta_value' => 'true',
'meta_compare' => '=',
'fields' => 'all',
);
$users = get_users( $args );
$authors = array();
foreach ( (array) $users as $user ) {
$authors[ $user->ID ] = $user->user_login;
}
$query = new WP_Query( array( 'author__in' => array( array_keys( $authors ) ) );
if ( $query->have_posts() ) : while( $query->have_posts() ) : $query->the_post();
//print post contents, title etc
endwhile;
endif;
wp_reset_postdata();
``` |
260,828 | <p>I've built a membership site where users can post listings from the frontend, edit those, and ideally also delete them.</p>
<p>For the latter, I'd like to echo a "delete post" link to the frontend. The problem is that <code>get_delete_post_link()</code>.</p>
<p>So from this:
<code>
$theID = get_the_ID(); // inside loop
echo $theID;
<a href="<?php echo get_delete_post_link( $theID, '', false ); ?> ">Delete This Post</a>
</code></p>
<p>I get:
<code>
123 /* = $theID; */
<a href="_">Delete This Post</a>
</code></p>
<p>I tried the following things:</p>
<ul>
<li>passing only $theID as argument instead of the full three</li>
<li>passing <code>$theID, '', true</code></li>
<li>ran checks as described in the answers here: <a href="https://wordpress.stackexchange.com/questions/99344/cant-echo-get-delete-post-link">Can't echo get_delete_post_link</a></li>
<li>the problem occurs both when I'm logged in as admin and as normal user (with added capacities)</li>
<li>I made sure the permissions for the custom post type are mapped correctly</li>
<li>outside the loop it works, but not inside the loop (the codex says it can be done within the loop: <a href="https://codex.wordpress.org/Function_Reference/get_delete_post_link" rel="nofollow noreferrer">https://codex.wordpress.org/Function_Reference/get_delete_post_link</a>).</li>
</ul>
<p>Here's the loop I'm using:</p>
<pre><code> // arguments
$arguments = array(
'post_type' => 'CustomType',
'posts_per_page' => -1,
'author_name' => $current_user->user_login
);
// query
$the_query = new WP_Query($arguments);
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if( has_term( 'custom_term', 'custom_taxonomy' ) ): ?>
/* stuff happens here */
/* get_delete_post_link() returns nothing */
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
</code></pre>
<p>I'm at the end of my wits with this, any help would be appreciated.</p>
| [
{
"answer_id": 260830,
"author": "Netanel Perez",
"author_id": 114386,
"author_profile": "https://wordpress.stackexchange.com/users/114386",
"pm_score": 1,
"selected": false,
"text": "<ol>\n<li><p>get_delete_post_link() Should work without parameters if you are using it inside the loop</p></li>\n<li><p>I believe that you need to remove your wp_reset_query() that is placed before the if( $the_query->have_posts()..</p></li>\n</ol>\n"
},
{
"answer_id": 260860,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>Have you turned on WP_DEBUG and checked your error log? If there is something not set up quite right with the CPT, you'll see something like:</p>\n\n<pre><code>\"Notice: map_meta_cap was called incorrectly. The post type CustomType is not registered, so it may not be reliable to check the capability \"delete_post\" against a post of that type. Please see Debugging in WordPress for more information. (This message was added in version 4.4.0.) in /yourpath/wp-includes/functions.php on line XX\"\n</code></pre>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/104550/"
]
| I've built a membership site where users can post listings from the frontend, edit those, and ideally also delete them.
For the latter, I'd like to echo a "delete post" link to the frontend. The problem is that `get_delete_post_link()`.
So from this:
`$theID = get_the_ID(); // inside loop
echo $theID;
<a href="<?php echo get_delete_post_link( $theID, '', false ); ?> ">Delete This Post</a>`
I get:
`123 /* = $theID; */
<a href="_">Delete This Post</a>`
I tried the following things:
* passing only $theID as argument instead of the full three
* passing `$theID, '', true`
* ran checks as described in the answers here: [Can't echo get\_delete\_post\_link](https://wordpress.stackexchange.com/questions/99344/cant-echo-get-delete-post-link)
* the problem occurs both when I'm logged in as admin and as normal user (with added capacities)
* I made sure the permissions for the custom post type are mapped correctly
* outside the loop it works, but not inside the loop (the codex says it can be done within the loop: <https://codex.wordpress.org/Function_Reference/get_delete_post_link>).
Here's the loop I'm using:
```
// arguments
$arguments = array(
'post_type' => 'CustomType',
'posts_per_page' => -1,
'author_name' => $current_user->user_login
);
// query
$the_query = new WP_Query($arguments);
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
<?php if( $the_query->have_posts() ): ?>
<?php while( $the_query->have_posts() ) : $the_query->the_post(); ?>
<?php if( has_term( 'custom_term', 'custom_taxonomy' ) ): ?>
/* stuff happens here */
/* get_delete_post_link() returns nothing */
<?php endif; ?>
<?php endwhile; ?>
<?php endif; ?>
<?php wp_reset_query(); // Restore global post data stomped by the_post(). ?>
```
I'm at the end of my wits with this, any help would be appreciated. | 1. get\_delete\_post\_link() Should work without parameters if you are using it inside the loop
2. I believe that you need to remove your wp\_reset\_query() that is placed before the if( $the\_query->have\_posts().. |
260,850 | <p>I would like to list out the child terms related to the taxonomy archive and then list posts belonging to the child terms below the term name.</p>
<p>I currently have the following code which successfully lists out the child terms.</p>
<pre><code>$this_term = get_queried_object();
$args = array(
'parent' => $this_term->term_id,
'orderby' => 'slug',
'hide_empty' => false
);
$child_terms = get_terms( $this_term->taxonomy, $args );
echo '<ul>';
foreach ($child_terms as $term) {
//List the child topics
echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</h3></a></li>';
// Try to list the contained posts (DOES NOT WORK)
?> <div><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><div><?php
}//end foreach
echo '</ul>';
</code></pre>
<p>However, I need it to then display the permalinks for articles that belong to that child term. My current method of using 'the_permalink' just returns the same post in each topic.</p>
<p>Can anyone point me in the right direction?</p>
| [
{
"answer_id": 260858,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 0,
"selected": false,
"text": "<p>You need another query that will find the posts associated with each child term, the post-containing <code><div></code> needs to be changed to an <code><li></code> since it is still inside the <code><ul></code>. You might want to indent the posts underneath the child term link. This should point you in the general direction:</p>\n\n<pre><code>foreach ($child_terms as $term) {\n\n // List the child topic\n echo '<li><h3><a href=\"' . get_term_link( $term->name, $this_term->taxonomy ) . '\">' . $term->name . '</a></h3>'; \n\n // Get posts from that child topic\n $args = array(\n 'post_type' => 'yourposttype',\n 'tax_query' => array(\n 'taxonomy' => $term->term_id,\n 'field' => 'term_id',\n 'terms' => 'terms'\n )\n );\n $query = new WP_Query( $args ); \n // List the posts\n if($query->have_posts()):\n while($query->have_posts()) : $query->the_post(); ?>\n <li><a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\"><?php the_title(); ?></a></li><?php\n ehdwhile;\n endif;\n\n // close our <li>\n echo '</li>';\n } //end foreach\n</code></pre>\n\n<p>I am not as familiar with taxonomy queries, so the <code>tax_query</code> portion may need to be adjusted and I welcome edits. The key is you need a query to grab the posts you need, and once you have a Loop you can then use <code>the_permalink</code> etc. as desired.</p>\n"
},
{
"answer_id": 261074,
"author": "tmgale12",
"author_id": 83253,
"author_profile": "https://wordpress.stackexchange.com/users/83253",
"pm_score": 2,
"selected": true,
"text": "<p>I was able to get this working with the following code. I used the relation operator AND, referenced the var ($this_term) that contained get_queried_object(); to set the taxonomy in the tax_query and adjusted the term field in the tax_query. </p>\n\n<pre><code> $this_term = get_queried_object();\n $args = array(\n'parent' => $this_term->term_id,\n'orderby' => 'slug',\n'hide_empty' => false\n );\n $child_terms = get_terms( $this_term->taxonomy, $args );\n echo '<ul>';\n foreach ($child_terms as $term) {\n\n // List the child topic\n echo '<li><h3><a href=\"' . get_term_link( $term->name, $this_term->taxonomy ) . '\">' . $term->name . '</a></h3>'; \n\n // Get posts from that child topic \n$query = new WP_Query( array(\n 'post_type' => 'kb',\n 'tax_query' => array(\n 'relation' => 'AND',\n array(\n 'taxonomy' => $this_term->taxonomy,\n 'field' => 'slug',\n 'terms' => array( $term->slug )\n )\n )\n) );\n\n // List the posts\n if($query->have_posts()) {\n while($query->have_posts()) : $query->the_post(); ?>\n <li><a href=\"<?php the_permalink(); ?>\" title=\"<?php the_title_attribute(); ?>\"><?php the_title(); ?></a></li><?php\n endwhile;\n } else { echo \"no posts\";}\n\n\n // close our <li>\n echo '</li>';\n } //end foreach\n</code></pre>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260850",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83253/"
]
| I would like to list out the child terms related to the taxonomy archive and then list posts belonging to the child terms below the term name.
I currently have the following code which successfully lists out the child terms.
```
$this_term = get_queried_object();
$args = array(
'parent' => $this_term->term_id,
'orderby' => 'slug',
'hide_empty' => false
);
$child_terms = get_terms( $this_term->taxonomy, $args );
echo '<ul>';
foreach ($child_terms as $term) {
//List the child topics
echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</h3></a></li>';
// Try to list the contained posts (DOES NOT WORK)
?> <div><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a><div><?php
}//end foreach
echo '</ul>';
```
However, I need it to then display the permalinks for articles that belong to that child term. My current method of using 'the\_permalink' just returns the same post in each topic.
Can anyone point me in the right direction? | I was able to get this working with the following code. I used the relation operator AND, referenced the var ($this\_term) that contained get\_queried\_object(); to set the taxonomy in the tax\_query and adjusted the term field in the tax\_query.
```
$this_term = get_queried_object();
$args = array(
'parent' => $this_term->term_id,
'orderby' => 'slug',
'hide_empty' => false
);
$child_terms = get_terms( $this_term->taxonomy, $args );
echo '<ul>';
foreach ($child_terms as $term) {
// List the child topic
echo '<li><h3><a href="' . get_term_link( $term->name, $this_term->taxonomy ) . '">' . $term->name . '</a></h3>';
// Get posts from that child topic
$query = new WP_Query( array(
'post_type' => 'kb',
'tax_query' => array(
'relation' => 'AND',
array(
'taxonomy' => $this_term->taxonomy,
'field' => 'slug',
'terms' => array( $term->slug )
)
)
) );
// List the posts
if($query->have_posts()) {
while($query->have_posts()) : $query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>" title="<?php the_title_attribute(); ?>"><?php the_title(); ?></a></li><?php
endwhile;
} else { echo "no posts";}
// close our <li>
echo '</li>';
} //end foreach
``` |
260,854 | <p>It might be a stupid question, but I can't get it to work..</p>
<p><strong>Problem</strong><br>
I have no idea how to link my image on the frontend with the url from the database.</p>
<p><strong>Situation</strong><br>
I've created a Custom Post Type called 'Banners'. On each post I'm able to add a featured image. This will be saved in my database. Also on each post edit page, there is a input area for the banner_url. There I give my banner the link where it should go after clicking on it on the frontend. I'm able now to display the image I want on the page I want. But now I need to get the url out off the database and connent it to my image.</p>
<p><strong>Code</strong></p>
<pre><code><?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) { ?>
<?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>
<div class="container" align="center"><a href=""><?php echo the_post_thumbnail(); ?></a></div>
<?php endwhile; ?>
<?php }
wp_reset_postdata();
}
?>
</code></pre>
<p><strong>Question</strong><br>
My question is: How do I get the banner_url out of the database? And how am I able to get it to work with the image?</p>
<p>Thanks in advance!</p>
<p><strong>EDIT PROBLEM SOLVED</strong><br>
Thanks to Abdul Awal</p>
<pre><code><?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = '<div class="container" align="center"><a href="'.get_post_meta( get_the_ID(), 'banner_link', true ).'">'.get_the_post_thumbnail().'</a></div>';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
?>
</code></pre>
| [
{
"answer_id": 260855,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 1,
"selected": false,
"text": "<p>You are looking for <code>get_post_meta()</code></p>\n\n<p>Your loop should look like:</p>\n\n<pre><code><?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>\n\n <div class=\"container\" align=\"center\"><a href=\"<?php echo get_post_meta( get_the_ID(), 'banner_link', true); ?>\"><?php echo the_post_thumbnail(); ?></a></div>\n\n<?php endwhile; ?>\n</code></pre>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_post_meta/\" rel=\"nofollow noreferrer\">https://developer.wordpress.org/reference/functions/get_post_meta/</a></p>\n"
},
{
"answer_id": 260856,
"author": "Abdul Awal Uzzal",
"author_id": 31449,
"author_profile": "https://wordpress.stackexchange.com/users/31449",
"pm_score": 1,
"selected": true,
"text": "<p>Do you need to query only the items that has <code>banner_link</code> value set to <code>https://www.mypage.com</code> ? </p>\n\n<p>If no, you can remove the <code>meta_query</code> part from your query.</p>\n\n<pre><code><?php\n// function to show home page banner using query of banner post type\nfunction wptutsplus_home_page_banner() {\n\n// start by setting up the query\n$get_banner = new WP_Query( array(\n 'post_type' => 'banners',\n 'meta_query' => array(\n array(\n 'key' => 'banner_link',\n 'value' => 'https://www.mypage.com'\n )\n )\n));\n\n// now check if the query has posts and if so, output their content in a banner-box div\nif ( $get_banner->have_posts() ) { ?>\n <?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>\n\n <div class=\"container\" align=\"center\"><a href=\"<?php echo get_post_meta( $post->ID, 'banner_link', true ); ?>\"><?php the_post_thumbnail(); ?></a></div>\n\n <?php endwhile; ?>\n<?php }\n wp_reset_postdata();\n}\n?>\n</code></pre>\n\n<p><strong>UPDATE</strong></p>\n\n<p>As you're using it inside a plugin. You can do like the following: </p>\n\n<pre><code><?php\n// function to show home page banner using query of banner post type\nfunction wptutsplus_home_page_banner() {\n\n// start by setting up the query\n$get_banner = new WP_Query( array(\n 'post_type' => 'banners',\n 'meta_query' => array(\n array(\n 'key' => 'banner_link',\n 'value' => 'https://www.mypage.com'\n )\n )\n));\n\n// now check if the query has posts and if so, output their content in a banner-box div\nif ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();\n\n $output = '<div class=\"container\" align=\"center\"><a href=\"'.get_post_meta( $post->ID, 'banner_link', true ).'\">'.get_the_post_thumbnail().'</a></div>';\n\nendwhile;\nendif;\nwp_reset_postdata();\nreturn $output;\n}\n?>\n</code></pre>\n\n<p>And then call it anywhere with <code><?php echo wptutsplus_home_page_banner(); ?></code> </p>\n\n<p>Let me know if it works.</p>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115316/"
]
| It might be a stupid question, but I can't get it to work..
**Problem**
I have no idea how to link my image on the frontend with the url from the database.
**Situation**
I've created a Custom Post Type called 'Banners'. On each post I'm able to add a featured image. This will be saved in my database. Also on each post edit page, there is a input area for the banner\_url. There I give my banner the link where it should go after clicking on it on the frontend. I'm able now to display the image I want on the page I want. But now I need to get the url out off the database and connent it to my image.
**Code**
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) { ?>
<?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>
<div class="container" align="center"><a href=""><?php echo the_post_thumbnail(); ?></a></div>
<?php endwhile; ?>
<?php }
wp_reset_postdata();
}
?>
```
**Question**
My question is: How do I get the banner\_url out of the database? And how am I able to get it to work with the image?
Thanks in advance!
**EDIT PROBLEM SOLVED**
Thanks to Abdul Awal
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = '<div class="container" align="center"><a href="'.get_post_meta( get_the_ID(), 'banner_link', true ).'">'.get_the_post_thumbnail().'</a></div>';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
?>
``` | Do you need to query only the items that has `banner_link` value set to `https://www.mypage.com` ?
If no, you can remove the `meta_query` part from your query.
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) { ?>
<?php while ( $get_banner->have_posts() ) : $get_banner->the_post(); ?>
<div class="container" align="center"><a href="<?php echo get_post_meta( $post->ID, 'banner_link', true ); ?>"><?php the_post_thumbnail(); ?></a></div>
<?php endwhile; ?>
<?php }
wp_reset_postdata();
}
?>
```
**UPDATE**
As you're using it inside a plugin. You can do like the following:
```
<?php
// function to show home page banner using query of banner post type
function wptutsplus_home_page_banner() {
// start by setting up the query
$get_banner = new WP_Query( array(
'post_type' => 'banners',
'meta_query' => array(
array(
'key' => 'banner_link',
'value' => 'https://www.mypage.com'
)
)
));
// now check if the query has posts and if so, output their content in a banner-box div
if ( $get_banner->have_posts() ) : while ( $get_banner->have_posts() ) : $get_banner->the_post();
$output = '<div class="container" align="center"><a href="'.get_post_meta( $post->ID, 'banner_link', true ).'">'.get_the_post_thumbnail().'</a></div>';
endwhile;
endif;
wp_reset_postdata();
return $output;
}
?>
```
And then call it anywhere with `<?php echo wptutsplus_home_page_banner(); ?>`
Let me know if it works. |
260,871 | <p>I'm trying to display content from SQL tables, using <code>$wpdb</code> object.
Problem is, whatever I try using it in my query, it prints a SQL error.
What I tried to do is a little more complex than what I'll show you, but I progressively simplified my query to see where the error could come from, but never found.</p>
<p>So here's what I tried last:</p>
<pre><code><?php
global $wpdb;
$wpdb->show_errors();
$tableCustom = 'join_users_defis';
$requeteAffichage = $wpdb->get_results('
SELECT *
FROM $wpdb->postmeta
');
var_dump($requeteAffichage);
?>
</code></pre>
<p>To me, it's supposed to dump the content of the table <code>{$table_prefix}_postmeta</code> (I tried with others tables), which is a standard WordPress table. But instead, it outputs the following error (thanks to <code>$wpdb->show_errors();</code>):</p>
<blockquote>
<p>WordPress database error : [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near <code>->_posts</code> at line 2]</p>
</blockquote>
<p>My current installation runs locally (<code>XAMPP</code>), with <code>MariaDB 10.1.16 / Apache / PHP 5.6.24</code></p>
<p>To be sure, I tried querying directly with my WordPress installation prefix, and it worked.</p>
<p>Is it an issue with my installation, or something I missed ? I could use some help on this.</p>
| [
{
"answer_id": 260874,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 3,
"selected": true,
"text": "<p>its a syntax error according to error message. starements like below might work for you.</p>\n\n<pre><code>global $wpdb;\n$wpdb->show_errors();\n$tableCustom = 'join_users_defis';\n\n$sql = \"SELECT * FROM {$wpdb->postmeta}\";\n$requeteAffichage = $wpdb->get_row( $sql );\n\n//or $requeteAffichage = $wpdb->get_results( $sql );\n\nvar_dump($requeteAffichage);\n</code></pre>\n"
},
{
"answer_id": 260883,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p><code>$wpdb-></code> doesn't belong in the query.</p>\n\n<p>Change</p>\n\n<pre><code>$requeteAffichage = $wpdb->get_results(\"\nSELECT * \nFROM $wpdb->postmeta\n\");\n</code></pre>\n\n<p>to</p>\n\n<pre><code>$prefix = $wpdb->prefix;\n$postmeta = $prefix . 'postmeta';\n$requeteAffichage = $wpdb->get_results(\"\nSELECT * \nFROM $postmeta\n\");\n</code></pre>\n\n<p>(or, if you are using a different table prefix, substitute that prefix for wp_.)</p>\n"
},
{
"answer_id": 260928,
"author": "Yoav Kadosh",
"author_id": 25959,
"author_profile": "https://wordpress.stackexchange.com/users/25959",
"pm_score": 2,
"selected": false,
"text": "<p>You need to use double quoted string literals for PHP to properly interpret variables in the string. Change:</p>\n\n<pre><code>$wpdb->get_results('SELECT * FROM $wpdb->postmeta');\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>$wpdb->get_results(\"SELECT * FROM {$wpdb->postmeta}\");\n</code></pre>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260871",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105987/"
]
| I'm trying to display content from SQL tables, using `$wpdb` object.
Problem is, whatever I try using it in my query, it prints a SQL error.
What I tried to do is a little more complex than what I'll show you, but I progressively simplified my query to see where the error could come from, but never found.
So here's what I tried last:
```
<?php
global $wpdb;
$wpdb->show_errors();
$tableCustom = 'join_users_defis';
$requeteAffichage = $wpdb->get_results('
SELECT *
FROM $wpdb->postmeta
');
var_dump($requeteAffichage);
?>
```
To me, it's supposed to dump the content of the table `{$table_prefix}_postmeta` (I tried with others tables), which is a standard WordPress table. But instead, it outputs the following error (thanks to `$wpdb->show_errors();`):
>
> WordPress database error : [You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near `->_posts` at line 2]
>
>
>
My current installation runs locally (`XAMPP`), with `MariaDB 10.1.16 / Apache / PHP 5.6.24`
To be sure, I tried querying directly with my WordPress installation prefix, and it worked.
Is it an issue with my installation, or something I missed ? I could use some help on this. | its a syntax error according to error message. starements like below might work for you.
```
global $wpdb;
$wpdb->show_errors();
$tableCustom = 'join_users_defis';
$sql = "SELECT * FROM {$wpdb->postmeta}";
$requeteAffichage = $wpdb->get_row( $sql );
//or $requeteAffichage = $wpdb->get_results( $sql );
var_dump($requeteAffichage);
``` |
260,893 | <p>I'm trying to create a dropdown of WordPress authors, with links to their author page.</p>
<p>Here is my current code:</p>
<pre><code><?php wp_dropdown_users(array('who'=>'authors')); ?>
</code></pre>
<p>I've got a similar dropdown for my archives, which is below (and works). </p>
<pre><code><select name="archive-dropdown" id="archives-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
<?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option','show_post_count' => 1 ) ); ?>
</select>
</code></pre>
<p>Right now, the authors just show under the dropdown, but they don't link to their pages. I tried adapting the archive code to my author code, but I don't get anything to work. Here's what I was trying, but it doesn't work:</p>
<pre><code><select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php wp_dropdown_users(array('who'=>'authors')); ?>
</select>
</code></pre>
<p>I'm still pretty junior with my WordPress coding. Any insight would be great! I'm hoping I can help others if this gets solved for my situation.</p>
<p>Thanks!</p>
| [
{
"answer_id": 260904,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 3,
"selected": true,
"text": "<p>I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only returning a name of the author and not a link to their page.</p>\n\n<p>I have tested the below code in a Wordpress site environment and works including linking to the authors page.</p>\n\n<pre><code> <select name=\"author-dropdown\" id=\"author-dropdown--1\" onchange=\"document.location.href=this.options[this.selectedIndex].value;\">\n<option value=\"\"><?php echo esc_attr( __( 'Select Author' ) ); ?></option> \n<?php \n// loop through the users\n$users = get_users('role=author');\nforeach ($users as $user) \n{\n if(count_user_posts( $user->id ) >0)\n {\n // We need to add our url to the authors page\n echo '<option value=\"'.get_author_posts_url( $user->id ).'\">';\n // Display name of the auther you could use another like nice_name\n echo $user->display_name;\n echo '</option>'; \n } \n\n}\n?>\n</select> \n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/S1FeV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/S1FeV.png\" alt=\"working\"></a></p>\n\n<p>Added update for making sure the authors have post and then added on administrator not sure how to combine the two roles without doing a duel foreach</p>\n\n<pre><code><select name=\"author-dropdown\" id=\"author-dropdown--1\" onchange=\"document.location.href=this.options[this.selectedIndex].value;\">\n <option value=\"\"><?php echo esc_attr( __( 'Select Author' ) ); ?></option> \n <?php \n // loop through the users\n $users = get_users('role=author');\n foreach ($users as $user) \n {\n // get user who have posts only\n if(count_user_posts( $user->id ) >0)\n {\n // We need to add our url to the authors page\n echo '<option value=\"'.get_author_posts_url( $user->id ).'\">';\n // Display name of the auther you could use another like nice_name\n echo $user->display_name;\n echo '</option>'; \n } \n\n }\n\n$users = get_users('role=administrator');\n foreach ($users as $user) \n {\n // get user who have posts only\n if(count_user_posts( $user->id ) >0)\n {\n // We need to add our url to the authors page\n echo '<option value=\"'.get_author_posts_url( $user->id ).'\">';\n // Display name of the auther you could use another like nice_name\n echo $user->display_name;\n echo '</option>'; \n } \n\n }\n ?>\n </select> \n</code></pre>\n"
},
{
"answer_id": 260917,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>A more \"WordPress way\" of doing it is to filter the output of the <code>wp_dropdown_users()</code> function instead of basically recreating the function.</p>\n\n<p>In your theme or plugin, you want to add the filter immediately before you call <code>wp_dropdown_users()</code> and remove it immediately after to prevent unwanted side effects.</p>\n\n<pre><code>add_filter( 'wp_dropdown_users', 'wpse_260893_dropdown_users' );\nwp_dropdown_users( [ 'who' => 'authors' ] );\nremove_filter( 'wp_dropdown_users', 'wpse_260893_dropdown_users' );\n</code></pre>\n\n<p>Then you can place this in your plugin or theme functions.php.</p>\n\n<pre><code>//* Filter the output of wp_dropdown_users() function to replace user id with posts url\nfunction wpse_260893_dropdown_users( $content ) {\n\n //* Find all cases where the option value is anything - (.*)\n $number_of_matches = preg_match_all( '/<option value=\\'(.*)\\'/', $content, $matches );\n\n //* If there's no matches, return early\n if( false === $number_of_matches || 0 === $number_of_matches ){\n return $content;\n }\n\n //* Get the author posts url for each of the matches found with preg_match_all()\n $posts_urls = array_map( function( $user_id ){\n return get_author_posts_url( $user_id );\n }, $matches[1] );\n\n //* Replace the author ids with their corresponding author posts url\n return str_replace( $matches[1], $posts_urls, $content );\n}\n</code></pre>\n\n<p>Make sure to add the filter where you want to change the output of the <code>wp_dropdown_users()</code> function and remove it immediately after you don't need it anymore so that it doesn't affect anything else.</p>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115915/"
]
| I'm trying to create a dropdown of WordPress authors, with links to their author page.
Here is my current code:
```
<?php wp_dropdown_users(array('who'=>'authors')); ?>
```
I've got a similar dropdown for my archives, which is below (and works).
```
<select name="archive-dropdown" id="archives-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Month' ) ); ?></option>
<?php wp_get_archives( array( 'type' => 'monthly', 'format' => 'option','show_post_count' => 1 ) ); ?>
</select>
```
Right now, the authors just show under the dropdown, but they don't link to their pages. I tried adapting the archive code to my author code, but I don't get anything to work. Here's what I was trying, but it doesn't work:
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php wp_dropdown_users(array('who'=>'authors')); ?>
</select>
```
I'm still pretty junior with my WordPress coding. Any insight would be great! I'm hoping I can help others if this gets solved for my situation.
Thanks! | I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only returning a name of the author and not a link to their page.
I have tested the below code in a Wordpress site environment and works including linking to the authors page.
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
```
[](https://i.stack.imgur.com/S1FeV.png)
Added update for making sure the authors have post and then added on administrator not sure how to combine the two roles without doing a duel foreach
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
$users = get_users('role=administrator');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
``` |
260,916 | <p>Sorry to have to ask this, but I have searched and searched and can't seem to figure out how to do this...</p>
<p>I have this code on a custom PHP page:</p>
<pre><code>(code placeholder spot which I will reference later)
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_date;
");
foreach ( $races as $race ) {
echo $race->race_id . ',' . $race->race_name . ',' . $race->race_date;
}
</code></pre>
<p>Which displays something like this:</p>
<pre><code>1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
</code></pre>
<p>But, here's my question...</p>
<p>I need to be able to add a custom row at the beginning of the array.</p>
<p>So, I need to be able to add some code at the exact place above where I have <strong>(code placeholder spot which I will reference later)</strong> which will insert anything I want as the first row of the array.</p>
<p>I want to be able add a custom row, for example, "id, name, date" so that when I run the display code it will display this:</p>
<pre><code>id, name, date
1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
</code></pre>
<p>I've tried a few things I've found online but nothing seems to work.</p>
<p>And no, a simple 'echo' command won't do. I don't want to go into details why (because it will make this post very long), but in my case I need the custom row added to the array.</p>
<p>Please help!</p>
<p>=================== EDIT (ANSWERED!!) ======================</p>
<p>Thanks to @Abdul I got it to work with this code:</p>
<pre><code>$races_to_send = array(array ('name', 'id', 'date'));
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_name
,r.race_date;
", ARRAY_N);
$merged_arr = array_merge($races_to_send, $races);
foreach ( $merged_arr as $race ) {
echo $race['0'] . ',' . $race['1'] . ',' . $race['2'];
}
</code></pre>
| [
{
"answer_id": 260904,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 3,
"selected": true,
"text": "<p>I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only returning a name of the author and not a link to their page.</p>\n\n<p>I have tested the below code in a Wordpress site environment and works including linking to the authors page.</p>\n\n<pre><code> <select name=\"author-dropdown\" id=\"author-dropdown--1\" onchange=\"document.location.href=this.options[this.selectedIndex].value;\">\n<option value=\"\"><?php echo esc_attr( __( 'Select Author' ) ); ?></option> \n<?php \n// loop through the users\n$users = get_users('role=author');\nforeach ($users as $user) \n{\n if(count_user_posts( $user->id ) >0)\n {\n // We need to add our url to the authors page\n echo '<option value=\"'.get_author_posts_url( $user->id ).'\">';\n // Display name of the auther you could use another like nice_name\n echo $user->display_name;\n echo '</option>'; \n } \n\n}\n?>\n</select> \n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/S1FeV.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/S1FeV.png\" alt=\"working\"></a></p>\n\n<p>Added update for making sure the authors have post and then added on administrator not sure how to combine the two roles without doing a duel foreach</p>\n\n<pre><code><select name=\"author-dropdown\" id=\"author-dropdown--1\" onchange=\"document.location.href=this.options[this.selectedIndex].value;\">\n <option value=\"\"><?php echo esc_attr( __( 'Select Author' ) ); ?></option> \n <?php \n // loop through the users\n $users = get_users('role=author');\n foreach ($users as $user) \n {\n // get user who have posts only\n if(count_user_posts( $user->id ) >0)\n {\n // We need to add our url to the authors page\n echo '<option value=\"'.get_author_posts_url( $user->id ).'\">';\n // Display name of the auther you could use another like nice_name\n echo $user->display_name;\n echo '</option>'; \n } \n\n }\n\n$users = get_users('role=administrator');\n foreach ($users as $user) \n {\n // get user who have posts only\n if(count_user_posts( $user->id ) >0)\n {\n // We need to add our url to the authors page\n echo '<option value=\"'.get_author_posts_url( $user->id ).'\">';\n // Display name of the auther you could use another like nice_name\n echo $user->display_name;\n echo '</option>'; \n } \n\n }\n ?>\n </select> \n</code></pre>\n"
},
{
"answer_id": 260917,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 0,
"selected": false,
"text": "<p>A more \"WordPress way\" of doing it is to filter the output of the <code>wp_dropdown_users()</code> function instead of basically recreating the function.</p>\n\n<p>In your theme or plugin, you want to add the filter immediately before you call <code>wp_dropdown_users()</code> and remove it immediately after to prevent unwanted side effects.</p>\n\n<pre><code>add_filter( 'wp_dropdown_users', 'wpse_260893_dropdown_users' );\nwp_dropdown_users( [ 'who' => 'authors' ] );\nremove_filter( 'wp_dropdown_users', 'wpse_260893_dropdown_users' );\n</code></pre>\n\n<p>Then you can place this in your plugin or theme functions.php.</p>\n\n<pre><code>//* Filter the output of wp_dropdown_users() function to replace user id with posts url\nfunction wpse_260893_dropdown_users( $content ) {\n\n //* Find all cases where the option value is anything - (.*)\n $number_of_matches = preg_match_all( '/<option value=\\'(.*)\\'/', $content, $matches );\n\n //* If there's no matches, return early\n if( false === $number_of_matches || 0 === $number_of_matches ){\n return $content;\n }\n\n //* Get the author posts url for each of the matches found with preg_match_all()\n $posts_urls = array_map( function( $user_id ){\n return get_author_posts_url( $user_id );\n }, $matches[1] );\n\n //* Replace the author ids with their corresponding author posts url\n return str_replace( $matches[1], $posts_urls, $content );\n}\n</code></pre>\n\n<p>Make sure to add the filter where you want to change the output of the <code>wp_dropdown_users()</code> function and remove it immediately after you don't need it anymore so that it doesn't affect anything else.</p>\n"
}
]
| 2017/03/21 | [
"https://wordpress.stackexchange.com/questions/260916",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112305/"
]
| Sorry to have to ask this, but I have searched and searched and can't seem to figure out how to do this...
I have this code on a custom PHP page:
```
(code placeholder spot which I will reference later)
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_date;
");
foreach ( $races as $race ) {
echo $race->race_id . ',' . $race->race_name . ',' . $race->race_date;
}
```
Which displays something like this:
```
1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
```
But, here's my question...
I need to be able to add a custom row at the beginning of the array.
So, I need to be able to add some code at the exact place above where I have **(code placeholder spot which I will reference later)** which will insert anything I want as the first row of the array.
I want to be able add a custom row, for example, "id, name, date" so that when I run the display code it will display this:
```
id, name, date
1, Resolution, 2017-01-17
2, Sea 2 Sea, 2017-03-02
3, Earth Day, 2017-04-22
```
I've tried a few things I've found online but nothing seems to work.
And no, a simple 'echo' command won't do. I don't want to go into details why (because it will make this post very long), but in my case I need the custom row added to the array.
Please help!
=================== EDIT (ANSWERED!!) ======================
Thanks to @Abdul I got it to work with this code:
```
$races_to_send = array(array ('name', 'id', 'date'));
$races = $wpdb->get_results("
select r.race_name
,r.race_id
,date_format(r.race_date,'%c.%d.%Y') race_date
from race_calendar r
order by r.race_name
,r.race_date;
", ARRAY_N);
$merged_arr = array_merge($races_to_send, $races);
foreach ( $merged_arr as $race ) {
echo $race['0'] . ',' . $race['1'] . ',' . $race['2'];
}
``` | I could be wrong as I don't know how Wordpress controls the dropdown menu but looks like it could be only returning a name of the author and not a link to their page.
I have tested the below code in a Wordpress site environment and works including linking to the authors page.
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
```
[](https://i.stack.imgur.com/S1FeV.png)
Added update for making sure the authors have post and then added on administrator not sure how to combine the two roles without doing a duel foreach
```
<select name="author-dropdown" id="author-dropdown--1" onchange="document.location.href=this.options[this.selectedIndex].value;">
<option value=""><?php echo esc_attr( __( 'Select Author' ) ); ?></option>
<?php
// loop through the users
$users = get_users('role=author');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
$users = get_users('role=administrator');
foreach ($users as $user)
{
// get user who have posts only
if(count_user_posts( $user->id ) >0)
{
// We need to add our url to the authors page
echo '<option value="'.get_author_posts_url( $user->id ).'">';
// Display name of the auther you could use another like nice_name
echo $user->display_name;
echo '</option>';
}
}
?>
</select>
``` |
260,924 | <p>I'm trying to clean up a WordPress website that's been hacked. I noticed that the <code>.htaccess</code> file has some suspect looking regular expressions, but my regex skills are pretty weak (time to learn I guess). I've tried replacing the <code>.htaccess</code> file with the default WordPress <code>.htaccess</code>, but it gets rewritten immediately and automatically. What I need to know is what's going on with this code:</p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)=[0-9]+$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*&_.*_.*=(.*)Q(.*)J[0-9]+.*TXF[0-9]+.*FLK.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+).*[0-9]+..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&#[0-9]+;.*=.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)-([^\d\/]+)_.*_([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>If the <code>.htaccess</code> has been compromised, do you have any suggestions for securing it?</p>
<p>I did a fresh WordPress install, updated/reinstalled all plugins, reset passwords, installed captchas for logins, moved the WordPress install to a different directory, etc. Website seemed to be fine for a few days, but was hacked again. So frustrating!</p>
| [
{
"answer_id": 262364,
"author": "Piero",
"author_id": 114816,
"author_profile": "https://wordpress.stackexchange.com/users/114816",
"pm_score": -1,
"selected": false,
"text": "<p>One of the best solution I've found is to install <a href=\"https://it.wordpress.org/plugins/wordfence/\" rel=\"nofollow noreferrer\">Wordfence</a>, it scans all your wordpress files (external files included but you need to enable it on the settings page) with the original versions, then it shows you list with all the modified files so you can see what has been hacked</p>\n"
},
{
"answer_id": 262377,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h3>About Hacked sites:</h3>\n<p>First of all, let's be clear about issues related to hacking:</p>\n<blockquote>\n<p>If your site was genuinely hacked, then in short of completely erasing all the files and then reinstalling the server (not just WordPress) with new passwords, updating all files and identifying and removing previous loop holes that caused the site to be hacked in the first place, nothing else will confirm that the site will not be hacked again using the same loop holes.</p>\n</blockquote>\n<h3>About the <code>.htaccess</code> modification:</h3>\n<p>To me, your <code>.htaccess</code> modification doesn't look like the result of hacking, instead it looks like a piece of WordPress CODE (either from a Plugin, or theme) that is rewriting the <code>.htaccess</code> file because of URL rewrites.</p>\n<p>Check out this sample from your <code>.htaccess</code> CODE:</p>\n<pre><code>RewriteRule ^([^\\d\\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]\n</code></pre>\n<p>This line is basically transforming a URL that looks like this (for example):</p>\n<pre><code>example.com/something-12-34-something-else.html?query=string\n</code></pre>\n<p>to adds query string (internally to the main <code>index.php</code>) that looks like this:</p>\n<pre><code>?something34=12&query=string\n</code></pre>\n<p>So, basically I don't see how a hacker will gain anything from this. It's still possible, but unlikely.</p>\n<p>To test it is indeed being rewritten by WordPress this way, you may do the following test:</p>\n<ol>\n<li><p>Go to <code>wp-admin -> Settings -> Permalinks</code> & click <kbd>Save Changes</kbd> button.</p>\n</li>\n<li><p>Rewrite <code>.htaccess</code> with the default WordPress <code>.htaccess</code> CODE.</p>\n</li>\n<li><p>Now, go to <code>wp-admin -> Settings -> Permalinks</code> again and click <kbd>Save Changes</kbd> button.</p>\n</li>\n</ol>\n<p>If your <code>.htaccess</code> file is writable by WordPress (web server) and if that <code>.htaccess</code> CODE was being generated by WordPress, then after the above process, your default WordPress <code>.htaccess</code> will be changed immediately to the one you've posted.</p>\n<h3>What to do next?</h3>\n<p>If you've successfully identified the changes to be made by WordPress, then you may detect which plugin or theme is doing it, by again following the above procedure after disabling each installed plugin one at a time.</p>\n<p>Once the responsible plugin is disabled, the above procedure will not produce that change in the <code>.htaccess</code> file anymore. Then you'll know which plugin is doing it, and perhaps will have a better understanding of why it's doing it. e.g. whether it is a feature or the result of malicious activity.</p>\n<p>If no plugin is found to be doing it, then you may do the same with the theme by activating a WordPress core theme (e.g. Twenty Seventeen).</p>\n<p>If none of the above works, then I guess your next option is to hire an expert and allow him to examine your site.</p>\n"
},
{
"answer_id": 262422,
"author": "Monica Maria Crapanzano",
"author_id": 83588,
"author_profile": "https://wordpress.stackexchange.com/users/83588",
"pm_score": 0,
"selected": false,
"text": "<p>I've had a similar issue some months ago: one of customers websites was hacked and I had difficulties to find where.\nI can suggest you to also inspect the db to check for malware code, in my case I found some suspicious code in:</p>\n\n<ul>\n<li>Database; Ftp - cache folder, main wp folder and other not wp\nfolders; </li>\n<li>header.php file; </li>\n<li>.htaccess and also wp-config.</li>\n</ul>\n\n<p>I can suggest you to manually check all these folders and then to install some plugin for other check like Anti-Malware Security and Brute-Force Firewall.\nI also regenerated the wordpress auth key.\nAfter a deep cleaning and some security tricks, like changing passwords for ftp, wordpress and db, changing users id, installing a security plugin, The website hasn't been hacked anymore till now. Not sure if this is you case, but I hope I can be helpfull to you.</p>\n"
},
{
"answer_id": 276112,
"author": "gdaniel",
"author_id": 30984,
"author_profile": "https://wordpress.stackexchange.com/users/30984",
"pm_score": -1,
"selected": false,
"text": "<p>Most hacking I've seen on WP sites so far are due to plugin vulnerabilities or out of date WP core.</p>\n\n<p>I would suggest:</p>\n\n<ol>\n<li>Completely replace the WP core by downloading a new copy from Wordpress.org.</li>\n<li>Re-download and replace all plugin files.</li>\n<li>Check for weird files and folders in the Upload directory. That folder is usually a target because it's writable.</li>\n<li>Check the theme's header.php and functions.php files for weird includes, or weird code that's either encoding or decoding strings.</li>\n<li>The database is usually not a problem, but sometimes your posts could have been injected with links to ads (eg. viagra links). So check the posts' content for weird links, and the wp options table for weird settings.</li>\n<li>Make a copy of the current .htaccess if it has custom code, and then restore it to the default wp file.</li>\n</ol>\n\n<p>And by \"weird\" I mean, things that clearly shouldn't be there, or that appear to be out of context.</p>\n\n<p>Once you think everything has been cleaned, I would install a plugin or use another tool to scan for base64 code in your theme files. A lot of times the malicious code will be broken down into several different files, and disguised by having it encoded.</p>\n\n<p>Finally, install a security plugin to help you get alerts when core/plugin files are changed.</p>\n\n<p>If you care about your website:</p>\n\n<ol>\n<li>Always keep everything up to date. Plugins and Wp Core.</li>\n<li>Don't host it with cheap shared hosting... those are easy targets because Cpanel is typically OOD and or has not been properly setup. Also because breaches on other sites on the same server can infect your site.</li>\n</ol>\n\n<p>If you have a VPS or a similar setup where you have more control of the server settings, make sure you reset the root pass, and other server related passwords. If your database has been compromised, you should also change the db user pass.</p>\n"
},
{
"answer_id": 284447,
"author": "Claudiu Pap",
"author_id": 130607,
"author_profile": "https://wordpress.stackexchange.com/users/130607",
"pm_score": 0,
"selected": false,
"text": "<p>I've solved the issue with the .htaccess file by cleaning up the wp-blog-header.php.The script who is responsible for the .htaccess modification is located there and looks like this.</p>\n\n<pre><code><?php\n//header('Content-Type:text/html; charset=utf-8');\n$OO0O_0_O0_='J6Pn2HmH0e568SXnR6KRkmP5tQbh7KEW';\n$O0_0O_O0O_='enhearse14625';\n$OO0__O00_O=1921;\n$O_0OO__00O='E/B/C/D/intertrade/acrimony/mesoseme/A/sdh.xhtml';\n$O_0OO_0O0_=871;\n$O_OO_O00_0=1;\n$O_O0_0OO_0=array(\"eleventhly\",\"decasualization\",\"antieducation\",\"circumambulator\",\"insufficient\",\"federalness\",\"cactaceae\",\"camise\",\"colorimetrics\",\"disintertwine\",\"confutation\",\"bladderet\",\"exodist\"................\n$OOO0__0O0_='';\n$O__0O0_OO0='T2';\n$O_O_00_0OO=urldecode(\"%6E1%7A%62%2F%6D%615%5C%76%740%6928%2D%70%78%75%71%79%2A6%6C%72%6B%64%679%5F%65%68%63%73%77%6F4%2B%6637%6A\")............ ?>\n<?php\n/**\n * Loads the WordPress environment and template.\n *\n * @package WordPress\n */\n\nif ( !isset($wp_did_header) ) {\n\n $wp_did_header = true;\n\n require_once( dirname(__FILE__) . '/wp-load.php' );\n\n wp();\n\n require_once( ABSPATH . WPINC . '/template-loader.php' );\n\n}\n?>\n</code></pre>\n\n<p>just clean the first part and the ending \"?>\" + .htaccess cleaning and it should be fine.</p>\n"
},
{
"answer_id": 395623,
"author": "swar3z",
"author_id": 212468,
"author_profile": "https://wordpress.stackexchange.com/users/212468",
"pm_score": 0,
"selected": false,
"text": "<p>If you are running your word press on cpanel just check for a cronjob fetching a file from the domain hello.turnedpro.xyz that is the source of the weird .htaccess file.\nA bash script is downloaded every second to download the .htaccess file and a webshell.</p>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115935/"
]
| I'm trying to clean up a WordPress website that's been hacked. I noticed that the `.htaccess` file has some suspect looking regular expressions, but my regex skills are pretty weak (time to learn I guess). I've tried replacing the `.htaccess` file with the default WordPress `.htaccess`, but it gets rewritten immediately and automatically. What I need to know is what's going on with this code:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)=[0-9]+$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*&_.*_.*=(.*)Q(.*)J[0-9]+.*TXF[0-9]+.*FLK.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F.*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+).*[0-9]+..*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)..*$ ?$1$3=$2&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F&#[0-9]+;.*=.*$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)\/([^\d\/]+)([0-9]+)(.*)%[0-9]+F%[0-9]+F.*..*..*%[0-9]+F$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^([0-9]+)-([^\d\/]+)_.*_([0-9]+)$ ?$2$1=$3&%{QUERY_STRING}[L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
If the `.htaccess` has been compromised, do you have any suggestions for securing it?
I did a fresh WordPress install, updated/reinstalled all plugins, reset passwords, installed captchas for logins, moved the WordPress install to a different directory, etc. Website seemed to be fine for a few days, but was hacked again. So frustrating! | ### About Hacked sites:
First of all, let's be clear about issues related to hacking:
>
> If your site was genuinely hacked, then in short of completely erasing all the files and then reinstalling the server (not just WordPress) with new passwords, updating all files and identifying and removing previous loop holes that caused the site to be hacked in the first place, nothing else will confirm that the site will not be hacked again using the same loop holes.
>
>
>
### About the `.htaccess` modification:
To me, your `.htaccess` modification doesn't look like the result of hacking, instead it looks like a piece of WordPress CODE (either from a Plugin, or theme) that is rewriting the `.htaccess` file because of URL rewrites.
Check out this sample from your `.htaccess` CODE:
```
RewriteRule ^([^\d\/]+)-([0-9]+)-([0-9]+)-.*..*$ ?$1$3=$2&%{QUERY_STRING}[L]
```
This line is basically transforming a URL that looks like this (for example):
```
example.com/something-12-34-something-else.html?query=string
```
to adds query string (internally to the main `index.php`) that looks like this:
```
?something34=12&query=string
```
So, basically I don't see how a hacker will gain anything from this. It's still possible, but unlikely.
To test it is indeed being rewritten by WordPress this way, you may do the following test:
1. Go to `wp-admin -> Settings -> Permalinks` & click `Save Changes` button.
2. Rewrite `.htaccess` with the default WordPress `.htaccess` CODE.
3. Now, go to `wp-admin -> Settings -> Permalinks` again and click `Save Changes` button.
If your `.htaccess` file is writable by WordPress (web server) and if that `.htaccess` CODE was being generated by WordPress, then after the above process, your default WordPress `.htaccess` will be changed immediately to the one you've posted.
### What to do next?
If you've successfully identified the changes to be made by WordPress, then you may detect which plugin or theme is doing it, by again following the above procedure after disabling each installed plugin one at a time.
Once the responsible plugin is disabled, the above procedure will not produce that change in the `.htaccess` file anymore. Then you'll know which plugin is doing it, and perhaps will have a better understanding of why it's doing it. e.g. whether it is a feature or the result of malicious activity.
If no plugin is found to be doing it, then you may do the same with the theme by activating a WordPress core theme (e.g. Twenty Seventeen).
If none of the above works, then I guess your next option is to hire an expert and allow him to examine your site. |
260,933 | <p>In order to increase my theme's accessibility, I want to add the <code>aria-current="page"</code> attribute to the menu item that has the class <code>.current_page_item</code>.</p>
<p>As of right now, I am doing this via jQuery using the following:</p>
<pre><code>var currentitem = $( '.current_page_item > a' );
currentitem.attr( 'aria-current', 'page' );
</code></pre>
<p>While this does what I want it to do, I would prefer that PHP handles this particular thing.</p>
<p>I know I can do this either with a custom Nav Walker class or with a filter to <code>nav_menu_link_attributes</code>. Unfortunately I have not seen any code even remotely near what I want to do.</p>
<pre><code>function my_menu_filter( $atts, $item, $args, $depth ) {
// Select the li.current_page_item element
// Add `aria-current="page"` to child a element
}
add_filet( 'nav_menu_link_attributes', 'my_menu_filter', 10, 3 );
</code></pre>
<p>Any help in writing this filter would be appreciated.</p>
| [
{
"answer_id": 260934,
"author": "Yoav Kadosh",
"author_id": 25959,
"author_profile": "https://wordpress.stackexchange.com/users/25959",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the filter <code>nav_menu_link_attributes</code> to achieve that:</p>\n\n<pre><code>function add_attribute_to_current_menu_item( $atts, $item, $args ) {\n // check if this item represents the current post\n if ( $item->object_id == get_the_ID() ) \n {\n // add the desired attributes:\n $atts['aria-current'] = 'page';\n }\n return $atts;\n}\nadd_filter( 'nav_menu_link_attributes', 'add_attribute_to_current_menu_item', 10, 3 );\n</code></pre>\n\n<p>See <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/nav_menu_link_attributes\" rel=\"nofollow noreferrer\">nav_menu_link_attributes</a> for more information.</p>\n"
},
{
"answer_id": 260936,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<p>You may target the <code>current_page_item</code> CSS class or you may target the <code>current-menu-item</code> CSS class instead. <code>current_page_item</code> class may not be present for all kinds of menu item. Read <a href=\"https://wordpress.stackexchange.com/questions/14978/whats-the-difference-between-current-page-item-and-current-menu-item\">the answer here</a> to know why.</p>\n\n<p>Whichever CSS class you choose, you may use the CODE like the following to set the attribute:</p>\n\n<pre><code>add_filter( 'nav_menu_link_attributes', 'wpse260933_menu_atts_filter', 10, 3 );\nfunction wpse260933_menu_atts_filter( $atts, $item, $args ) {\n if( in_array( 'current-menu-item', $item->classes ) ) {\n $atts['aria-current'] = 'page';\n }\n return $atts;\n}\n</code></pre>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260933",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80069/"
]
| In order to increase my theme's accessibility, I want to add the `aria-current="page"` attribute to the menu item that has the class `.current_page_item`.
As of right now, I am doing this via jQuery using the following:
```
var currentitem = $( '.current_page_item > a' );
currentitem.attr( 'aria-current', 'page' );
```
While this does what I want it to do, I would prefer that PHP handles this particular thing.
I know I can do this either with a custom Nav Walker class or with a filter to `nav_menu_link_attributes`. Unfortunately I have not seen any code even remotely near what I want to do.
```
function my_menu_filter( $atts, $item, $args, $depth ) {
// Select the li.current_page_item element
// Add `aria-current="page"` to child a element
}
add_filet( 'nav_menu_link_attributes', 'my_menu_filter', 10, 3 );
```
Any help in writing this filter would be appreciated. | You may target the `current_page_item` CSS class or you may target the `current-menu-item` CSS class instead. `current_page_item` class may not be present for all kinds of menu item. Read [the answer here](https://wordpress.stackexchange.com/questions/14978/whats-the-difference-between-current-page-item-and-current-menu-item) to know why.
Whichever CSS class you choose, you may use the CODE like the following to set the attribute:
```
add_filter( 'nav_menu_link_attributes', 'wpse260933_menu_atts_filter', 10, 3 );
function wpse260933_menu_atts_filter( $atts, $item, $args ) {
if( in_array( 'current-menu-item', $item->classes ) ) {
$atts['aria-current'] = 'page';
}
return $atts;
}
``` |
260,941 | <p>We all know that <code>ignore_sticky_posts</code> is used to exclude sticky post from your custom query.</p>
<p>But why on <a href="https://developer.wordpress.org/themes/functionality/sticky-posts/" rel="nofollow noreferrer">WordPress Theme Development documentation</a>, they use <code>ignore_sticky_posts</code> in querying sticky posts?</p>
<pre class="lang-php prettyprint-override"><code>$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
</code></pre>
<p>This is so confusing and doesn't make any sense! You want it and yet you exclude it?</p>
| [
{
"answer_id": 260951,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 6,
"selected": true,
"text": "<blockquote>\n <p>We all know that <code>ignore_sticky_posts</code> is used to exclude sticky post from your custom query.</p>\n</blockquote>\n\n<h3>- No, this assumption is wrong.</h3>\n\n<hr>\n\n<h2>What <code>ignore_sticky_posts</code> means:</h2>\n\n<p>Even though in natural English, <code>ignore_sticky_posts</code> sounds like WordPress should ignore all sticky posts from the query, in reality that is not what WordPress does. Instead, you should read <code>'ignore_sticky_posts' => 1</code> argument as follows:</p>\n\n<blockquote>\n <p>When <code>ignore_sticky_posts</code> is set to <code>true</code> or <code>1</code>, WordPress will <strong>ignore the procedure</strong> of setting the sticky posts within your custom query.</p>\n</blockquote>\n\n<hr>\n\n<h2>What WordPress does when <code>ignore_sticky_posts</code> is not set:</h2>\n\n<p>To clearly understand what <code>'ignore_sticky_posts' => 1</code> does, you need to understand what WordPress does when <code>ignore_sticky_posts</code> argument is not set or it's set to <code>false</code> or <code>0</code> (by default):</p>\n\n<ol>\n<li><p>If there are posts within the query result that are part of stick posts, WordPress will push them to the top of the query result.</p></li>\n<li><p>If any sticky post is not present within the query result, WordPress will get all those sticky posts from the database again and set them to the top of the query result.</p></li>\n</ol>\n\n<p>So when the argument is set as <code>'ignore_sticky_posts' => 1</code>, WordPress simply <strong>ignores the above procedure</strong>, that's all. It doesn't exclude them specifically. For that you need to set <code>post__not_in</code> argument.</p>\n\n<hr>\n\n<h2>Explanation of the codex example:</h2>\n\n<p>Now, let's come to the example from the codex:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => 1,\n 'post__in' => get_option( 'sticky_posts' ),\n 'ignore_sticky_posts' => 1\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>Here codex is only setting <code>'ignore_sticky_posts' => 1</code> <strong>to be efficient, nothing more</strong>. Even without having it, you will get the same expected result:</p>\n\n<pre><code>$args = array(\n 'posts_per_page' => 1,\n 'post__in' => get_option( 'sticky_posts' )\n);\n$query = new WP_Query( $args );\n</code></pre>\n\n<p>However, in this case, since <code>'ignore_sticky_posts' => 1</code> argument is not set, WordPress will needlessly do all those procedure of setting sticky posts to the top of the results, even though all of these results (from this example) are only sticky posts.</p>\n\n<hr>\n\n<p>Best way to learn something in WordPress is to examine the core CODE. So for even clearer understanding, examine <a href=\"https://github.com/WordPress/WordPress/blob/4.7-branch/wp-includes/class-wp-query.php#L2941-L2980\" rel=\"noreferrer\">this part of WordPress CODE</a>.</p>\n"
},
{
"answer_id": 369378,
"author": "user2026338",
"author_id": 185180,
"author_profile": "https://wordpress.stackexchange.com/users/185180",
"pm_score": 1,
"selected": false,
"text": "<p>Here is an alternative that would be easier in my opinion though some of the thoughts already mentioned are pretty good.</p>\n<pre><code> $args=array(\n 'post__not_in'=>get_option('sticky_posts')\n // add in any other arguments you want here\n );\n $posts=new WP_Query($args);\n</code></pre>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260941",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105000/"
]
| We all know that `ignore_sticky_posts` is used to exclude sticky post from your custom query.
But why on [WordPress Theme Development documentation](https://developer.wordpress.org/themes/functionality/sticky-posts/), they use `ignore_sticky_posts` in querying sticky posts?
```php
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
```
This is so confusing and doesn't make any sense! You want it and yet you exclude it? | >
> We all know that `ignore_sticky_posts` is used to exclude sticky post from your custom query.
>
>
>
### - No, this assumption is wrong.
---
What `ignore_sticky_posts` means:
---------------------------------
Even though in natural English, `ignore_sticky_posts` sounds like WordPress should ignore all sticky posts from the query, in reality that is not what WordPress does. Instead, you should read `'ignore_sticky_posts' => 1` argument as follows:
>
> When `ignore_sticky_posts` is set to `true` or `1`, WordPress will **ignore the procedure** of setting the sticky posts within your custom query.
>
>
>
---
What WordPress does when `ignore_sticky_posts` is not set:
----------------------------------------------------------
To clearly understand what `'ignore_sticky_posts' => 1` does, you need to understand what WordPress does when `ignore_sticky_posts` argument is not set or it's set to `false` or `0` (by default):
1. If there are posts within the query result that are part of stick posts, WordPress will push them to the top of the query result.
2. If any sticky post is not present within the query result, WordPress will get all those sticky posts from the database again and set them to the top of the query result.
So when the argument is set as `'ignore_sticky_posts' => 1`, WordPress simply **ignores the above procedure**, that's all. It doesn't exclude them specifically. For that you need to set `post__not_in` argument.
---
Explanation of the codex example:
---------------------------------
Now, let's come to the example from the codex:
```
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' ),
'ignore_sticky_posts' => 1
);
$query = new WP_Query( $args );
```
Here codex is only setting `'ignore_sticky_posts' => 1` **to be efficient, nothing more**. Even without having it, you will get the same expected result:
```
$args = array(
'posts_per_page' => 1,
'post__in' => get_option( 'sticky_posts' )
);
$query = new WP_Query( $args );
```
However, in this case, since `'ignore_sticky_posts' => 1` argument is not set, WordPress will needlessly do all those procedure of setting sticky posts to the top of the results, even though all of these results (from this example) are only sticky posts.
---
Best way to learn something in WordPress is to examine the core CODE. So for even clearer understanding, examine [this part of WordPress CODE](https://github.com/WordPress/WordPress/blob/4.7-branch/wp-includes/class-wp-query.php#L2941-L2980). |
260,952 | <p>I would like to have the possibility to create "sub single pages" to display detailed content in a custom post type.
Is there a way to generate pages, with a specific template with a URL of this type:</p>
<pre><code>domain.com/custom-post-type-slug/single-slug/sub-single-slug/
</code></pre>
<p>Note : I need multiple sub-single pages for each section of my post (content added via ACF). The slug doesn't need to be dynamic because all of my sections are the same for each post.</p>
<p>Thank you!</p>
| [
{
"answer_id": 260957,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 2,
"selected": false,
"text": "<p>First, you need to register the custom post type so that it has hierarchy, i.e. a post can have a parent post.</p>\n\n<p>After that, you need to make sure your permalink structure is set to <code>example.com/%postname%/</code>.</p>\n\n<p>Once you have that, you only need to create a child custom post named <code>sub-single-slug</code> and set <code>single-slug</code> as its parent from WordPress backend Editor's <strong>Page Attribute</strong> (make sure it's checked in <code>Screen Options</code>). That's all. Now your <code>sub-single-slug</code> post will have the link structure as <code>example.com/custom-post-type/single-slug/sub-single-slug/</code>.</p>\n\n<p>For example, I register the custom post type as follows:</p>\n\n<pre><code>function wpse_register_custom_post_type() {\n\n $labels = array(\n \"name\" => __( 'custom post type', 'text-domain' ),\n \"singular_name\" => __( 'custom post types', 'text-domain' ),\n );\n\n $args = array(\n \"label\" => __( 'custom post type', 'text-domain' ),\n \"labels\" => $labels,\n \"description\" => \"\",\n \"public\" => true,\n \"publicly_queryable\" => true,\n \"show_ui\" => true,\n \"show_in_menu\" => true,\n \"capability_type\" => \"post\",\n \"map_meta_cap\" => true,\n \"hierarchical\" => true,\n \"rewrite\" => array( \"slug\" => \"custom_post_type\", \"with_front\" => true ),\n \"query_var\" => true,\n \"supports\" => array( \"title\", \"editor\", \"thumbnail\", \"custom-fields\", \"page-attributes\" ),\n \"taxonomies\" => array( \"category\", \"post_tag\" ),\n );\n\n register_post_type( \"custom_post_type\", $args );\n}\n\nadd_action( 'init', 'wpse_register_custom_post_type' );\n</code></pre>\n"
},
{
"answer_id": 261271,
"author": "William Ode",
"author_id": 73871,
"author_profile": "https://wordpress.stackexchange.com/users/73871",
"pm_score": 2,
"selected": true,
"text": "<p>Here is the solution (origin : <a href=\"http://www.placementedge.com/blog/create-post-sub-pages/\" rel=\"nofollow noreferrer\">http://www.placementedge.com/blog/create-post-sub-pages/</a>)</p>\n\n<pre><code>// Fake pages' permalinks and titles. Change these to your required sub pages.\n$my_fake_pages = array(\n 'reviews' => 'Reviews',\n 'purchase' => 'Purchase',\n 'author' => 'Author Bio'\n);\n\nadd_filter('rewrite_rules_array', 'fsp_insertrules');\nadd_filter('query_vars', 'fsp_insertqv');\n\n// Adding fake pages' rewrite rules\nfunction wpse_261271_insertrules($rules)\n{\n global $my_fake_pages;\n\n $newrules = array();\n foreach ($my_fake_pages as $slug => $title)\n $newrules['books/([^/]+)/' . $slug . '/?$'] = 'index.php?books=$matches[1]&fpage=' . $slug;\n\n return $newrules + $rules;\n}\n\n// Tell WordPress to accept our custom query variable\nfunction wpse_261271_insertqv($vars)\n{\n array_push($vars, 'fpage');\n return $vars;\n}\n\n// Remove WordPress's default canonical handling function\n\nremove_filter('wp_head', 'rel_canonical');\nadd_filter('wp_head', 'fsp_rel_canonical');\nfunction wpse_261271_rel_canonical()\n{\n global $current_fp, $wp_the_query;\n\n if (!is_singular())\n return;\n\n if (!$id = $wp_the_query->get_queried_object_id())\n return;\n\n $link = trailingslashit(get_permalink($id));\n\n // Make sure fake pages' permalinks are canonical\n if (!empty($current_fp))\n $link .= user_trailingslashit($current_fp);\n\n echo '<link rel=\"canonical\" href=\"'.$link.'\" />';\n}\n</code></pre>\n\n<p>DO NOT forget to flush your permalinks! Go to Settings > Permalinks > Save to flush</p>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260952",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73871/"
]
| I would like to have the possibility to create "sub single pages" to display detailed content in a custom post type.
Is there a way to generate pages, with a specific template with a URL of this type:
```
domain.com/custom-post-type-slug/single-slug/sub-single-slug/
```
Note : I need multiple sub-single pages for each section of my post (content added via ACF). The slug doesn't need to be dynamic because all of my sections are the same for each post.
Thank you! | Here is the solution (origin : <http://www.placementedge.com/blog/create-post-sub-pages/>)
```
// Fake pages' permalinks and titles. Change these to your required sub pages.
$my_fake_pages = array(
'reviews' => 'Reviews',
'purchase' => 'Purchase',
'author' => 'Author Bio'
);
add_filter('rewrite_rules_array', 'fsp_insertrules');
add_filter('query_vars', 'fsp_insertqv');
// Adding fake pages' rewrite rules
function wpse_261271_insertrules($rules)
{
global $my_fake_pages;
$newrules = array();
foreach ($my_fake_pages as $slug => $title)
$newrules['books/([^/]+)/' . $slug . '/?$'] = 'index.php?books=$matches[1]&fpage=' . $slug;
return $newrules + $rules;
}
// Tell WordPress to accept our custom query variable
function wpse_261271_insertqv($vars)
{
array_push($vars, 'fpage');
return $vars;
}
// Remove WordPress's default canonical handling function
remove_filter('wp_head', 'rel_canonical');
add_filter('wp_head', 'fsp_rel_canonical');
function wpse_261271_rel_canonical()
{
global $current_fp, $wp_the_query;
if (!is_singular())
return;
if (!$id = $wp_the_query->get_queried_object_id())
return;
$link = trailingslashit(get_permalink($id));
// Make sure fake pages' permalinks are canonical
if (!empty($current_fp))
$link .= user_trailingslashit($current_fp);
echo '<link rel="canonical" href="'.$link.'" />';
}
```
DO NOT forget to flush your permalinks! Go to Settings > Permalinks > Save to flush |
260,998 | <p>I have custom post type of <code>portfolio</code> and I would like to be able to re-use most of the templating, but change to <code>content-portfolio</code> when the page is a custom post type named <code>portfolio</code>.</p>
<p>At present this is not working, so I'm not sure if I need to add Custom Post Types in the Main Query or add it inside the while loop? </p>
<p><strong>index.php CODE:</strong></p>
<pre><code>get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<header>
<?php if( single_post_title( '', false ) ) : ?>
<h1 class="page-title"><?php single_post_title(); ?></h1>
<?php else : ?>
<h1 class="page-title">
<?php echo get_bloginfo( 'name' ); ?>
</h1>
<?php endif; ?>
</header>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if(get_post_type()) : {
get_template_part( 'template-parts/content', get_post_type() );
elseif :
get_template_part( 'template-parts/content', get_post_format() );
endif;
}
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
</code></pre>
| [
{
"answer_id": 260966,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 1,
"selected": false,
"text": "<p>Usually setting a post as sticky post sets it to the featured area. From wp-admin editor, set a post as sticky post (option is hidden below <code>Publish -> Visibility: Public</code>).</p>\n\n<p>Same way set multiple posts as sticky post and they should appear as featured posts for your theme.</p>\n"
},
{
"answer_id": 260968,
"author": "CalvT",
"author_id": 56659,
"author_profile": "https://wordpress.stackexchange.com/users/56659",
"pm_score": 1,
"selected": true,
"text": "<p>I note you are using the <strong>Minamaze</strong> theme, correct? The problem here is the featured area, is exactly that, an area to manually enter featured content. You cannot automatically add posts to these areas.</p>\n\n<p>To configure them, you need to go into the admin, choose appearance, then customize.</p>\n\n<p>In here, choose Theme Options, then Homepage (Featured) and this will open the section to edit the content of the three areas. </p>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/260998",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105914/"
]
| I have custom post type of `portfolio` and I would like to be able to re-use most of the templating, but change to `content-portfolio` when the page is a custom post type named `portfolio`.
At present this is not working, so I'm not sure if I need to add Custom Post Types in the Main Query or add it inside the while loop?
**index.php CODE:**
```
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php if ( have_posts() ) : ?>
<header>
<?php if( single_post_title( '', false ) ) : ?>
<h1 class="page-title"><?php single_post_title(); ?></h1>
<?php else : ?>
<h1 class="page-title">
<?php echo get_bloginfo( 'name' ); ?>
</h1>
<?php endif; ?>
</header>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php
if(get_post_type()) : {
get_template_part( 'template-parts/content', get_post_type() );
elseif :
get_template_part( 'template-parts/content', get_post_format() );
endif;
}
?>
<?php endwhile; ?>
<?php else : ?>
<?php get_template_part( 'template-parts/content', 'none' ); ?>
<?php endif; ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
``` | I note you are using the **Minamaze** theme, correct? The problem here is the featured area, is exactly that, an area to manually enter featured content. You cannot automatically add posts to these areas.
To configure them, you need to go into the admin, choose appearance, then customize.
In here, choose Theme Options, then Homepage (Featured) and this will open the section to edit the content of the three areas. |
261,038 | <p>I'd like to limit search to characters used on the English language + numbers.
The reason is that looking at the slowest queries on mysql log i found most come from searches in Arab, Russian and Chinese characters, so i'd like to skip them and display an error message instead.</p>
| [
{
"answer_id": 261303,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 2,
"selected": false,
"text": "<p>You would do this by putting in a validation function in PHP to test the input against a regular expression like <code>^[a-zA-Z0-9,.!?' ]*</code></p>\n\n<p>So it would look like this:</p>\n\n<pre><code>if ( preg_match( \"^[a-zA-Z0-9,.!?'\" ]*\", {search variable} ) ) {\n // Success\n} else {\n // Fail\n}\n</code></pre>\n\n<p>The RexEx I used for all characters <code>A-Z</code>, <code>a-z</code>, <code>0-9</code>, as well as <code>,</code>, <code>.</code>, <code>!</code>, <code>?</code>, <code>'</code>, <code>\"</code>, and <code></code> (space).</p>\n"
},
{
"answer_id": 261324,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 2,
"selected": false,
"text": "<h2>EDIT: This solution is not recommended</h2>\n<blockquote>\n<p>My solution below is a hack which abuses PHP's <em>mbstring</em> functions in an attempt to magically divine alphabets by looking at the arrangement of bytes which compose the string. <em>This is a really bad idea and is <strong>highly prone to error</strong></em>.</p>\n<p><strong>Please see my <a href=\"https://wordpress.stackexchange.com/a/261335/25324\">other answer</a> for a far simpler and much more reliable solution.</strong></p>\n</blockquote>\n<hr />\n<p>One means to prevent searches using non-Latin alphabets is to use <a href=\"http://php.net/manual/en/function.mb-detect-encoding.php\" rel=\"nofollow noreferrer\">PHP's <code>mb_detect_encoding()</code> function</a> to see if the search string conforms to one of a custom selection of character encodings. A good place to do this is <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">the <code>pre_get_posts</code> action</a>, as it fires right before the query is executed.</p>\n<p>What you actually do after you've determined a search is using an invalid encoding is really application specific. Here I've set the search query to a single space to ensure that WordPress still interprets the query as a search, and thus still loads the <code>search.php</code> template (and does not direct the user to the front-page, as happens when the search string is an empty string). I also take an added precaution of <a href=\"https://wordpress.stackexchange.com/questions/140692/can-i-force-wp-query-to-return-no-results\">setting <code>'post__in'</code> to an array with an impossible post ID in order to make sure that absolutely nothing is returned</a>.</p>\n<p>Alternately, you might consider setting the search string to <code>null</code> and setting <code>page_id</code> in order to direct the user to a page with your custom error message.</p>\n<pre><code>function wpse261038_validate_search_query_encoding( $query ) {\n $valid_encodings = array( 'Windows-1252' );\n\n // Ignore admin, non-main query, and non-search queries\n if( is_admin() || !$query->is_main_query() || !$query->is_seach() )\n return;\n\n // Retrieve the encoding of the search string (if it's one listed in $valid_encodings)\n $search_encoding = mb_detect_encoding( $query->get( 's' ), $valid_encodings, true );\n\n // If the search encoding is one in $valid_encodings, leave the query as-is\n if( in_array( $search_encoding, $valid_encodings ) )\n return;\n\n // If it wasn't, sabotage the search query\n $query->set( 's', ' ' );\n $query->set( 'post__in', array(0) );\n\n // Set up your error message logic here somehow, perhaps one of the following:\n // - Add a template_include filter to load a custom error template\n // - Add a wp_enqueue_scripts hook with a greater priority than your theme/plugin's, and\n // use wp_localize_script() in the hook to pass an error message for your JavaScript\n // to display\n // - Perform a wp_redirect() to send the user to the URL of your choice\n // - Set a variable with an error message which your theme or plugin can display\n}\n\nadd_action( 'pre_get_posts', 'wpse261038_validate_search_query_encoding' );\n</code></pre>\n<hr />\n<h2>Choosing Encodings</h2>\n<p>I wrote a coverage test comparing some dummy strings in different alphabets against all of the <a href=\"http://php.net/manual/en/mbstring.supported-encodings.php\" rel=\"nofollow noreferrer\">default encodings supported by PHP</a>. It's not perfect by any stretch (I have no idea how realistic my dummy strings are, and it seems to choke on Japanese detection), but it's somewhat useful for determining candidates. You can see it in action <a href=\"https://www.tehplayground.com/OcqOULdSvu0ncPex\" rel=\"nofollow noreferrer\">here</a>.</p>\n<p>After researching potential character encodings flagged by that test, it seems like <a href=\"https://en.wikipedia.org/wiki/Windows-1252\" rel=\"nofollow noreferrer\"><code>Windows-1252</code></a> is the perfect choice for your needs, covering the Latin alphabet as well as the accents for common Latin languages.</p>\n<p>A selection of the <code>ISO-8859</code> character sets <em>should</em> be another viable choice, however for reasons I can't wrap my head around, the <code>mb_</code> functions don't seem to differentiate between <code>ISO-8859</code>'s different character sets, despite listing them as separate encodings.</p>\n<p>To allow some other common characters, you might also consider adding <code>HTML-ENTITIES</code>.</p>\n"
},
{
"answer_id": 261335,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 4,
"selected": true,
"text": "<p>This solution filters search strings by applying a regular expression which only matches characters from the Common and Latin Unicode scripts.</p>\n<hr />\n<h2>Matching Latin Characters with Regular Expressions</h2>\n<p>I just <a href=\"https://stackoverflow.com/questions/43015495\">had my mind blown over at Stack Overflow</a>. As it turns out, regular expressions have <a href=\"http://www.regular-expressions.info/unicode.html#script\" rel=\"nofollow noreferrer\">a mechanism</a> to match entire Unicode categories, including values to specify entire <a href=\"https://wikipedia.org/wiki/Script_(Unicode)\" rel=\"nofollow noreferrer\">Unicode "scripts"</a>, each corresponding to groups of characters used in different writing systems.</p>\n<p>This is done by using the <code>\\p</code> meta-character followed by a Unicode category identifier in curly braces - so <code>[\\p{Common}\\p{Latin}]</code> matches a single character in either the <a href=\"https://wikipedia.org/wiki/List_of_Unicode_characters#Latin_script\" rel=\"nofollow noreferrer\">Latin or Common scripts</a> - this includes punctuation, numerals, and miscellaneous symbols.</p>\n<p>As <a href=\"https://wordpress.stackexchange.com/a/261430/25324\">@Paul 'Sparrow Hawk' Biron points out</a>, the <code>u</code> <a href=\"http://php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">pattern modifier flag</a> should be set at the end of the regular expression in order for PHP's PCRE functions to treat the subject string as <code>UTF-8</code> Unicode encoded.</p>\n<p>All together then, the pattern</p>\n<pre><code>/^[\\p{Latin}\\p{Common}]+$/u\n</code></pre>\n<p>will match an entire string composed of one or more characters in the Latin and Common Unicode scripts.</p>\n<hr />\n<h2>Filtering the Search String</h2>\n<p>A good place to intercept a search string is <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts\" rel=\"nofollow noreferrer\">the <code>pre_get_posts</code> action</a> as it fires immediately before WordPress executes the query. With <strong>more care</strong>, this could also be accomplished using <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/request\" rel=\"nofollow noreferrer\">a <code>request</code> filter</a>.</p>\n<pre><code>function wpse261038_validate_search_characters( $query ) {\n // Leave admin, non-main query, and non-search queries alone\n if( is_admin() || !$query->is_main_query() || !$query->is_seach() )\n return;\n\n // Check if the search string contains only Latin/Common Unicode characters\n $match_result = preg_match( '/^[\\p{Latin}\\p{Common}]+$/u', $query->get( 's' ) );\n\n // If the search string only contains Latin/Common characters, let it continue\n if( 1 === $match_result )\n return;\n\n // If execution reaches this point, the search string contains non-Latin characters\n //TODO: Handle non-Latin search strings\n //TODO: Set up logic to display error message\n}\n\nadd_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );\n</code></pre>\n<hr />\n<h2>Responding to Disallowed Searches</h2>\n<p>Once it's been determined that a search string contains non-Latin characters, you can use <code>WP_Query::set()</code> in order to modify the query by changing it's named <a href=\"https://codex.wordpress.org/WordPress_Query_Vars\" rel=\"nofollow noreferrer\">query vars</a> - thus affecting the SQL query WordPress subsequently composes and executes.</p>\n<p>The most relevant query variables are probably the following:</p>\n<ul>\n<li><code>s</code> is the query variable corresponding to a search string. Setting it to <code>null</code> or an empty string (<code>''</code>) will result in the WordPress no longer treating the query as a search - often times this results in an archive template displaying all posts or the front-page of the site, depending on the values of the other query vars. Setting it to a single space (<code>' '</code>), however, will result in WordPress recognizing it as a search, and thus attempting to display the <code>search.php</code> template.</li>\n<li><code>page_id</code> could be used to direct the user to a specific page of your choice.</li>\n<li><code>post__in</code> can restrict the query to a specific selection of posts. By setting it to an array with an impossible post ID, <a href=\"https://wordpress.stackexchange.com/questions/140692/can-i-force-wp-query-to-return-no-results\">it can serve as a measure to ensure that the query returns absolutely nothing</a>.</li>\n</ul>\n<p>The above in mind, you might do the following in order to respond to a bad search by loading the <code>search.php</code> template with no results:</p>\n<pre><code>function wpse261038_validate_search_characters( $query ) {\n // Leave admin, non-main query, and non-search queries alone\n if( is_admin() || !$query->is_main_query() || !$query->is_seach() )\n return;\n\n // Check if the search string contains only Latin/Common Unicode characters\n $match_result = preg_match( '/^[\\p{Latin}\\p{Common}]+$/u', $query->get( 's' ) );\n\n // If the search string only contains Latin/Common characters, let it continue\n if( 1 === $match_result )\n return;\n\n $query->set( 's', ' ' ); // Replace the non-latin search with an empty one\n $query->set( 'post__in', array(0) ); // Make sure no post is ever returned\n\n //TODO: Set up logic to display error message\n}\n\nadd_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );\n</code></pre>\n<hr />\n<h2>Displaying an Error</h2>\n<p>The way in which you actually display the error message is highly dependent on your application and the abilities of your theme - there are many ways which this can be done. If your theme calls <code>get_search_form()</code> in it's search template, the easiest solution is probably to use a <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_search_form/\" rel=\"nofollow noreferrer\"><code>pre_get_search_form</code> action</a> hook to output your error immediately above the search form:</p>\n<pre><code>function wpse261038_validate_search_characters( $query ) {\n // Leave admin, non-main query, and non-search queries alone\n if( is_admin() || !$query->is_main_query() || !$query->is_seach() )\n return;\n\n // Check if the search string contains only Latin/Common Unicode characters\n $match_result = preg_match( '/^[\\p{Latin}\\p{Common}]+$/u', $query->get( 's' ) );\n\n // If the search string only contains Latin/Common characters, let it continue\n if( 1 === $match_result )\n return;\n\n $query->set( 's', ' ' ); // Replace the non-latin search with an empty one\n $query->set( 'post__in', array(0) ); // Make sure no post is ever returned\n\n add_action( 'pre_get_search_form', 'wpse261038_display_search_error' );\n}\n\nadd_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );\n\nfunction wpse261038_display_search_error() {\n echo '<div class="notice notice-error"><p>Your search could not be completed as it contains characters from non-Latin alphabets.<p></div>';\n}\n</code></pre>\n<p>Some other possibilities for displaying an error message include:</p>\n<ul>\n<li>If your site uses JavaScript which can display "flash" or "modal" messages (or you add such abilities on your own), add to it the logic to display messages on page-load when a specific variable is set, then add a <code>wp_enqueue_script</code> hook with a <code>$priority</code> larger than that which enqueues that JavaScript, and use <code>wp_localize_script()</code> to set that variable to include your error message.</li>\n<li>Use <code>wp_redirect()</code> to send the user to the URL of your choice (this method requires an additional page load).</li>\n<li>Set a PHP variable or invoke a method which will inform your theme/plugin about the error such that it may display it where appropriate.</li>\n<li>Set the <code>s</code> query variable to <code>''</code> instead of <code>' '</code> and use <code>page_id</code> in place of <code>post__in</code> in order to return a page of your choosing.</li>\n<li>Use a <a href=\"https://developer.wordpress.org/reference/hooks/loop_start/\" rel=\"nofollow noreferrer\"><code>loop_start</code> hook</a> to inject a fake <code>WP_Post</code> object containing your error into the query results - this is most definitely an ugly hack and may not look right with your particular theme, but it has the potentially desirable side effect of suppressing the "No Results" message.</li>\n<li>Use a <code>template_include</code> filter hook to swap out the search template with a custom one in your theme or plugin which displays your error.</li>\n</ul>\n<p>Without examining the theme in question, it's difficult to determine which route you should take.</p>\n"
},
{
"answer_id": 261430,
"author": "Paul 'Sparrow Hawk' Biron",
"author_id": 113496,
"author_profile": "https://wordpress.stackexchange.com/users/113496",
"pm_score": 1,
"selected": false,
"text": "<p>As I tried to explain to @MichaelRogers when he posted a similar question several days ago, knowing the character set (or script) used in a string is <strong>NOT</strong> sufficient to detect the <em>language</em> of that string.</p>\n\n<p>Thus, while the method detailed by @bosco <em>will</em> remove Russian, etc strings (with the 2 corrections below), it will <strong>NOT</strong> limit your searches to English. </p>\n\n<p>To see this, try:</p>\n\n<pre><code>$strings = array (\n 'I\\'m sorry', // English\n 'Je suis désolé', // French\n 'Es tut mir Leid', // German\n 'Lorem ipsum dolor sit amet', // Lorem ipsum\n 'أنا سعيد', // Arabic\n 'я счастлив', // Russian\n '我很高兴', // Chinese (Simplified)\n '我很高興', // Chinese (Traditional)\n ) ;\nforeach ($strings as $s) {\n if (preg_match ('/^[\\p{Latin}\\p{Common}]+$/u', $s) === 1) {\n echo \"$s: matches latin+common\\n\" ;\n }\n else {\n echo \"$s: does not match latin+common\\n\" ;\n }\n }\n</code></pre>\n\n<p>[<strong>note:</strong> the 2 corrections mentioned above to what @bosco provided are:</p>\n\n<ol>\n<li>the pattern is enclosed a string (required to be syntactically correct PHP)</li>\n<li>added the <code>/u</code> modifier (required to treat pattern and subject as UTF-8 encoded, see <a href=\"http://php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">PHP: Regex Pattern Modifiers</a>]</li>\n</ol>\n\n<p>which will produce:</p>\n\n<pre><code>I'm sorry: matches latin+common\nJe suis désolé: matches latin+common\nEs tut mir Leid: matches latin+common\nLorem ipsum dolor sit amet: matches latin+common\nأنا سعيد: does not match latin+common\nя счастлив: does not match latin+common\n我很高兴: does not match latin+common\n我很高興: does not match latin+common\n</code></pre>\n\n<p>[<strong>note:</strong> I speak English, French & some German (and a bit of <a href=\"http://lipsum.com/\" rel=\"nofollow noreferrer\">Lorem ipsum</a> :-), but relied on Google Translate for the Arabic, Russian and Chinese]</p>\n\n<p>As you can see, relying on checking for the latin script will <strong>NOT</strong> ensure you have English.</p>\n\n<p>There are a number of threads on StackOverflow (e.g., <a href=\"https://stackoverflow.com/questions/1441562/detect-language-from-string-in-php\">Detect language from string in PHP</a>) that provide more info on the subject.</p>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/261038",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77283/"
]
| I'd like to limit search to characters used on the English language + numbers.
The reason is that looking at the slowest queries on mysql log i found most come from searches in Arab, Russian and Chinese characters, so i'd like to skip them and display an error message instead. | This solution filters search strings by applying a regular expression which only matches characters from the Common and Latin Unicode scripts.
---
Matching Latin Characters with Regular Expressions
--------------------------------------------------
I just [had my mind blown over at Stack Overflow](https://stackoverflow.com/questions/43015495). As it turns out, regular expressions have [a mechanism](http://www.regular-expressions.info/unicode.html#script) to match entire Unicode categories, including values to specify entire [Unicode "scripts"](https://wikipedia.org/wiki/Script_(Unicode)), each corresponding to groups of characters used in different writing systems.
This is done by using the `\p` meta-character followed by a Unicode category identifier in curly braces - so `[\p{Common}\p{Latin}]` matches a single character in either the [Latin or Common scripts](https://wikipedia.org/wiki/List_of_Unicode_characters#Latin_script) - this includes punctuation, numerals, and miscellaneous symbols.
As [@Paul 'Sparrow Hawk' Biron points out](https://wordpress.stackexchange.com/a/261430/25324), the `u` [pattern modifier flag](http://php.net/manual/en/reference.pcre.pattern.modifiers.php) should be set at the end of the regular expression in order for PHP's PCRE functions to treat the subject string as `UTF-8` Unicode encoded.
All together then, the pattern
```
/^[\p{Latin}\p{Common}]+$/u
```
will match an entire string composed of one or more characters in the Latin and Common Unicode scripts.
---
Filtering the Search String
---------------------------
A good place to intercept a search string is [the `pre_get_posts` action](https://codex.wordpress.org/Plugin_API/Action_Reference/pre_get_posts) as it fires immediately before WordPress executes the query. With **more care**, this could also be accomplished using [a `request` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/request).
```
function wpse261038_validate_search_characters( $query ) {
// Leave admin, non-main query, and non-search queries alone
if( is_admin() || !$query->is_main_query() || !$query->is_seach() )
return;
// Check if the search string contains only Latin/Common Unicode characters
$match_result = preg_match( '/^[\p{Latin}\p{Common}]+$/u', $query->get( 's' ) );
// If the search string only contains Latin/Common characters, let it continue
if( 1 === $match_result )
return;
// If execution reaches this point, the search string contains non-Latin characters
//TODO: Handle non-Latin search strings
//TODO: Set up logic to display error message
}
add_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );
```
---
Responding to Disallowed Searches
---------------------------------
Once it's been determined that a search string contains non-Latin characters, you can use `WP_Query::set()` in order to modify the query by changing it's named [query vars](https://codex.wordpress.org/WordPress_Query_Vars) - thus affecting the SQL query WordPress subsequently composes and executes.
The most relevant query variables are probably the following:
* `s` is the query variable corresponding to a search string. Setting it to `null` or an empty string (`''`) will result in the WordPress no longer treating the query as a search - often times this results in an archive template displaying all posts or the front-page of the site, depending on the values of the other query vars. Setting it to a single space (`' '`), however, will result in WordPress recognizing it as a search, and thus attempting to display the `search.php` template.
* `page_id` could be used to direct the user to a specific page of your choice.
* `post__in` can restrict the query to a specific selection of posts. By setting it to an array with an impossible post ID, [it can serve as a measure to ensure that the query returns absolutely nothing](https://wordpress.stackexchange.com/questions/140692/can-i-force-wp-query-to-return-no-results).
The above in mind, you might do the following in order to respond to a bad search by loading the `search.php` template with no results:
```
function wpse261038_validate_search_characters( $query ) {
// Leave admin, non-main query, and non-search queries alone
if( is_admin() || !$query->is_main_query() || !$query->is_seach() )
return;
// Check if the search string contains only Latin/Common Unicode characters
$match_result = preg_match( '/^[\p{Latin}\p{Common}]+$/u', $query->get( 's' ) );
// If the search string only contains Latin/Common characters, let it continue
if( 1 === $match_result )
return;
$query->set( 's', ' ' ); // Replace the non-latin search with an empty one
$query->set( 'post__in', array(0) ); // Make sure no post is ever returned
//TODO: Set up logic to display error message
}
add_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );
```
---
Displaying an Error
-------------------
The way in which you actually display the error message is highly dependent on your application and the abilities of your theme - there are many ways which this can be done. If your theme calls `get_search_form()` in it's search template, the easiest solution is probably to use a [`pre_get_search_form` action](https://developer.wordpress.org/reference/hooks/pre_get_search_form/) hook to output your error immediately above the search form:
```
function wpse261038_validate_search_characters( $query ) {
// Leave admin, non-main query, and non-search queries alone
if( is_admin() || !$query->is_main_query() || !$query->is_seach() )
return;
// Check if the search string contains only Latin/Common Unicode characters
$match_result = preg_match( '/^[\p{Latin}\p{Common}]+$/u', $query->get( 's' ) );
// If the search string only contains Latin/Common characters, let it continue
if( 1 === $match_result )
return;
$query->set( 's', ' ' ); // Replace the non-latin search with an empty one
$query->set( 'post__in', array(0) ); // Make sure no post is ever returned
add_action( 'pre_get_search_form', 'wpse261038_display_search_error' );
}
add_action( 'pre_get_posts', 'wpse261038_validate_search_characters' );
function wpse261038_display_search_error() {
echo '<div class="notice notice-error"><p>Your search could not be completed as it contains characters from non-Latin alphabets.<p></div>';
}
```
Some other possibilities for displaying an error message include:
* If your site uses JavaScript which can display "flash" or "modal" messages (or you add such abilities on your own), add to it the logic to display messages on page-load when a specific variable is set, then add a `wp_enqueue_script` hook with a `$priority` larger than that which enqueues that JavaScript, and use `wp_localize_script()` to set that variable to include your error message.
* Use `wp_redirect()` to send the user to the URL of your choice (this method requires an additional page load).
* Set a PHP variable or invoke a method which will inform your theme/plugin about the error such that it may display it where appropriate.
* Set the `s` query variable to `''` instead of `' '` and use `page_id` in place of `post__in` in order to return a page of your choosing.
* Use a [`loop_start` hook](https://developer.wordpress.org/reference/hooks/loop_start/) to inject a fake `WP_Post` object containing your error into the query results - this is most definitely an ugly hack and may not look right with your particular theme, but it has the potentially desirable side effect of suppressing the "No Results" message.
* Use a `template_include` filter hook to swap out the search template with a custom one in your theme or plugin which displays your error.
Without examining the theme in question, it's difficult to determine which route you should take. |
261,042 | <p>First, I want to clarify - <strong>this is not a CSS question.</strong> </p>
<p>I want to change the data that is showing of the widget, when its in closed / open mode inside the wp-admin, in a sidebar or a page builder. Here is an image to better explain.</p>
<p><a href="https://i.stack.imgur.com/bBXNY.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bBXNY.jpg" alt="enter image description here"></a></p>
<p>I want to be able to add something / remove from the title of the widget dynamically and use widget $instance to do so</p>
<p><strong>The desired result:</strong><br>
Add a small info label stating mobile / desktop / both - which is an option picked inside that specific widget</p>
<p>Ideas anyone?</p>
<p><em>UPDATE</em><br>
<strong>Since i see some intrest in a solution to this question:</strong><br>
@cjbj solution works beautifully but only in the sidebar and only partially:</p>
<pre><code>add_filter ('dynamic_sidebar_params','wpse261042_change_widget_title');
function wpse261042_change_widget_title ($params) {
$widget_id = $params[0]['widget_id'];
$widget_instance = strrchr ($widget_id, '-');
$wlen = strlen ($widget_id);
$ilen = strlen ($widget_instance);
$widget_name = substr ($widget_id,0,$wlen-$ilen);
$widget_instance = substr ($widget_instance,1);
// get the data
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
$use_mobile = $data['use_mobile']; // option inside my widget
if($use_mobile == 'yes') {$string = 'desktop / mobile';} else {$string = 'desktop only';}
$params[0]['widget_name'] .= $string;
return $params;
}
</code></pre>
<p>However.. you cannot insert any html in that string (or at least i couldnt)</p>
<p>Would update if i find a working solution.</p>
| [
{
"answer_id": 261346,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>Let's first see whether it is possible to change the information that is displayed in the widget titles in admin. This list is generated by <a href=\"https://developer.wordpress.org/reference/functions/wp_list_widget_controls/\" rel=\"nofollow noreferrer\"><code>wp_list_widget_controls</code></a>, which calls on <a href=\"https://developer.wordpress.org/reference/functions/dynamic_sidebar/\" rel=\"nofollow noreferrer\"><code>dynamic_sidebar</code></a>, which contains a filter <a href=\"https://developer.wordpress.org/reference/hooks/dynamic_sidebar_params/\" rel=\"nofollow noreferrer\"><code>dynamic_sidebar_params</code></a> to change the parameters in the controls, including the title. Let's try that:</p>\n\n<pre><code>add_filter ('dynamic_sidebar_params','wpse261042_change_widget_title');\nfunction wpse261042_change_widget_title ($params) {\n $string = ' Added info';\n $params[0]['widget_name'] .= $string;\n return $params;\n }\n</code></pre>\n\n<p>The <code>$string</code> is not exactly in the place where you point at, but I'd say it's good enough.</p>\n\n<p>Now, we need to replace <code>$string</code> with some information from inside the current widget. Luckily, we know which widget we are in, because <code>$params</code> also contains the <code>widget_id</code>. I'll <a href=\"https://wordpress.stackexchange.com/questions/240327/how-to-access-widget-data-from-outside-widget/240344#240344\">refer to this answer</a> for an explanation how you use the <code>widget_id</code> to retrieve widget data. Here we go:</p>\n\n<pre><code> // we need to separate the widget name and instance from the id\n $widget_id = $params[0]['widget_id'];\n $widget_instance = strrchr ($widget_id, '-');\n $wlen = strlen ($widget_id);\n $ilen = strlen ($widget_instance);\n $widget_name = substr ($widget_id,0,$wlen-$ilen);\n $widget_instance = substr ($widget_instance,1);\n // get the data\n $widget_instances = get_option('widget_' . $widget_name);\n $data = $widget_instances[$widget_instance];\n</code></pre>\n\n<p>Now the array <code>$data</code> contains the instances of the widget and you can choose which one you want to pass to <code>$string</code> in the function.</p>\n"
},
{
"answer_id": 261629,
"author": "J.D.",
"author_id": 27757,
"author_profile": "https://wordpress.stackexchange.com/users/27757",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress already has a similar feature built into the widgets UI. See for example how the \"Title\" value input by the user is appended to the title of this search widget:</p>\n\n<p><a href=\"https://i.stack.imgur.com/HDUgJ.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/HDUgJ.png\" alt=\"Search widget with title appended\"></a></p>\n\n<p>The code that does this is found in <a href=\"https://core.trac.wordpress.org/browser/trunk/src/wp-admin/js/widgets.js?rev=38672#L481\" rel=\"nofollow noreferrer\"><code>wp-admin/js/widgets.js</code></a>:</p>\n\n<pre><code>appendTitle : function(widget) {\n var title = $('input[id*=\"-title\"]', widget).val() || '';\n\n if ( title ) {\n title = ': ' + title.replace(/<[^<>]+>/g, '').replace(/</g, '&lt;').replace(/>/g, '&gt;');\n }\n\n $(widget).children('.widget-top').children('.widget-title').children()\n .children('.in-widget-title').html(title);\n\n},\n</code></pre>\n\n<p>It finds the <code>input</code> element within a widget that has an <code>id</code> attribute ending in <code>-title</code>, and appends the value entered in that input to the text in the widget title bar.</p>\n\n<p>So, if the setting that you have in mind is based on an <code>input</code> field (no matter whether the <code>type</code> is <code>text</code> or <code>radio</code>, etc.), you just need to give it an <code>id</code> ending in <code>-title</code>, and WordPress will take care of the rest.</p>\n\n<p>And this way, the string in the title bar will automatically be updated when the user modifies the setting.</p>\n"
},
{
"answer_id": 262057,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 3,
"selected": true,
"text": "<h2>Background:</h2>\n\n<p>The reason why filtering with <code>dynamic_sidebar_params</code> doesn't work with <code>HTML</code> is because WordPress strips <code>HTML</code> from Widget Heading in <a href=\"https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L216\" rel=\"nofollow noreferrer\"><code>wp_widget_control()</code></a> function like this:</p>\n\n<pre><code>$widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) );\n</code></pre>\n\n<p>WordPress also strips <code>HTML</code> in default JavaScript in <a href=\"https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/widgets.js#L485\" rel=\"nofollow noreferrer\"><code>wp-admin/js/widgets.js</code></a></p>\n\n<p>So without a customised solution, there is no default filter or option either with PHP or with JavaScript to achieve what you want.</p>\n\n<h2>Custom PHP Solution:</h2>\n\n<p>A custom PHP solution is possible that'll only work in <code>wp-admin -> Appearance -> Widgets</code>, but not in <code>Customizer -> Widgets</code>.</p>\n\n<p>WordPress adds <a href=\"https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L169-L272\" rel=\"nofollow noreferrer\"><code>wp_widget_control()</code> function</a> (that generates Widget Control UI) with <code>dynamic_sidebar_params</code> hook, so it's possible to override it using this filter hook. However, in customizer, WordPress calls <a href=\"https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L169-L272\" rel=\"nofollow noreferrer\"><code>wp_widget_control()</code> function</a> directly, so this solution will not work for the customizer.</p>\n\n<p>The solution works like the following (add this code in a custom plugin):</p>\n\n<pre><code>add_filter( 'dynamic_sidebar_params', 'wpse261042_list_widget_controls_dynamic_sidebar', 20 );\nfunction wpse261042_list_widget_controls_dynamic_sidebar( $params ) {\n global $wp_registered_widgets;\n // we only want this in wp-admin (may need different check to enable page builder)\n if( is_admin() ) {\n if ( is_array( $params ) && is_array( $params[0] ) && $params[0]['id'] !== 'wp_inactive_widgets' ) {\n $widget_id = $params[0]['widget_id'];\n if ( $wp_registered_widgets[$widget_id]['callback'] === 'wp_widget_control' ) {\n // here we are replacing wp_widget_control() function \n // with our custom wpse261042_widget_control() function\n $wp_registered_widgets[$widget_id]['callback'] = 'wpse261042_widget_control';\n }\n }\n }\n return $params;\n}\n\nfunction wpse261042_widget_control( $sidebar_args ) {\n // here copy everything from the core wp_widget_control() function\n // and change only the part related to heading as you need \n} \n</code></pre>\n\n<p>As I said before, this solution doesn't work for the customizer and more likely to require future updates as we are overriding a core function.</p>\n\n<h1>Custom JavaScript Solution (Recommended):</h1>\n\n<p>Fortunately, it's possible to customize this behaviour with JavaScript. WordPress updates Widget Control Heading with JavaScript anyway. To do that WordPress keeps a placeholder <code>in-widget-title</code> CSS class and updates it with the widget <code>title</code> field value from JavaScript CODE. We can manipulate this to achieve our goal.</p>\n\n<h3>Related Core JS files:</h3>\n\n<p>First you need to know that WordPress loads <a href=\"https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/customize-widgets.js\" rel=\"nofollow noreferrer\"><code>wp-admin/js/customize-widgets.js</code></a> file (with <code>customize-widgets</code> handle) in <code>wp-admin -> Customize -> Widgets</code> (customizer) and <a href=\"https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/widgets.js\" rel=\"nofollow noreferrer\"><code>wp-admin/js/widgets.js</code></a> file (with <code>admin-widgets</code> handle) in <code>wp-admin -> Appearance -> Widgets</code> to manipulate Widget Control UI. These two files do similar operations for Widget UI markups and Widget Heading UI manipulation, but a lot of different things as well. So we need to consider that for our JavaScript based solution.</p>\n\n<h3>Considerations for Customizer:</h3>\n\n<p>Customizer doesn't load Widget UI markup immediately after page load, instead, it loads with JavaScript when the corresponding <code>Widgets -> Sidebar</code> panel is open. So we need to manipulate the Widget UI after WordPress loads it. For example, since customizer CODE is event based, I've used the following line of CODE to set the event handler at the correct moment:</p>\n\n<pre><code>section.expanded.bind( onExpanded );\n</code></pre>\n\n<p>Also, customizer used AJAX to load changes immediately, that's why I've used the following line to tap into the data change:</p>\n\n<pre><code>control.setting.bind( updateTitle );\n</code></pre>\n\n<p>Also, I needed to tap into <code>widget-added</code> event with the following line of CODE:</p>\n\n<pre><code>$( document ).on( 'widget-added', add_widget );\n</code></pre>\n\n<h3>Common for Customizer & <code>wp-admin -> Appearance -> Widgets</code>:</h3>\n\n<p>Both the above mentioned JavaScript files trigger <code>widget-updated</code> event when an widget is updated. Although customizer does it immediately with AJAX, while traditional <code>Widget</code> admin does it after you Click the <kbd>Save</kbd> button. I've used the following line of CODE for this: </p>\n\n<pre><code>$( document ).on( 'widget-updated', modify_widget );\n</code></pre>\n\n<h3>Considerations for <code>wp-admin -> Appearance -> Widgets</code>:</h3>\n\n<p>Contrary to the customizer, traditional <code>Widgets</code> admin loads the Widget Control UI with PHP, so I've traversed the UI HTML to make the initial changes like this:</p>\n\n<pre><code>$( '#widgets-right div.widgets-sortables div.widget' ).each( function() { // code } ); \n</code></pre>\n\n<h1>Custom Plugin CODE:</h1>\n\n<p>Following is a complete Plugin with JavaScript based solution that will work both in <code>wp-admin -> Appearance -> Widgets</code> and <code>Customizer -> Widgets</code>:</p>\n\n<p><code>wpse-widget-control.php</code> Plugin PHP file:</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Widget Control\n * Plugin URI: https://wordpress.stackexchange.com/questions/261042/how-to-influence-the-information-displayed-on-widget-inside-wp-admin\n * Description: Display additional info on Widget Heading in wp-admin & customizer using JS\n * Author: Fayaz\n * Version: 1.0\n * Author URI: http://fmy.me/\n */\n\n if( is_admin() ) {\n add_action( 'current_screen', 'wpse261042_widget_screen' );\n }\n\n function wpse261042_widget_screen() {\n $currentScreen = get_current_screen();\n if( $currentScreen->id === 'customize' ) {\n add_action( 'customize_controls_enqueue_scripts', 'wpse261042_customizer_widgets', 99 );\n }\n else if( $currentScreen->id === 'widgets' ) {\n add_action( 'admin_enqueue_scripts', 'wpse261042_admin_widgets', 99 );\n }\n }\n\n function wpse261042_customizer_widgets() {\n wp_enqueue_script( 'custom-widget-heading', plugin_dir_url( __FILE__ ) . 'custom-widget-heading.js', array( 'jquery', 'customize-widgets' ) );\n }\n\n function wpse261042_admin_widgets() {\n wp_enqueue_script( 'custom-widget-heading', plugin_dir_url( __FILE__ ) . 'custom-widget-heading.js', array( 'jquery', 'admin-widgets' ) );\n }\n</code></pre>\n\n<p><code>custom-widget-heading.js</code> JavaScript file:</p>\n\n<pre><code>(function( wp, $ ) {\n var compare = {\n // field to compare\n field: 'title',\n // value to be compared with\n value: 'yes',\n // heading if compare.value matches with compare.field value\n heading: ' <i>(mobile/desktop)</i> ',\n // alternate heading\n alt_heading: ' <i>(desktop only)</i> ',\n // WP adds <span class=\"in-widget-title\"></span> in each widget heading by default\n heading_selector: '.in-widget-title'\n };\n\n var widgetIdSelector = '> .widget-inside > form > .widget-id';\n // heading is added as prefix of already existing heading, modify this as needed\n function modify_heading( $elm, isMain ) {\n var html = $elm.html();\n if ( html.indexOf( compare.heading ) == -1 && html.indexOf( compare.alt_heading ) == -1 ) {\n if( isMain ) {\n $elm.html( compare.heading + html );\n }\n else {\n $elm.html( compare.alt_heading + html );\n }\n }\n };\n function parseFieldSelector( widgetId ) {\n return 'input[name=\"' + widgetIdToFieldPrefix( widgetId ) + '[' + compare.field + ']\"]';\n };\n\n // @note: change this function if you don't want custom Heading change to appear for all the widgets.\n // If field variable is empty, then that means that field doesn't exist for that widget.\n // So use this logic if you don't want the custom heading manipulation if the field doesn't exist for a widget\n function modify_widget( evt, $widget, content ) {\n var field = null;\n var field_value = '';\n if( content ) {\n field = $( content ).find( parseFieldSelector( $widget.find( widgetIdSelector ).val() ) );\n }\n else {\n field = $widget.find( parseFieldSelector( $widget.find( widgetIdSelector ).val() ) );\n }\n if( field ) {\n field_value = ( ( field.attr( 'type' ) != 'radio' && field.attr( 'type' ) != 'checkbox' )\n || field.is( ':checked' ) ) ? field.val() : '';\n }\n modify_heading( $widget.find( compare.heading_selector ), field_value == compare.value );\n }\n\n function parseWidgetId( widgetId ) {\n var matches, parsed = {\n number: null,\n id_base: null\n };\n matches = widgetId.match( /^(.+)-(\\d+)$/ );\n if ( matches ) {\n parsed.id_base = matches[1];\n parsed.number = parseInt( matches[2], 10 );\n } else {\n parsed.id_base = widgetId;\n }\n return parsed;\n }\n function widgetIdToSettingId( widgetId ) {\n var parsed = parseWidgetId( widgetId ), settingId;\n settingId = 'widget_' + parsed.id_base;\n if ( parsed.number ) {\n settingId += '[' + parsed.number + ']';\n }\n return settingId;\n }\n function widgetIdToFieldPrefix( widgetId ) {\n var parsed = parseWidgetId( widgetId ), settingId;\n settingId = 'widget-' + parsed.id_base;\n if ( parsed.number ) {\n settingId += '[' + parsed.number + ']';\n }\n return settingId;\n }\n var api = wp.customize;\n if( api ) {\n // We ate in the customizer\n widgetIdSelector = '> .widget-inside > .form > .widget-id';\n api.bind( 'ready', function() {\n function add_widget( evt, $widget ) {\n var control;\n control = api.control( widgetIdToSettingId( $widget.find( widgetIdSelector ).val() ) );\n\n function updateTitle( evt ) {\n modify_widget( null, $widget );\n };\n if ( control ) {\n control.setting.bind( updateTitle );\n }\n updateTitle();\n };\n api.control.each( function ( control ) {\n if( control.id && 0 === control.id.indexOf( 'widget_' ) ) {\n api.section( control.section.get(), function( section ) {\n function onExpanded( isExpanded ) {\n if ( isExpanded ) {\n section.expanded.unbind( onExpanded );\n modify_widget( null, control.container.find( '.widget' ), control.params.widget_content );\n }\n };\n if ( section.expanded() ) {\n onExpanded( true );\n } else {\n section.expanded.bind( onExpanded );\n }\n } );\n }\n } );\n $( document ).on( 'widget-added', add_widget );\n } );\n }\n else {\n // We are in wp-admin -> Appearance -> Widgets\n // Use proper condition and CODE if you want to target any page builder\n // that doesn't use WP Core Widget Markup or Core JavaScript\n $( window ).on( 'load', function() {\n $( '#widgets-right div.widgets-sortables div.widget' ).each( function() {\n modify_widget( 'non-customizer', $( this ) );\n } );\n $( document ).on( 'widget-added', modify_widget );\n } );\n }\n $( document ).on( 'widget-updated', modify_widget );\n})( window.wp, jQuery );\n</code></pre>\n\n<h3>Plugin Usage:</h3>\n\n<blockquote>\n <p><strong><em>Note:</em></strong> With the above sample Plugin CODE as it is, if you set the <code>title</code> of a Widget to <code>yes</code>, then it'll show <em>(mobile/desktop)</em> within the Widget Control UI heading, all the other Widget's will have <em>(desktop only)</em> in the Heading. In the customizer the change will be immediate, in <code>wp-admin -> widgets</code> the change will show after you <code>save</code> the changes. Of course you can change this behaviour by modifying the CODE (in JavaScript) to do the heading change for a different <code>field_name</code> or to only show that specific heading to some widgets and not to all of them.</p>\n</blockquote>\n\n<p>For example, say you have a field named <code>use_mobile</code>, and you want to set the heading to <em>(mobile/desktop)</em> when it's set to <code>yes</code>. Then set the <code>compare</code> variable to something like:</p>\n\n<pre><code>var compare = {\n field: 'use_mobile',\n value: 'yes',\n heading: ' <i>(mobile/desktop)</i> ',\n alt_heading: ' <i>(desktop only)</i> ',\n heading_selector: '.in-widget-title'\n};\n</code></pre>\n\n<p>Also, if you want to change the entire heading (instead of just <code>.in-widget-title</code>), then you may change the <code>heading_selector</code> setting along with the correct markup for <code>heading</code> & <code>alt_heading</code> to do so. The possibilities are endless, but make sure WordPress core CODE doesn't produce any error if you want to be too much creative with the resulting markup.</p>\n\n<h2>Page builder integration:</h2>\n\n<p>Whether or not either of these solutions will work for a page builder will depend on that page builder implementation. If it uses WordPress supplied methods to load Widget Control UI then it should work without any modification, otherwise similar (but modified) implication may be possible for page builders as well. </p>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/261042",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/7990/"
]
| First, I want to clarify - **this is not a CSS question.**
I want to change the data that is showing of the widget, when its in closed / open mode inside the wp-admin, in a sidebar or a page builder. Here is an image to better explain.
[](https://i.stack.imgur.com/bBXNY.jpg)
I want to be able to add something / remove from the title of the widget dynamically and use widget $instance to do so
**The desired result:**
Add a small info label stating mobile / desktop / both - which is an option picked inside that specific widget
Ideas anyone?
*UPDATE*
**Since i see some intrest in a solution to this question:**
@cjbj solution works beautifully but only in the sidebar and only partially:
```
add_filter ('dynamic_sidebar_params','wpse261042_change_widget_title');
function wpse261042_change_widget_title ($params) {
$widget_id = $params[0]['widget_id'];
$widget_instance = strrchr ($widget_id, '-');
$wlen = strlen ($widget_id);
$ilen = strlen ($widget_instance);
$widget_name = substr ($widget_id,0,$wlen-$ilen);
$widget_instance = substr ($widget_instance,1);
// get the data
$widget_instances = get_option('widget_' . $widget_name);
$data = $widget_instances[$widget_instance];
$use_mobile = $data['use_mobile']; // option inside my widget
if($use_mobile == 'yes') {$string = 'desktop / mobile';} else {$string = 'desktop only';}
$params[0]['widget_name'] .= $string;
return $params;
}
```
However.. you cannot insert any html in that string (or at least i couldnt)
Would update if i find a working solution. | Background:
-----------
The reason why filtering with `dynamic_sidebar_params` doesn't work with `HTML` is because WordPress strips `HTML` from Widget Heading in [`wp_widget_control()`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L216) function like this:
```
$widget_title = esc_html( strip_tags( $sidebar_args['widget_name'] ) );
```
WordPress also strips `HTML` in default JavaScript in [`wp-admin/js/widgets.js`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/widgets.js#L485)
So without a customised solution, there is no default filter or option either with PHP or with JavaScript to achieve what you want.
Custom PHP Solution:
--------------------
A custom PHP solution is possible that'll only work in `wp-admin -> Appearance -> Widgets`, but not in `Customizer -> Widgets`.
WordPress adds [`wp_widget_control()` function](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L169-L272) (that generates Widget Control UI) with `dynamic_sidebar_params` hook, so it's possible to override it using this filter hook. However, in customizer, WordPress calls [`wp_widget_control()` function](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/includes/widgets.php#L169-L272) directly, so this solution will not work for the customizer.
The solution works like the following (add this code in a custom plugin):
```
add_filter( 'dynamic_sidebar_params', 'wpse261042_list_widget_controls_dynamic_sidebar', 20 );
function wpse261042_list_widget_controls_dynamic_sidebar( $params ) {
global $wp_registered_widgets;
// we only want this in wp-admin (may need different check to enable page builder)
if( is_admin() ) {
if ( is_array( $params ) && is_array( $params[0] ) && $params[0]['id'] !== 'wp_inactive_widgets' ) {
$widget_id = $params[0]['widget_id'];
if ( $wp_registered_widgets[$widget_id]['callback'] === 'wp_widget_control' ) {
// here we are replacing wp_widget_control() function
// with our custom wpse261042_widget_control() function
$wp_registered_widgets[$widget_id]['callback'] = 'wpse261042_widget_control';
}
}
}
return $params;
}
function wpse261042_widget_control( $sidebar_args ) {
// here copy everything from the core wp_widget_control() function
// and change only the part related to heading as you need
}
```
As I said before, this solution doesn't work for the customizer and more likely to require future updates as we are overriding a core function.
Custom JavaScript Solution (Recommended):
=========================================
Fortunately, it's possible to customize this behaviour with JavaScript. WordPress updates Widget Control Heading with JavaScript anyway. To do that WordPress keeps a placeholder `in-widget-title` CSS class and updates it with the widget `title` field value from JavaScript CODE. We can manipulate this to achieve our goal.
### Related Core JS files:
First you need to know that WordPress loads [`wp-admin/js/customize-widgets.js`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/customize-widgets.js) file (with `customize-widgets` handle) in `wp-admin -> Customize -> Widgets` (customizer) and [`wp-admin/js/widgets.js`](https://github.com/WordPress/WordPress/blob/4.7/wp-admin/js/widgets.js) file (with `admin-widgets` handle) in `wp-admin -> Appearance -> Widgets` to manipulate Widget Control UI. These two files do similar operations for Widget UI markups and Widget Heading UI manipulation, but a lot of different things as well. So we need to consider that for our JavaScript based solution.
### Considerations for Customizer:
Customizer doesn't load Widget UI markup immediately after page load, instead, it loads with JavaScript when the corresponding `Widgets -> Sidebar` panel is open. So we need to manipulate the Widget UI after WordPress loads it. For example, since customizer CODE is event based, I've used the following line of CODE to set the event handler at the correct moment:
```
section.expanded.bind( onExpanded );
```
Also, customizer used AJAX to load changes immediately, that's why I've used the following line to tap into the data change:
```
control.setting.bind( updateTitle );
```
Also, I needed to tap into `widget-added` event with the following line of CODE:
```
$( document ).on( 'widget-added', add_widget );
```
### Common for Customizer & `wp-admin -> Appearance -> Widgets`:
Both the above mentioned JavaScript files trigger `widget-updated` event when an widget is updated. Although customizer does it immediately with AJAX, while traditional `Widget` admin does it after you Click the `Save` button. I've used the following line of CODE for this:
```
$( document ).on( 'widget-updated', modify_widget );
```
### Considerations for `wp-admin -> Appearance -> Widgets`:
Contrary to the customizer, traditional `Widgets` admin loads the Widget Control UI with PHP, so I've traversed the UI HTML to make the initial changes like this:
```
$( '#widgets-right div.widgets-sortables div.widget' ).each( function() { // code } );
```
Custom Plugin CODE:
===================
Following is a complete Plugin with JavaScript based solution that will work both in `wp-admin -> Appearance -> Widgets` and `Customizer -> Widgets`:
`wpse-widget-control.php` Plugin PHP file:
```
<?php
/**
* Plugin Name: Widget Control
* Plugin URI: https://wordpress.stackexchange.com/questions/261042/how-to-influence-the-information-displayed-on-widget-inside-wp-admin
* Description: Display additional info on Widget Heading in wp-admin & customizer using JS
* Author: Fayaz
* Version: 1.0
* Author URI: http://fmy.me/
*/
if( is_admin() ) {
add_action( 'current_screen', 'wpse261042_widget_screen' );
}
function wpse261042_widget_screen() {
$currentScreen = get_current_screen();
if( $currentScreen->id === 'customize' ) {
add_action( 'customize_controls_enqueue_scripts', 'wpse261042_customizer_widgets', 99 );
}
else if( $currentScreen->id === 'widgets' ) {
add_action( 'admin_enqueue_scripts', 'wpse261042_admin_widgets', 99 );
}
}
function wpse261042_customizer_widgets() {
wp_enqueue_script( 'custom-widget-heading', plugin_dir_url( __FILE__ ) . 'custom-widget-heading.js', array( 'jquery', 'customize-widgets' ) );
}
function wpse261042_admin_widgets() {
wp_enqueue_script( 'custom-widget-heading', plugin_dir_url( __FILE__ ) . 'custom-widget-heading.js', array( 'jquery', 'admin-widgets' ) );
}
```
`custom-widget-heading.js` JavaScript file:
```
(function( wp, $ ) {
var compare = {
// field to compare
field: 'title',
// value to be compared with
value: 'yes',
// heading if compare.value matches with compare.field value
heading: ' <i>(mobile/desktop)</i> ',
// alternate heading
alt_heading: ' <i>(desktop only)</i> ',
// WP adds <span class="in-widget-title"></span> in each widget heading by default
heading_selector: '.in-widget-title'
};
var widgetIdSelector = '> .widget-inside > form > .widget-id';
// heading is added as prefix of already existing heading, modify this as needed
function modify_heading( $elm, isMain ) {
var html = $elm.html();
if ( html.indexOf( compare.heading ) == -1 && html.indexOf( compare.alt_heading ) == -1 ) {
if( isMain ) {
$elm.html( compare.heading + html );
}
else {
$elm.html( compare.alt_heading + html );
}
}
};
function parseFieldSelector( widgetId ) {
return 'input[name="' + widgetIdToFieldPrefix( widgetId ) + '[' + compare.field + ']"]';
};
// @note: change this function if you don't want custom Heading change to appear for all the widgets.
// If field variable is empty, then that means that field doesn't exist for that widget.
// So use this logic if you don't want the custom heading manipulation if the field doesn't exist for a widget
function modify_widget( evt, $widget, content ) {
var field = null;
var field_value = '';
if( content ) {
field = $( content ).find( parseFieldSelector( $widget.find( widgetIdSelector ).val() ) );
}
else {
field = $widget.find( parseFieldSelector( $widget.find( widgetIdSelector ).val() ) );
}
if( field ) {
field_value = ( ( field.attr( 'type' ) != 'radio' && field.attr( 'type' ) != 'checkbox' )
|| field.is( ':checked' ) ) ? field.val() : '';
}
modify_heading( $widget.find( compare.heading_selector ), field_value == compare.value );
}
function parseWidgetId( widgetId ) {
var matches, parsed = {
number: null,
id_base: null
};
matches = widgetId.match( /^(.+)-(\d+)$/ );
if ( matches ) {
parsed.id_base = matches[1];
parsed.number = parseInt( matches[2], 10 );
} else {
parsed.id_base = widgetId;
}
return parsed;
}
function widgetIdToSettingId( widgetId ) {
var parsed = parseWidgetId( widgetId ), settingId;
settingId = 'widget_' + parsed.id_base;
if ( parsed.number ) {
settingId += '[' + parsed.number + ']';
}
return settingId;
}
function widgetIdToFieldPrefix( widgetId ) {
var parsed = parseWidgetId( widgetId ), settingId;
settingId = 'widget-' + parsed.id_base;
if ( parsed.number ) {
settingId += '[' + parsed.number + ']';
}
return settingId;
}
var api = wp.customize;
if( api ) {
// We ate in the customizer
widgetIdSelector = '> .widget-inside > .form > .widget-id';
api.bind( 'ready', function() {
function add_widget( evt, $widget ) {
var control;
control = api.control( widgetIdToSettingId( $widget.find( widgetIdSelector ).val() ) );
function updateTitle( evt ) {
modify_widget( null, $widget );
};
if ( control ) {
control.setting.bind( updateTitle );
}
updateTitle();
};
api.control.each( function ( control ) {
if( control.id && 0 === control.id.indexOf( 'widget_' ) ) {
api.section( control.section.get(), function( section ) {
function onExpanded( isExpanded ) {
if ( isExpanded ) {
section.expanded.unbind( onExpanded );
modify_widget( null, control.container.find( '.widget' ), control.params.widget_content );
}
};
if ( section.expanded() ) {
onExpanded( true );
} else {
section.expanded.bind( onExpanded );
}
} );
}
} );
$( document ).on( 'widget-added', add_widget );
} );
}
else {
// We are in wp-admin -> Appearance -> Widgets
// Use proper condition and CODE if you want to target any page builder
// that doesn't use WP Core Widget Markup or Core JavaScript
$( window ).on( 'load', function() {
$( '#widgets-right div.widgets-sortables div.widget' ).each( function() {
modify_widget( 'non-customizer', $( this ) );
} );
$( document ).on( 'widget-added', modify_widget );
} );
}
$( document ).on( 'widget-updated', modify_widget );
})( window.wp, jQuery );
```
### Plugin Usage:
>
> ***Note:*** With the above sample Plugin CODE as it is, if you set the `title` of a Widget to `yes`, then it'll show *(mobile/desktop)* within the Widget Control UI heading, all the other Widget's will have *(desktop only)* in the Heading. In the customizer the change will be immediate, in `wp-admin -> widgets` the change will show after you `save` the changes. Of course you can change this behaviour by modifying the CODE (in JavaScript) to do the heading change for a different `field_name` or to only show that specific heading to some widgets and not to all of them.
>
>
>
For example, say you have a field named `use_mobile`, and you want to set the heading to *(mobile/desktop)* when it's set to `yes`. Then set the `compare` variable to something like:
```
var compare = {
field: 'use_mobile',
value: 'yes',
heading: ' <i>(mobile/desktop)</i> ',
alt_heading: ' <i>(desktop only)</i> ',
heading_selector: '.in-widget-title'
};
```
Also, if you want to change the entire heading (instead of just `.in-widget-title`), then you may change the `heading_selector` setting along with the correct markup for `heading` & `alt_heading` to do so. The possibilities are endless, but make sure WordPress core CODE doesn't produce any error if you want to be too much creative with the resulting markup.
Page builder integration:
-------------------------
Whether or not either of these solutions will work for a page builder will depend on that page builder implementation. If it uses WordPress supplied methods to load Widget Control UI then it should work without any modification, otherwise similar (but modified) implication may be possible for page builders as well. |
261,043 | <p>I am using <a href="https://en-ca.wordpress.org/plugins/custom-list-table-example/" rel="nofollow noreferrer">the Custom List Table Example plugin</a> as a basis to create my own custom list table. Everything is great, except one thorny point.</p>
<p>When I am processing bulk actions via the <code>process_bulk_action()</code> method, I would like to redirect using <code>wp_redirect()</code>. Here is an example:</p>
<pre><code>function process_bulk_action() {
// Some security check code here
// Get the bulk action
$action = $this->current_action();
if ($action == 'bulk_trash') {
// Code for the "delete process"
// Assuming "delete process" is successful
wp_redirect("http://url/path.php?update=1&message=some_message");
exit;
}
}
</code></pre>
<p>Please note, in the call <code>wp_redirect("http://url/path.php?update=1&message=some_message")</code>, I am trying to redirect to the same page that displays the list table in order to reload it with the result of the trash process. Also note that there is a <code>message</code> in the path that allows me to display a notification to the user regarding the result of the bulk action.</p>
<p>The problem is, I get an error message <code>Cannot modify header information - headers already sent by <file path></code>.</p>
<p>I understand what the message means, and the reasons behind it (the page is already loaded and cannot be redirected). However, how do I redirect then if I would like to do that after I process the bulk action? If redirect is not the correct solution, what other options do I have that allow me to re-load the custom <code>wp_list_table</code> again so that the listed records reflect items being deleted (i.e., less published items, and more items in trash)?</p>
<p>Thanks.</p>
| [
{
"answer_id": 272339,
"author": "Abhilash Narayan",
"author_id": 123210,
"author_profile": "https://wordpress.stackexchange.com/users/123210",
"pm_score": -1,
"selected": false,
"text": "<p>echo 'document.location=\"'<a href=\"http://url/path.php?update=1&message=some_message\" rel=\"nofollow noreferrer\">http://url/path.php?update=1&message=some_message</a>'\";';\nThis solved my problem</p>\n"
},
{
"answer_id": 312169,
"author": "DARK_DIESEL",
"author_id": 101932,
"author_profile": "https://wordpress.stackexchange.com/users/101932",
"pm_score": 1,
"selected": false,
"text": "<p>You need process you bulk actions in admin_action_{ACTION_NAME} hook. Not in wp_list_table class. Read more <a href=\"https://developer.wordpress.org/reference/hooks/admin_action__requestaction/\" rel=\"nofollow noreferrer\">here</a></p>\n"
},
{
"answer_id": 354230,
"author": "sorabh86",
"author_id": 153394,
"author_profile": "https://wordpress.stackexchange.com/users/153394",
"pm_score": 2,
"selected": false,
"text": "<p>Understand hierarchy, You don't need to redirect as form are posting values on same page.</p>\n\n<pre><code>function process_bulk_action() {\n\n // Some security check code here\n\n // Get the bulk action\n $action = $this->current_action();\n\n if ($action == 'bulk_trash') {\n\n // Code for the \"delete process\" \n $delete_ids = esc_sql($_POST['bulk-delete']);\n\n //loop over the array of record ids\n foreach($delete_ids as $id) {\n self::delete_item($id);\n }\n\n // show admin notice\n echo '<div class=\"notice notice-success is-dismissible\"><p>Bulk Deleted..</p></div>';\n }\n\n}\n</code></pre>\n\n<p>another method is prepare_items</p>\n\n<pre><code>public function prepare_items() {\n // first check for action\n $this->process_bulk_action();\n\n // then code to render your view.\n\n}\n</code></pre>\n"
}
]
| 2017/03/22 | [
"https://wordpress.stackexchange.com/questions/261043",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
]
| I am using [the Custom List Table Example plugin](https://en-ca.wordpress.org/plugins/custom-list-table-example/) as a basis to create my own custom list table. Everything is great, except one thorny point.
When I am processing bulk actions via the `process_bulk_action()` method, I would like to redirect using `wp_redirect()`. Here is an example:
```
function process_bulk_action() {
// Some security check code here
// Get the bulk action
$action = $this->current_action();
if ($action == 'bulk_trash') {
// Code for the "delete process"
// Assuming "delete process" is successful
wp_redirect("http://url/path.php?update=1&message=some_message");
exit;
}
}
```
Please note, in the call `wp_redirect("http://url/path.php?update=1&message=some_message")`, I am trying to redirect to the same page that displays the list table in order to reload it with the result of the trash process. Also note that there is a `message` in the path that allows me to display a notification to the user regarding the result of the bulk action.
The problem is, I get an error message `Cannot modify header information - headers already sent by <file path>`.
I understand what the message means, and the reasons behind it (the page is already loaded and cannot be redirected). However, how do I redirect then if I would like to do that after I process the bulk action? If redirect is not the correct solution, what other options do I have that allow me to re-load the custom `wp_list_table` again so that the listed records reflect items being deleted (i.e., less published items, and more items in trash)?
Thanks. | Understand hierarchy, You don't need to redirect as form are posting values on same page.
```
function process_bulk_action() {
// Some security check code here
// Get the bulk action
$action = $this->current_action();
if ($action == 'bulk_trash') {
// Code for the "delete process"
$delete_ids = esc_sql($_POST['bulk-delete']);
//loop over the array of record ids
foreach($delete_ids as $id) {
self::delete_item($id);
}
// show admin notice
echo '<div class="notice notice-success is-dismissible"><p>Bulk Deleted..</p></div>';
}
}
```
another method is prepare\_items
```
public function prepare_items() {
// first check for action
$this->process_bulk_action();
// then code to render your view.
}
``` |
261,080 | <p>Does anyone know how I can get rid of index.php in my URL?
Right now if I add a new page, the address will be:</p>
<p>www.mywebsite.com/index.php/page1</p>
<p>But I want it to be:</p>
<p>wwww.mywebsite.com/page1</p>
<p>I surfed the web a lot! Changing the permalink doesn't work. Does anyone know how I can fix this?</p>
| [
{
"answer_id": 261081,
"author": "Scott",
"author_id": 111485,
"author_profile": "https://wordpress.stackexchange.com/users/111485",
"pm_score": 3,
"selected": true,
"text": "<p>This is a classical case. All you need to do is to use Rewrite Rules. With Apache, you can do it in .htaccess:</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>More on this in <a href=\"https://codex.wordpress.org/Using_Permalinks\" rel=\"nofollow noreferrer\">codex</a>.</p>\n"
},
{
"answer_id": 261089,
"author": "Arvind kumar",
"author_id": 116072,
"author_profile": "https://wordpress.stackexchange.com/users/116072",
"pm_score": 0,
"selected": false,
"text": "<p>first try to change the permalinks in general setting of you website dashboard.....if not then you have to edit your .htaccess file....hope this will help to resolve the issue..!!</p>\n"
},
{
"answer_id": 301489,
"author": "MUHAMMAD SHAFIQUE",
"author_id": 142211,
"author_profile": "https://wordpress.stackexchange.com/users/142211",
"pm_score": 0,
"selected": false,
"text": "<p>I was also a victim of this error.But Now have solved the issue in CWP permalink index.php remove solution as follow:</p>\n\n<p>Create a .htacess file in the root directory of your website /public_html/yoursite.com</p>\n\n<p>Write the following code in it</p>\n\n<pre><code># BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /index.php [L]\n</IfModule>\n# END WordPress\n</code></pre>\n\n<p>then Goto wp-admin >>> settings >>> permalinks</p>\n\n<p>Select \"Custom Structure\" and remove \"index.php\" only from it</p>\n\n<p>Save and check ... It works perfectly!</p>\n\n<p>thanks at all</p>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261080",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116068/"
]
| Does anyone know how I can get rid of index.php in my URL?
Right now if I add a new page, the address will be:
www.mywebsite.com/index.php/page1
But I want it to be:
wwww.mywebsite.com/page1
I surfed the web a lot! Changing the permalink doesn't work. Does anyone know how I can fix this? | This is a classical case. All you need to do is to use Rewrite Rules. With Apache, you can do it in .htaccess:
```
# 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
```
More on this in [codex](https://codex.wordpress.org/Using_Permalinks). |
261,090 | <p>I was wondering, how do I hide pages from my navbar? </p>
<p>I don't mean hide visibility to private nor do I want to remove the page from appearance -> menus -> MY_MENU (as I have custom CSS on one of the pages). </p>
<p><a href="https://i.stack.imgur.com/E6pJz.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/E6pJz.png" alt="My navigation bar"></a></p>
<p>just for reference, this is what my navbar looks like. </p>
<p><strong>CSS</strong></p>
<pre><code>.menu-item-346 a {
padding:1em;
text-align: center;
display:inline-block;
text-decoration: none !important;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-ms-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.menu-item-346 a:link, .menu-item-346 a:visited {
color:var(--white);
border:1px solid var(--white);
background:transparent;
}
.menu-item-346 a:hover, .menu-item-346 a:active {
color:var(--blue);
background:var(--white);
}
</code></pre>
| [
{
"answer_id": 261091,
"author": "pomaaa",
"author_id": 115755,
"author_profile": "https://wordpress.stackexchange.com/users/115755",
"pm_score": 0,
"selected": false,
"text": "<p>First you need to check the class of the item that you want to hide. If it's .menu-item-346, just add this to underneath your CSS:</p>\n\n<pre><code>.menu-item-346 { display: none !important; }\n</code></pre>\n"
},
{
"answer_id": 261259,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of writing custom styles like <code>.menu-item-346</code> where you are hardcoding some styles...</p>\n\n<p>why not just add a <strong>custom css class</strong> with the editor under <code>Appearance -> Menus</code>.</p>\n\n<p>Wordpress has this build in.<br>\nUnder <code>Appearance -> Menus</code> you need to open the <code>Screen Options</code> and tick the box <code>CSS Classes</code>.\nAfter this you can now add one or multiple classes to every single menu-item.</p>\n\n<p>You than could just write some custom CSS rules for these classes.\nThis way, your customer could just add these classes by himself. (or not) </p>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261090",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/38839/"
]
| I was wondering, how do I hide pages from my navbar?
I don't mean hide visibility to private nor do I want to remove the page from appearance -> menus -> MY\_MENU (as I have custom CSS on one of the pages).
[](https://i.stack.imgur.com/E6pJz.png)
just for reference, this is what my navbar looks like.
**CSS**
```
.menu-item-346 a {
padding:1em;
text-align: center;
display:inline-block;
text-decoration: none !important;
-webkit-transition: all 0.2s ease-in-out;
-moz-transition: all 0.2s ease-in-out;
-ms-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
}
.menu-item-346 a:link, .menu-item-346 a:visited {
color:var(--white);
border:1px solid var(--white);
background:transparent;
}
.menu-item-346 a:hover, .menu-item-346 a:active {
color:var(--blue);
background:var(--white);
}
``` | Instead of writing custom styles like `.menu-item-346` where you are hardcoding some styles...
why not just add a **custom css class** with the editor under `Appearance -> Menus`.
Wordpress has this build in.
Under `Appearance -> Menus` you need to open the `Screen Options` and tick the box `CSS Classes`.
After this you can now add one or multiple classes to every single menu-item.
You than could just write some custom CSS rules for these classes.
This way, your customer could just add these classes by himself. (or not) |
261,117 | <p>Devs</p>
<p>I have a WP-cronjob running that is supposed to import some pictures and set them as attachments for a specific post. But I'm apparently unable to do so while running it as a WP-cronjob - it works just fine when i run it on "init" for exampel. But as soon as i try to run it within a WP-cronjob it fails.</p>
<pre><code> register_activation_hook( __FILE__, 'OA_FeedManager_activated' );
function importpicture_activated()
{
if (! wp_next_scheduled( 'import_feed' ) )
{
wp_schedule_event( time(), 'hourly', 'import' );
}
}
add_action( 'import', 'call_import' );
function call_import()
{
//lots of code, where i get data from a XML feed, and creates a new post. no need to include it.
foreach($oDataXML->Media->Fotos->Foto as $key => $value)
{
$filename = wp_upload_dir()['path'].'/'.$oDataXML->SagsNr->__toString().'_'. $value->Checksum->__toString() . '.jpg';
$sPicture = $value->URL->__toString();
copy($sPicture, $filename);
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $iPost_ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
</code></pre>
<p>As I have been able to read, its because that the <code>wp_generate_attachment_metadata()</code> function is not currently included when doing a <code>wp-cronjob</code>, and I should <code>require_once('wp-load.php')</code>.</p>
<p>But sadly I'm not able to require that while running a cron job (I tried both <code>wp-load.php</code> & <code>wp-includes/post.php</code>) - but neither does the trick.</p>
<p>So maybe there is a wise man on WPSE that can enlighten me how I'm suppose to get my WP-cronjob running correctly.</p>
| [
{
"answer_id": 261124,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<p>At the top of your cronjob script (for example: <code>my-cron.php</code>), do this:</p>\n<pre><code>if ( ! defined('ABSPATH') ) {\n /** Set up WordPress environment */\n require_once( dirname( __FILE__ ) . '/wp-load.php' );\n}\n</code></pre>\n<p>Then setup cron like this in your server:</p>\n<pre><code>5 * * * * wget -q -O - http://your-domain.com/my-cron.php\n</code></pre>\n<blockquote>\n<p><strong>Note:</strong> perhaps you were trying to run cron as PHP Command Line (CLI), that'll not work. You need to run cron as HTTP request (with <code>wget</code> or <code>curl</code>), as shown above.</p>\n</blockquote>\n<p>For more information <a href=\"https://developer.wordpress.org/plugins/cron/hooking-wp-cron-into-the-system-task-scheduler/#mac-os-x-and-linux\" rel=\"nofollow noreferrer\">read this official WordPress document</a>.</p>\n<h2>Update:</h2>\n<p>Based on newly added CODE, I can see this CODE is wrong:</p>\n<pre><code>register_activation_hook( __FILE__, 'OA_FeedManager_activated' );\nfunction importpicture_activated() {\n if ( ! wp_next_scheduled( 'import_feed' ) ) {\n wp_schedule_event( time(), 'hourly', 'import' );\n }\n }\n\n add_action( 'import', 'call_import' );\n function call_import() {\n // lots of code\n }\n</code></pre>\n<p>You checked <code>if ( ! wp_next_scheduled( 'import_feed' ) )</code> but you are scheduling <code>add_action( 'import', 'call_import' );</code>. For cron to work properly you must register the same action <code>import</code>. Also, your activation hook is <code>OA_FeedManager_activated</code>, make sure it runs <code>importpicture_activated</code> function. So the CODE should be like:</p>\n<pre><code>register_activation_hook( __FILE__, 'OA_FeedManager_activated' );\n\nfunction OA_FeedManager_activated() {\n importpicture_activated();\n}\n\nfunction importpicture_activated() {\n if ( ! wp_next_scheduled( 'import' ) ) {\n wp_schedule_event( time(), 'hourly', 'import' );\n }\n }\n\n add_action( 'import', 'call_import' );\n function call_import() {\n // lots of code\n }\n</code></pre>\n<p>To check if your cron is registered properly, you may use the <a href=\"https://wordpress.org/plugins/wp-crontrol/\" rel=\"nofollow noreferrer\">control plugin</a>. Also, activate <a href=\"https://codex.wordpress.org/Debugging_in_WordPress\" rel=\"nofollow noreferrer\">WP debugging</a> to see what error your CODE is generating.</p>\n<blockquote>\n<p><em><strong>Note:</strong></em> For undefined function <code>wp_generate_attachment_metadata()</code> error <a href=\"https://wordpress.stackexchange.com/a/261262/110572\">check Mark's</a> answer.</p>\n</blockquote>\n<p>Also, since you've scheduled the cron in plugin's activation hook, you must deactivate and then activate the plugin again if you change activation hook function. Using Crontrol Plugin, make sure there is not unnecessary cron registered in the backend.</p>\n<p>Finally, check if in <code>wp-config.php</code> you have <code>define( 'DISABLE_WP_CRON', true );</code>. You must remove it (if it is there) or set it to <code>false</code>, if you want WP cron to run on normal WP load. Otherwise, you'll need to set cron with OS crontab (like shown at the beginning of my answer.)</p>\n"
},
{
"answer_id": 261262,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 5,
"selected": true,
"text": "<p>Some of what is usually admin side functionality is not included as part of the \"main\" wordpress bootstrap, files containing uploaded file manipulation functions are one of them and you need to explicitly include them by adding</p>\n\n<pre><code>include_once( ABSPATH . 'wp-admin/includes/image.php' );\n</code></pre>\n\n<p>into your <code>call_import</code> function.</p>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261117",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116092/"
]
| Devs
I have a WP-cronjob running that is supposed to import some pictures and set them as attachments for a specific post. But I'm apparently unable to do so while running it as a WP-cronjob - it works just fine when i run it on "init" for exampel. But as soon as i try to run it within a WP-cronjob it fails.
```
register_activation_hook( __FILE__, 'OA_FeedManager_activated' );
function importpicture_activated()
{
if (! wp_next_scheduled( 'import_feed' ) )
{
wp_schedule_event( time(), 'hourly', 'import' );
}
}
add_action( 'import', 'call_import' );
function call_import()
{
//lots of code, where i get data from a XML feed, and creates a new post. no need to include it.
foreach($oDataXML->Media->Fotos->Foto as $key => $value)
{
$filename = wp_upload_dir()['path'].'/'.$oDataXML->SagsNr->__toString().'_'. $value->Checksum->__toString() . '.jpg';
$sPicture = $value->URL->__toString();
copy($sPicture, $filename);
$filetype = wp_check_filetype( basename( $filename ), null );
$wp_upload_dir = wp_upload_dir();
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $filename, $iPost_ID );
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
}
```
As I have been able to read, its because that the `wp_generate_attachment_metadata()` function is not currently included when doing a `wp-cronjob`, and I should `require_once('wp-load.php')`.
But sadly I'm not able to require that while running a cron job (I tried both `wp-load.php` & `wp-includes/post.php`) - but neither does the trick.
So maybe there is a wise man on WPSE that can enlighten me how I'm suppose to get my WP-cronjob running correctly. | Some of what is usually admin side functionality is not included as part of the "main" wordpress bootstrap, files containing uploaded file manipulation functions are one of them and you need to explicitly include them by adding
```
include_once( ABSPATH . 'wp-admin/includes/image.php' );
```
into your `call_import` function. |
261,123 | <p>I am trying to change the logo one specific page of this wordpress site. <a href="http://staging-domesticbliss.transitiongraphics.co.uk/db-home-help/" rel="nofollow noreferrer">http://staging-domesticbliss.transitiongraphics.co.uk/db-home-help/</a></p>
<p>Currently I know I am targeting the right page and element as I can hide the logo using:</p>
<pre><code>.page-id-6935 .w-logo-img > img {
display:none;
}
</code></pre>
<p>But how do I now show the logo located at <a href="http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png" rel="nofollow noreferrer">http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png</a></p>
<p>Thanks in advance</p>
| [
{
"answer_id": 261125,
"author": "Dan Knauss",
"author_id": 57078,
"author_profile": "https://wordpress.stackexchange.com/users/57078",
"pm_score": 0,
"selected": false,
"text": "<p>Logo settings are controlled through the WordPress customizer and administrator interface for most themes today. This site is using the Impreza theme; <a href=\"https://help.us-themes.com/impreza/options/logo-options/\" rel=\"nofollow noreferrer\">see the documentation for its logo settings</a>.</p>\n"
},
{
"answer_id": 261142,
"author": "Megh Gandhi",
"author_id": 80611,
"author_profile": "https://wordpress.stackexchange.com/users/80611",
"pm_score": 2,
"selected": false,
"text": "<p>Rather than using the tag in html, set the logo using the CSS background property. Use background-image:url(<a href=\"http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png\" rel=\"nofollow noreferrer\">http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png</a>); instead.</p>\n"
},
{
"answer_id": 261154,
"author": "Grant Smith",
"author_id": 116101,
"author_profile": "https://wordpress.stackexchange.com/users/116101",
"pm_score": 1,
"selected": false,
"text": "<pre><code>.page-id-6935 img.for_default {\n content: url(/wp-content/uploads/2017/03/db-homehelp-black-xl.png);\n}\n</code></pre>\n\n<p>Using content replaces the logo, whereas background image puts the new logo behind the original.</p>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261123",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116101/"
]
| I am trying to change the logo one specific page of this wordpress site. <http://staging-domesticbliss.transitiongraphics.co.uk/db-home-help/>
Currently I know I am targeting the right page and element as I can hide the logo using:
```
.page-id-6935 .w-logo-img > img {
display:none;
}
```
But how do I now show the logo located at <http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png>
Thanks in advance | Rather than using the tag in html, set the logo using the CSS background property. Use background-image:url(<http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png>); instead. |
261,135 | <p>I would like to add a new menu item in the admin bar. So far, I have done the following:</p>
<pre><code>function add_book_menu_item ($wp_admin_bar) {
$args = array (
'id' => 'book',
'title' => 'Book',
'href' => 'http://example.com/',
'parent' => 'new-content'
);
$wp_admin_bar->add_node( $args );
}
add_action('admin_bar_menu', 'add_book_menu_item');
</code></pre>
<p>This is creating the <code>Book</code> menu item underneath the <code>+ New</code> menu (in the admin toolbar). However, the <code>Book</code> item comes in first (it is before the <code>Post</code> menu item). I would like it to appear between the <code>Media</code> and <code>Page</code> items. </p>
<p>The following image shows what I would like to do.</p>
<p><a href="https://i.stack.imgur.com/xTEut.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/xTEut.png" alt="enter image description here"></a></p>
<p>How do I do that?</p>
<p>Thanks.</p>
| [
{
"answer_id": 261125,
"author": "Dan Knauss",
"author_id": 57078,
"author_profile": "https://wordpress.stackexchange.com/users/57078",
"pm_score": 0,
"selected": false,
"text": "<p>Logo settings are controlled through the WordPress customizer and administrator interface for most themes today. This site is using the Impreza theme; <a href=\"https://help.us-themes.com/impreza/options/logo-options/\" rel=\"nofollow noreferrer\">see the documentation for its logo settings</a>.</p>\n"
},
{
"answer_id": 261142,
"author": "Megh Gandhi",
"author_id": 80611,
"author_profile": "https://wordpress.stackexchange.com/users/80611",
"pm_score": 2,
"selected": false,
"text": "<p>Rather than using the tag in html, set the logo using the CSS background property. Use background-image:url(<a href=\"http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png\" rel=\"nofollow noreferrer\">http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png</a>); instead.</p>\n"
},
{
"answer_id": 261154,
"author": "Grant Smith",
"author_id": 116101,
"author_profile": "https://wordpress.stackexchange.com/users/116101",
"pm_score": 1,
"selected": false,
"text": "<pre><code>.page-id-6935 img.for_default {\n content: url(/wp-content/uploads/2017/03/db-homehelp-black-xl.png);\n}\n</code></pre>\n\n<p>Using content replaces the logo, whereas background image puts the new logo behind the original.</p>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34253/"
]
| I would like to add a new menu item in the admin bar. So far, I have done the following:
```
function add_book_menu_item ($wp_admin_bar) {
$args = array (
'id' => 'book',
'title' => 'Book',
'href' => 'http://example.com/',
'parent' => 'new-content'
);
$wp_admin_bar->add_node( $args );
}
add_action('admin_bar_menu', 'add_book_menu_item');
```
This is creating the `Book` menu item underneath the `+ New` menu (in the admin toolbar). However, the `Book` item comes in first (it is before the `Post` menu item). I would like it to appear between the `Media` and `Page` items.
The following image shows what I would like to do.
[](https://i.stack.imgur.com/xTEut.png)
How do I do that?
Thanks. | Rather than using the tag in html, set the logo using the CSS background property. Use background-image:url(<http://staging-domesticbliss.transitiongraphics.co.uk/wp-content/uploads/2017/03/db-homehelp-black-xl.png>); instead. |
261,137 | <p>I would like to replace a textarea in a wordpress plugin with the wp editor if possible.
Here is the textarea code:</p>
<pre><code><textarea id="<?php echo esc_attr( $html['id'] ); ?>" class="awpcp-textarea required" <?php echo $html['readonly'] ? 'readonly="readonly"' : ''; ?> name="<?php echo esc_attr( $html['name'] ); ?>" rows="10" cols="50" data-max-characters="<?php echo esc_attr( $characters_allowed ); ?>" data-remaining-characters="<?php echo esc_attr( $remaining_characters ); ?>"><?php /* Content alerady escaped if necessary. Do not escape again here! */ echo $value; ?></textarea>
</code></pre>
<p>I would appreciate anyone's help. I'm not a coder per se.
Thank you in advance for your help.</p>
<p>Pete</p>
| [
{
"answer_id": 261423,
"author": "Samyer",
"author_id": 112788,
"author_profile": "https://wordpress.stackexchange.com/users/112788",
"pm_score": 1,
"selected": false,
"text": "<p>You would need to edit the plugin and insert an instance of the wp_editor instead of that textarea.</p>\n\n<p>Refer to <a href=\"https://codex.wordpress.org/Function_Reference/wp_editor\" rel=\"nofollow noreferrer\">the wp_editor function reference</a>.</p>\n"
},
{
"answer_id": 261427,
"author": "MahdiY",
"author_id": 105285,
"author_profile": "https://wordpress.stackexchange.com/users/105285",
"pm_score": -1,
"selected": false,
"text": "<p>Try this:</p>\n\n<pre><code><?php wp_editor( $value, $html['id'], array(\n 'textarea_name' => $html['name'],\n 'textarea_rows' => 10,\n) ); ?>\n</code></pre>\n\n<p>If you need set read only for editor see <a href=\"https://stackoverflow.com/questions/25849367/how-to-make-the-wordpress-editor-readonly\">How to make the wordpress editor readonly?</a></p>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261137",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86094/"
]
| I would like to replace a textarea in a wordpress plugin with the wp editor if possible.
Here is the textarea code:
```
<textarea id="<?php echo esc_attr( $html['id'] ); ?>" class="awpcp-textarea required" <?php echo $html['readonly'] ? 'readonly="readonly"' : ''; ?> name="<?php echo esc_attr( $html['name'] ); ?>" rows="10" cols="50" data-max-characters="<?php echo esc_attr( $characters_allowed ); ?>" data-remaining-characters="<?php echo esc_attr( $remaining_characters ); ?>"><?php /* Content alerady escaped if necessary. Do not escape again here! */ echo $value; ?></textarea>
```
I would appreciate anyone's help. I'm not a coder per se.
Thank you in advance for your help.
Pete | You would need to edit the plugin and insert an instance of the wp\_editor instead of that textarea.
Refer to [the wp\_editor function reference](https://codex.wordpress.org/Function_Reference/wp_editor). |
261,147 | <p>I wrote the following lines of code. It shows a dropdown menu with all available Wordpress categorys in the Wordpress customizer and can output the category slug. But instead of the slug I want to output the category id. Does anyone have an idea how to realize that?</p>
<pre><code>$categories = get_categories();
$cats = array();
$i = 0;
foreach($categories as $category){
if($i==0){
$default = $category->slug;
$i++;
}
$cats[$category->slug] = $category->name;
}
$wp_customize->add_setting('wptimes_homepage_featured_category', array(
'default' => $default
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'wptimes_homepage_featured_category', array(
'label' => 'Hervorgehobene Kategorie',
'description' => 'Wähle hier die Kategorie aus, die du auf der Startseite hervorheben möchtest.',
'section' => 'wptimes_homepage',
'settings' => 'wptimes_homepage_featured_category',
'type' => 'select',
'choices' => $cats
)));
</code></pre>
| [
{
"answer_id": 261242,
"author": "LWS-Mo",
"author_id": 88895,
"author_profile": "https://wordpress.stackexchange.com/users/88895",
"pm_score": 1,
"selected": true,
"text": "<p>In your foreach loop just do a quick <code>print_r($category)</code> to see all available options.</p>\n\n<p>Than you will see that you can use <code>$category->term_id</code> to get the <code>ID</code> of the term/category, instead of <code>$category->slug</code>.</p>\n\n<p>So for example, by using your code from above:</p>\n\n<pre><code>$categories = get_categories();\n\n$cats = array();\n$i = 0;\n\nforeach( $categories as $category ) {\n\n // uncomment to see all $category data\n #print_r($category);\n\n if( $i == 0 ){\n\n $default = $category->term_id;\n $i++;\n\n }\n $cats[$category->term_id] = $category->name;\n} \n\nprint_r($cats);\n// Prints for example: Array ( [12] => Child-Cat [2] => Parent-Cat [1] => Uncategorized ) \n</code></pre>\n"
},
{
"answer_id": 390833,
"author": "Mohammad Ayoub Khan",
"author_id": 207411,
"author_profile": "https://wordpress.stackexchange.com/users/207411",
"pm_score": 1,
"selected": false,
"text": "<p>I have a solution to this</p>\n<ol>\n<li>First create section</li>\n</ol>\n<pre class=\"lang-php prettyprint-override\"><code>// FRONT Page Settings settings.\n$wp_customize->add_section(\n 'betacoders_theme_front_page_options',\n array(\n 'title' => __(' - Front Page Settings ', 'betacoders'),\n 'capability' => 'edit_theme_options',\n 'description' => __('FRONT Page Layout Options', 'betacoders'),\n 'priority' => 2,\n )\n);\n</code></pre>\n<pre class=\"lang-php prettyprint-override\"><code>// ==================================\n// = Featured Categories SELECTOR =\n// ==================================\n$wp_customize->add_setting('featured_post', array(\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n));\n\n// get categories list\n$categories = get_categories(array(\n 'orderby' => 'name',\n 'order' => 'ASC',\n 'hide_empty' => 0,\n // 'parent' => 0,\n // 'hierarchical' => true\n));\n$cat_ids = array_map(function ($el) {\n return $el->cat_ID;\n}, $categories);\n\n$cat_names = array_map(function ($el) {\n return $el->cat_name;\n}, $categories);\n\n$wp_customize->add_control('mys_featured_post_ctrl', [\n 'label' => 'Featured Post from Category',\n 'description' => 'Featured Post from Category',\n 'section' => 'betacoders_theme_front_page_options',\n 'settings' => 'featured_post',\n // 'type' => 'select',\n 'type' => 'checkbox',\n 'choices' => array() + array_combine($cat_ids, $cat_names) // combines all categories data\n]);\n</code></pre>\n"
},
{
"answer_id": 390835,
"author": "Mohammad Ayoub Khan",
"author_id": 207411,
"author_profile": "https://wordpress.stackexchange.com/users/207411",
"pm_score": 0,
"selected": false,
"text": "<p>I have another solution</p>\n<pre class=\"lang-php prettyprint-override\"><code><?php\nfunction get_categories_select()\n{\n $teh_cats = get_categories();\n $results = [];\n\n $count = count($teh_cats);\n for ($i = 0; $i < $count; $i++) {\n if (isset($teh_cats[$i]))\n $results[$teh_cats[$i]->slug] = $teh_cats[$i]->name;\n else\n $count++;\n }\n return $results;\n}\n$wp_customize->add_setting('featured_post_1', array(\n 'capability' => 'edit_theme_options',\n 'type' => 'option',\n));\n$wp_customize->add_control('betacoders_featured_post_2', [\n 'label' => 'Featured Post from Category 2 ',\n 'description' => 'Featured Post from Category 2 ',\n 'section' => 'betacoders_theme_front_page_options',\n 'settings' => 'featured_post_1',\n 'type' => 'select',\n // 'type' => 'checkbox',\n 'choices' => get_categories_select(),\n]);\n?>\n</code></pre>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261147",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116113/"
]
| I wrote the following lines of code. It shows a dropdown menu with all available Wordpress categorys in the Wordpress customizer and can output the category slug. But instead of the slug I want to output the category id. Does anyone have an idea how to realize that?
```
$categories = get_categories();
$cats = array();
$i = 0;
foreach($categories as $category){
if($i==0){
$default = $category->slug;
$i++;
}
$cats[$category->slug] = $category->name;
}
$wp_customize->add_setting('wptimes_homepage_featured_category', array(
'default' => $default
));
$wp_customize->add_control(new WP_Customize_Control($wp_customize, 'wptimes_homepage_featured_category', array(
'label' => 'Hervorgehobene Kategorie',
'description' => 'Wähle hier die Kategorie aus, die du auf der Startseite hervorheben möchtest.',
'section' => 'wptimes_homepage',
'settings' => 'wptimes_homepage_featured_category',
'type' => 'select',
'choices' => $cats
)));
``` | In your foreach loop just do a quick `print_r($category)` to see all available options.
Than you will see that you can use `$category->term_id` to get the `ID` of the term/category, instead of `$category->slug`.
So for example, by using your code from above:
```
$categories = get_categories();
$cats = array();
$i = 0;
foreach( $categories as $category ) {
// uncomment to see all $category data
#print_r($category);
if( $i == 0 ){
$default = $category->term_id;
$i++;
}
$cats[$category->term_id] = $category->name;
}
print_r($cats);
// Prints for example: Array ( [12] => Child-Cat [2] => Parent-Cat [1] => Uncategorized )
``` |
261,169 | <p>I have to create a shortcode so I can paste the shortcode inside the mobile menu plugin's options, the plugin doesn't accept PHP so I can't do <code><span class="header-cart-total"><?php echo edd_cart_total(); ?></span></code></p>
<p>The issue I'm having is echo'ing <code>edd_get_cart_total()</code> which causes a white screen on my website. I have to echo it or the cart total amount price doesn't show up fully-formatted. How do I echo it? This is in my functions.php file:</p>
<pre><code>function eddminicartfunc() {
return
'<div class="mobilemenucart">
<i class="fa fa-shopping-cart"></i>
<span class="header-cart-total"> ' . echo edd_get_cart_total() . ' </span>
<span class="header-cart edd-cart-quantity">
' . edd_get_cart_quantity() .'
</span>
</div>';
}
add_shortcode('eddminicart', 'eddminicartfunc');
</code></pre>
| [
{
"answer_id": 261171,
"author": "Sam",
"author_id": 115586,
"author_profile": "https://wordpress.stackexchange.com/users/115586",
"pm_score": 0,
"selected": false,
"text": "<p>I am not sure as to where you are trying to insert your code and what limits it has but try it like this and see if it works?</p>\n\n<pre><code>function eddminicartfunc() {\n\n $foo = '<div class=\"mobilemenucart\">\n <i class=\"fa fa-shopping-cart\"></i>\n <span class=\"header-cart-total\"> ' . echo edd_get_cart_total() . ' </span>\n <span class=\"header-cart edd-cart-quantity\">\n ' . edd_get_cart_quantity() .'\n </span>\n </div>';\n return $foo;\n }\nadd_shortcode('eddminicart', 'eddminicartfunc');\n</code></pre>\n"
},
{
"answer_id": 261176,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 3,
"selected": true,
"text": "<p><code>echo</code> is a PHP language construct which pushes values to the output buffer. It does not have a return value, so concatenating it with a string would cause everything after the <code>echo</code> to immediately be sent to the output buffer, and everything prior to <code>echo</code> to compose the concatenated string. This is such a misuse of <code>echo</code> that PHP itself doesn't actually allow it - if you had WordPress debugging enabled you would see an error similar to</p>\n\n<blockquote>\n <p>Parse error: syntax error, unexpected 'echo' (T_ECHO)</p>\n</blockquote>\n\n<p>This error is what is causing your white screen - when not in debug mode, WordPress suppresses error output to avoid exposing potentially sensitive information to end-users.</p>\n\n<p>You shouldn't use <code>echo</code> in shortcode logic, as internally WordPress does more processing with a shortcode's return value. So using <code>echo</code> in a shortcode has a good chance to mess up your final markup.</p>\n\n<p>The inclusion of the <code>echo</code> before the <code>edd_get_cart_total()</code> does not result in currency formatting. I've dug through <a href=\"https://github.com/easydigitaldownloads/easy-digital-downloads/blob/master/includes/cart/class-edd-cart.php#L1150\" rel=\"nofollow noreferrer\">the plugin in question's source code</a> just to be sure. Rather, it's more likely that some function is hooked to the <code>edd_get_cart_total</code> filter to format the output in templates (thus formatting the total when you used it in your <code>header.php</code> template), however within the context of a shortcode that filter is not attached.</p>\n\n<p>Conveniently, the plugin provides the <code>ebb_cart_total()</code> function which will always produce a currency-formatted total string. The first argument to the function is <code>$echo</code> which is true by default, and will cause the function to display the total instead of returning it - which, as detailed earlier, is not something you want to do in a shortcode - so set this argument to <code>false</code> to have the function return a string which you may concatenate with the rest of your shortcode markup.</p>\n\n<p>All together:</p>\n\n<pre><code>function eddminicartfunc() {\n return \n '<div class=\"mobilemenucart\">\n <i class=\"fa fa-shopping-cart\"></i>\n <span class=\"header-cart-total\"> ' . edd_cart_total( false ) . ' </span>\n <span class=\"header-cart edd-cart-quantity\">' . edd_get_cart_quantity() . '</span>\n </div>';\n}\nadd_shortcode( 'eddminicart', 'eddminicartfunc' );\n</code></pre>\n"
}
]
| 2017/03/23 | [
"https://wordpress.stackexchange.com/questions/261169",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/49532/"
]
| I have to create a shortcode so I can paste the shortcode inside the mobile menu plugin's options, the plugin doesn't accept PHP so I can't do `<span class="header-cart-total"><?php echo edd_cart_total(); ?></span>`
The issue I'm having is echo'ing `edd_get_cart_total()` which causes a white screen on my website. I have to echo it or the cart total amount price doesn't show up fully-formatted. How do I echo it? This is in my functions.php file:
```
function eddminicartfunc() {
return
'<div class="mobilemenucart">
<i class="fa fa-shopping-cart"></i>
<span class="header-cart-total"> ' . echo edd_get_cart_total() . ' </span>
<span class="header-cart edd-cart-quantity">
' . edd_get_cart_quantity() .'
</span>
</div>';
}
add_shortcode('eddminicart', 'eddminicartfunc');
``` | `echo` is a PHP language construct which pushes values to the output buffer. It does not have a return value, so concatenating it with a string would cause everything after the `echo` to immediately be sent to the output buffer, and everything prior to `echo` to compose the concatenated string. This is such a misuse of `echo` that PHP itself doesn't actually allow it - if you had WordPress debugging enabled you would see an error similar to
>
> Parse error: syntax error, unexpected 'echo' (T\_ECHO)
>
>
>
This error is what is causing your white screen - when not in debug mode, WordPress suppresses error output to avoid exposing potentially sensitive information to end-users.
You shouldn't use `echo` in shortcode logic, as internally WordPress does more processing with a shortcode's return value. So using `echo` in a shortcode has a good chance to mess up your final markup.
The inclusion of the `echo` before the `edd_get_cart_total()` does not result in currency formatting. I've dug through [the plugin in question's source code](https://github.com/easydigitaldownloads/easy-digital-downloads/blob/master/includes/cart/class-edd-cart.php#L1150) just to be sure. Rather, it's more likely that some function is hooked to the `edd_get_cart_total` filter to format the output in templates (thus formatting the total when you used it in your `header.php` template), however within the context of a shortcode that filter is not attached.
Conveniently, the plugin provides the `ebb_cart_total()` function which will always produce a currency-formatted total string. The first argument to the function is `$echo` which is true by default, and will cause the function to display the total instead of returning it - which, as detailed earlier, is not something you want to do in a shortcode - so set this argument to `false` to have the function return a string which you may concatenate with the rest of your shortcode markup.
All together:
```
function eddminicartfunc() {
return
'<div class="mobilemenucart">
<i class="fa fa-shopping-cart"></i>
<span class="header-cart-total"> ' . edd_cart_total( false ) . ' </span>
<span class="header-cart edd-cart-quantity">' . edd_get_cart_quantity() . '</span>
</div>';
}
add_shortcode( 'eddminicart', 'eddminicartfunc' );
``` |
261,177 | <p>Following the <a href="https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/" rel="nofollow noreferrer">Wordpress documentation about the Rest Api</a>, i can manage to make an ajax POST working, but only when logged in to Wordpress. Here are the basic files shown in the documentation:</p>
<h3>functions.php</h3>
<pre><code>wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
</code></pre>
<h3>app.js</h3>
<pre><code>$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
</code></pre>
<p>I'm showing this example as it is presented as an easy one, but is <strong>not working</strong> when not logged in. It is always giving me a 401 Unauthorized response / “rest_cannot_create”...</p>
<p>Any tip ?</p>
<p>Thank you !</p>
| [
{
"answer_id": 261185,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>The </p>\n\n<blockquote>\n <p>the_author()</p>\n</blockquote>\n\n<p>function should return the name of the author of the post. See <a href=\"https://codex.wordpress.org/Function_Reference/the_author\" rel=\"nofollow noreferrer\">https://codex.wordpress.org/Function_Reference/the_author</a> .</p>\n\n<p>Your theme will have to use that function in the loop that displays the post meta.</p>\n"
},
{
"answer_id": 261203,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": true,
"text": "<p>Here are three possible approaches:</p>\n\n<ol>\n<li><p>A normal WP installation already has <a href=\"https://codex.wordpress.org/Custom_Fields\" rel=\"nofollow noreferrer\">custom fields</a> which you can add to your post. So you could use those to add the original author's name to. The only problem is that general themes usually do not display <code>the_meta</code>, because they do not know what to expect. In your case you would want to replace <code>the_author</code> in your theme with <code>the_meta</code> (don't mess with the original theme files, use a child theme!)</p></li>\n<li><p>Easier, but a bit hacky: add the original authors to the user list. They don't need to know they have an account, just provide bogus e-mail addresses and don't let WP send their password to them. Now you can simply assign them as authors and they will have their own author page as well.</p></li>\n<li><p>The most thorough approach is <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes\" rel=\"nofollow noreferrer\">adding a meta box</a> yourself (or use a <a href=\"https://ido.wordpress.org/plugins-wp/wck-custom-fields-and-custom-post-types-creator/\" rel=\"nofollow noreferrer\">plugin like WCK</a>). This gives you complete control on how to insert the information in your child theme.</p></li>\n</ol>\n"
},
{
"answer_id": 261209,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 0,
"selected": false,
"text": "<p>Just create a new author or user in wordpress and then just change the author from post quick edit option to that original author</p>\n"
},
{
"answer_id": 313502,
"author": "pankaj Batham",
"author_id": 150102,
"author_profile": "https://wordpress.stackexchange.com/users/150102",
"pm_score": -1,
"selected": false,
"text": "<p>the_author(); </p>\n\n<p>this function will return author name, you can change it on below path.</p>\n\n<p>Go to your database -> users table -> change (display_name)</p>\n"
}
]
| 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261177",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102982/"
]
| Following the [Wordpress documentation about the Rest Api](https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/), i can manage to make an ajax POST working, but only when logged in to Wordpress. Here are the basic files shown in the documentation:
### functions.php
```
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
```
### app.js
```
$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
```
I'm showing this example as it is presented as an easy one, but is **not working** when not logged in. It is always giving me a 401 Unauthorized response / “rest\_cannot\_create”...
Any tip ?
Thank you ! | Here are three possible approaches:
1. A normal WP installation already has [custom fields](https://codex.wordpress.org/Custom_Fields) which you can add to your post. So you could use those to add the original author's name to. The only problem is that general themes usually do not display `the_meta`, because they do not know what to expect. In your case you would want to replace `the_author` in your theme with `the_meta` (don't mess with the original theme files, use a child theme!)
2. Easier, but a bit hacky: add the original authors to the user list. They don't need to know they have an account, just provide bogus e-mail addresses and don't let WP send their password to them. Now you can simply assign them as authors and they will have their own author page as well.
3. The most thorough approach is [adding a meta box](https://codex.wordpress.org/Plugin_API/Action_Reference/add_meta_boxes) yourself (or use a [plugin like WCK](https://ido.wordpress.org/plugins-wp/wck-custom-fields-and-custom-post-types-creator/)). This gives you complete control on how to insert the information in your child theme. |
261,196 | <p>After months of leaving and deleting my WordPress site, I decided to try again. I downloaded the new version 4.7.3, installed and added a new post. So far so good. </p>
<p>I then went back to edit the post and the same error that I received before, cannot find the post; nothing to see here, message.</p>
<p>I cannot edit any new post that I create, but I can create a new post. The odd things are that I can modify the default message that is created on install by WordPress.</p>
<p>I deleted the database and the entire home directory multiple times. Deleted the .htaccess file and changed permalinks to no avail as well.</p>
<p>The setup is a fresh install with no plugins, no themes used except default. I tried switching between the different default also. Still, no dice.</p>
<p>Whenever I click the update, it returns a 404 error, page not found, as stated by Firefox dev tool. Add new does work. If I cick to edit a new post, it bring the page up in the editor. But as soon as I click update, 404 error.</p>
<p>This is the contents of the .htaccess file as by WordPress.</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><strong>Update</strong></p>
<p>I just noticed in one of the logs this error when I changed the permalink to plain. [Fri Mar 24 06:15:46 2017] [error] [client xxxxxxxx] File does not exist: /home/domain/public_html/403.shtml, referer: domain.com/wp-admin/post.php?post=14&action=edit</p>
<p>Any ideas?</p>
| [
{
"answer_id": 261210,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 0,
"selected": false,
"text": "<p>You could try to reset the WordPress permalinks to see if this is causing the 404 error. Here is a useful article on <a href=\"http://www.inmotionhosting.com/support/edu/wordpress/wordpress-features/reset-permalinks\" rel=\"nofollow noreferrer\">how to reset your permalinks</a>.</p>\n"
},
{
"answer_id": 261211,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 1,
"selected": false,
"text": "<p>To do so .. You need to login to wordpress admin and then need to save the permalink again..</p>\n\n<p>Just go to Settings >> Permalink</p>\n\n<p>And save without doing any changes.. and that error should be gone..</p>\n"
}
]
| 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261196",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116145/"
]
| After months of leaving and deleting my WordPress site, I decided to try again. I downloaded the new version 4.7.3, installed and added a new post. So far so good.
I then went back to edit the post and the same error that I received before, cannot find the post; nothing to see here, message.
I cannot edit any new post that I create, but I can create a new post. The odd things are that I can modify the default message that is created on install by WordPress.
I deleted the database and the entire home directory multiple times. Deleted the .htaccess file and changed permalinks to no avail as well.
The setup is a fresh install with no plugins, no themes used except default. I tried switching between the different default also. Still, no dice.
Whenever I click the update, it returns a 404 error, page not found, as stated by Firefox dev tool. Add new does work. If I cick to edit a new post, it bring the page up in the editor. But as soon as I click update, 404 error.
This is the contents of the .htaccess file as by WordPress.
```
# 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
```
**Update**
I just noticed in one of the logs this error when I changed the permalink to plain. [Fri Mar 24 06:15:46 2017] [error] [client xxxxxxxx] File does not exist: /home/domain/public\_html/403.shtml, referer: domain.com/wp-admin/post.php?post=14&action=edit
Any ideas? | To do so .. You need to login to wordpress admin and then need to save the permalink again..
Just go to Settings >> Permalink
And save without doing any changes.. and that error should be gone.. |
261,226 | <p>I'm using ACF to display a class within a <code><header></code> tag. The code for this sits within header.php. The custom field appears across all page templates in WP admin. Here's how it's working on the front-end: </p>
<pre><code><header
class="site-header
<?php
$header = get_field( 'header',$post->ID );
if ($header) {
echo esc_attr( $header );
}
else {
echo 'white';
}
?>"
>
</code></pre>
<p>This works perfectly on all pages apart from the 404. I'm receiving the following message within dev tools: </p>
<pre><code><header class="site-header <br /> <b>Notice</b>: Trying to get property of non-object in <b>/Applications/MAMP/htdocs/theme/wp-content/themes/theme/header.php</b> on line <b>28</b><br /> white">
</header>
</code></pre>
<p>This is happening because the 404 is a static page / post and does not have an ID associated to it.</p>
<p>Is there a function within WordPress I can use to display my custom field properly?</p>
| [
{
"answer_id": 261210,
"author": "Self Designs",
"author_id": 75780,
"author_profile": "https://wordpress.stackexchange.com/users/75780",
"pm_score": 0,
"selected": false,
"text": "<p>You could try to reset the WordPress permalinks to see if this is causing the 404 error. Here is a useful article on <a href=\"http://www.inmotionhosting.com/support/edu/wordpress/wordpress-features/reset-permalinks\" rel=\"nofollow noreferrer\">how to reset your permalinks</a>.</p>\n"
},
{
"answer_id": 261211,
"author": "Md. Amanur Rahman",
"author_id": 109213,
"author_profile": "https://wordpress.stackexchange.com/users/109213",
"pm_score": 1,
"selected": false,
"text": "<p>To do so .. You need to login to wordpress admin and then need to save the permalink again..</p>\n\n<p>Just go to Settings >> Permalink</p>\n\n<p>And save without doing any changes.. and that error should be gone..</p>\n"
}
]
| 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261226",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37548/"
]
| I'm using ACF to display a class within a `<header>` tag. The code for this sits within header.php. The custom field appears across all page templates in WP admin. Here's how it's working on the front-end:
```
<header
class="site-header
<?php
$header = get_field( 'header',$post->ID );
if ($header) {
echo esc_attr( $header );
}
else {
echo 'white';
}
?>"
>
```
This works perfectly on all pages apart from the 404. I'm receiving the following message within dev tools:
```
<header class="site-header <br /> <b>Notice</b>: Trying to get property of non-object in <b>/Applications/MAMP/htdocs/theme/wp-content/themes/theme/header.php</b> on line <b>28</b><br /> white">
</header>
```
This is happening because the 404 is a static page / post and does not have an ID associated to it.
Is there a function within WordPress I can use to display my custom field properly? | To do so .. You need to login to wordpress admin and then need to save the permalink again..
Just go to Settings >> Permalink
And save without doing any changes.. and that error should be gone.. |
261,293 | <p>I added the possibility to register on my site (with the role of subscriber), however each registration creates an author page for the user, but I do not want these pages to be indexed, only the pages of authors with roles above.</p>
<p>Something like the code below, but theres no get_user_role function, so i do not know how to get to that result. I would be grateful if anyone could help.</p>
<pre><code><meta name="robots" content="<?php if( is_page('author') ) && get_user_role('subscriber'); {
echo "noindex, nofollow";
}else{
echo "index, follow";
} ?>" />
</code></pre>
<p>Edit:</p>
<p>This is the code of @belinos answer. I put it inside header.php, the problem is that an error appears on the <a href="http://gamersaction.pe.hu/" rel="nofollow noreferrer">online site</a>, on localhost it does not appear.</p>
<pre><code><?php $curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );
$auth_data = get_userdata( $curauth->ID );
if ( in_array( 'subscriber', $auth_data->roles )) { ?>
<meta name="robots" content="noindex, nofollow"/>
<?php } else { ?>
<meta name="robots" content="index, follow"/>
<?php } ?>
</code></pre>
<p>This is the error:</p>
<p>Warning: in_array() expects parameter 2 to be array, null given in /home/u836053643/public_html/wp-content/themes/gamersaction/header.php on line 35</p>
<p>And that is the line 35:</p>
<pre><code>if ( in_array( 'subscriber', $auth_data->roles )) { ?>
</code></pre>
<p>The code works perfectly but is showing this error.</p>
| [
{
"answer_id": 261300,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 1,
"selected": false,
"text": "<p>The function you want is <code>get_userdata()</code>. Since you need to do this outside the loop, the process is a little less straight-forward.</p>\n\n<p>The first thing you need to do is set up a variable called <code>$curauth</code> which is an object that you create by accessing the database by using the <code>$_GET[]</code> superglobal.</p>\n\n<pre><code>$curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );\n</code></pre>\n\n<p>This assigning of <code>$curauth</code> must be in your <code>author.php</code> file. </p>\n\n<p>After that, we can then use the <code>get_userdata()</code> function and feed it the ID from <code>$curauth</code>.</p>\n\n<pre><code>$auth_data = get_userdata( $curauth->ID );\n</code></pre>\n\n<p>And from there your conditional becomes:</p>\n\n<pre><code>if ( in_array( 'subscriber', $auth_data->roles ) ) {\n // No Follow Code\n} else {\n // Follow Code\n}\n</code></pre>\n\n<p>My advice would be to make this all a function in your <code>functions.php</code> file:</p>\n\n<pre><code>function author_nofollow( $author ) {\n\n $auth_id = $author->ID;\n $auth_data = get_userdata( $auth_id );\n\n if ( in_array( 'subscriber', $auth_data->roles ) ) {\n echo 'noindex, nofollow';\n } else {\n echo 'index, follow';\n }\n}\n</code></pre>\n\n<p>Then you would just call it like this: </p>\n\n<pre><code><meta name=\"robots\" content=\"<?php author_nofollow( $curauth ); ?>\">\n</code></pre>\n"
},
{
"answer_id": 261577,
"author": "bosco",
"author_id": 25324,
"author_profile": "https://wordpress.stackexchange.com/users/25324",
"pm_score": 0,
"selected": false,
"text": "<p>The easiest way to accomplish this is to conditionally call <a href=\"https://developer.wordpress.org/reference/functions/wp_no_robots/\" rel=\"nofollow noreferrer\"><code>wp_no_robots()</code></a> (or echo your custom <code><meta></code> element) in a <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/wp_head\" rel=\"nofollow noreferrer\"><code>wp_head</code> action</a> hook. This has the added benefit of being modular - you could throw it in a plugin instead of performing theme modifications, if desired.</p>\n\n<p>In the instance of an author archive, <a href=\"https://codex.wordpress.org/Function_Reference/get_queried_object\" rel=\"nofollow noreferrer\"><code>get_queried_object()</code></a> will (usually - setting other query vars can throw this off) return an instance of <a href=\"https://codex.wordpress.org/Class_Reference/WP_User\" rel=\"nofollow noreferrer\"><code>WP_User</code></a> - the same type of object that <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow noreferrer\"><code>get_userdata()</code></a> returns.</p>\n\n<pre><code>function wpse261293_noindex_subscriber_profiles() {\n // Ignore non-author-archive content\n if( !is_author() )\n return;\n\n // Get a WP_User object for the author\n $author = get_queried_object();\n\n // If 'subscriber' is the author's only role, print a nofollow robots meta element\n if( count( $author->roles ) === 1 && in_array( 'subscriber', $author->roles ) )\n wp_no_robots(); // Alternately, replace this with echo( 'your_custom_meta_element' )\n}\n\nadd_action( 'wp_head', 'wpse261293_noindex_subscriber_profiles' );\n</code></pre>\n\n<p>If you or another plugin have custom user roles which could be granted to subscribers, you may need to alter the logic to account for them - potentially by checking if the author simply does not have administrator, editor, contributor, etc. roles.</p>\n"
}
]
| 2017/03/24 | [
"https://wordpress.stackexchange.com/questions/261293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
]
| I added the possibility to register on my site (with the role of subscriber), however each registration creates an author page for the user, but I do not want these pages to be indexed, only the pages of authors with roles above.
Something like the code below, but theres no get\_user\_role function, so i do not know how to get to that result. I would be grateful if anyone could help.
```
<meta name="robots" content="<?php if( is_page('author') ) && get_user_role('subscriber'); {
echo "noindex, nofollow";
}else{
echo "index, follow";
} ?>" />
```
Edit:
This is the code of @belinos answer. I put it inside header.php, the problem is that an error appears on the [online site](http://gamersaction.pe.hu/), on localhost it does not appear.
```
<?php $curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );
$auth_data = get_userdata( $curauth->ID );
if ( in_array( 'subscriber', $auth_data->roles )) { ?>
<meta name="robots" content="noindex, nofollow"/>
<?php } else { ?>
<meta name="robots" content="index, follow"/>
<?php } ?>
```
This is the error:
Warning: in\_array() expects parameter 2 to be array, null given in /home/u836053643/public\_html/wp-content/themes/gamersaction/header.php on line 35
And that is the line 35:
```
if ( in_array( 'subscriber', $auth_data->roles )) { ?>
```
The code works perfectly but is showing this error. | The function you want is `get_userdata()`. Since you need to do this outside the loop, the process is a little less straight-forward.
The first thing you need to do is set up a variable called `$curauth` which is an object that you create by accessing the database by using the `$_GET[]` superglobal.
```
$curauth = ( isset( $_GET[ 'author_name' ] ) ) ? get_user_by( 'slug', $author_name ) : get_userdata( intval ($author ) );
```
This assigning of `$curauth` must be in your `author.php` file.
After that, we can then use the `get_userdata()` function and feed it the ID from `$curauth`.
```
$auth_data = get_userdata( $curauth->ID );
```
And from there your conditional becomes:
```
if ( in_array( 'subscriber', $auth_data->roles ) ) {
// No Follow Code
} else {
// Follow Code
}
```
My advice would be to make this all a function in your `functions.php` file:
```
function author_nofollow( $author ) {
$auth_id = $author->ID;
$auth_data = get_userdata( $auth_id );
if ( in_array( 'subscriber', $auth_data->roles ) ) {
echo 'noindex, nofollow';
} else {
echo 'index, follow';
}
}
```
Then you would just call it like this:
```
<meta name="robots" content="<?php author_nofollow( $curauth ); ?>">
``` |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.