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
|
---|---|---|---|---|---|---|
207,442 |
<p>I want to use a svg as a custom header in WordPress.</p>
<p>I tried two ways:</p>
<h1>First</h1>
<p>I want the user to be able to upload their own svg as a custom header.
So I enabled svg uploads in the functions.php:</p>
<pre><code>function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
</code></pre>
<p>But that does not work because WordPress requires me to crop the image before using it as the custom header image. Even when it is the exact size I defined in the <code>functions.php</code> file.</p>
<h1>Second</h1>
<p>Since there seems to be no way to get svgs as a custom header from a simple user upload, I thought about adding the svg as a default image. This is what I did:</p>
<pre><code>add_theme_support( 'custom-header', array(
'default-image' => get_stylesheet_directory_uri() . '/images/logo.svg',
'width' => 320,
'height' => 320,
'header-selector' => '.site-title a',
'header-text' => false,
) );
</code></pre>
<p>When I set the header image to the default in the backend, it seems to work. The svg is shown as the header image, and I can save it. But when I close the customization panel and look at the frontend, the fallback text is shown. No sign of my settings …</p>
<h1>The worst way</h1>
<p>This leaves me with hard-coding the default logo directly to the theme. Which leaves me with no way to overwrite it from the WordPress backend, rendering the custom header function completely useless.</p>
<p>Any suggestions on how to solve this are much appreciated!</p>
|
[
{
"answer_id": 207786,
"author": "Afterlame",
"author_id": 28865,
"author_profile": "https://wordpress.stackexchange.com/users/28865",
"pm_score": 3,
"selected": true,
"text": "<p>I solved it using the second way.</p>\n\n<p>I found out that you have to register the default image also.\nSo after registering the svg as a default header it displays like it should!</p>\n\n<p>Here is my code:</p>\n\n<pre><code>register_default_headers( array(\n 'kami-logo' => array(\n 'url' => get_stylesheet_directory_uri() . '/images/logo.svg',\n 'thumbnail_url' => get_stylesheet_directory_uri() . '/images/logo.svg',\n 'description' => __( 'Kami Logo', 'fun' )\n )\n));\n\nadd_theme_support( 'custom-header', array(\n 'default-image' => get_stylesheet_directory_uri() . '/images/logo.svg',\n 'width' => 320,\n 'height' => 320,\n 'header-selector' => '.site-title a',\n 'header-text' => false\n) );\n</code></pre>\n"
},
{
"answer_id": 226119,
"author": "Gray Ayer",
"author_id": 18275,
"author_profile": "https://wordpress.stackexchange.com/users/18275",
"pm_score": 0,
"selected": false,
"text": "<p>An alternative to setting up the default image is to provide a button to \"skip cropping\" on the 2nd screen after selecting your svg image, which must be already cropped as the exact size you need.</p>\n\n<p>All you need to do is take that array defined above, where you define the height and width, then add this:</p>\n\n<pre><code> 'flex-width' => true,\n 'flex-height' => true,\n</code></pre>\n\n<p>so for my own custom theme the full snippet is:</p>\n\n<pre><code>function hikeitbaby_custom_header_setup() {\n add_theme_support( 'custom-header', apply_filters( 'hikeitbaby_custom_header_args', array(\n 'default-image' => '',\n 'default-text-color' => '000000',\n 'width' => 190,\n 'height' => 84,\n 'flex-width' => true,\n 'flex-height' => true,\n 'wp-head-callback' => 'hikeitbaby_header_style',\n 'admin-head-callback' => 'hikeitbaby_admin_header_style',\n 'admin-preview-callback' => 'hikeitbaby_admin_header_image',\n ) ) );\n}\nadd_action( 'after_setup_theme', 'hikeitbaby_custom_header_setup' );\n</code></pre>\n\n<p>which will provide you with a screen like this:\n<a href=\"https://i.stack.imgur.com/ak3rh.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/ak3rh.png\" alt=\"What your upload screen will look like\"></a></p>\n"
}
] |
2015/11/03
|
[
"https://wordpress.stackexchange.com/questions/207442",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28865/"
] |
I want to use a svg as a custom header in WordPress.
I tried two ways:
First
=====
I want the user to be able to upload their own svg as a custom header.
So I enabled svg uploads in the functions.php:
```
function cc_mime_types($mimes) {
$mimes['svg'] = 'image/svg+xml';
return $mimes;
}
add_filter('upload_mimes', 'cc_mime_types');
```
But that does not work because WordPress requires me to crop the image before using it as the custom header image. Even when it is the exact size I defined in the `functions.php` file.
Second
======
Since there seems to be no way to get svgs as a custom header from a simple user upload, I thought about adding the svg as a default image. This is what I did:
```
add_theme_support( 'custom-header', array(
'default-image' => get_stylesheet_directory_uri() . '/images/logo.svg',
'width' => 320,
'height' => 320,
'header-selector' => '.site-title a',
'header-text' => false,
) );
```
When I set the header image to the default in the backend, it seems to work. The svg is shown as the header image, and I can save it. But when I close the customization panel and look at the frontend, the fallback text is shown. No sign of my settings …
The worst way
=============
This leaves me with hard-coding the default logo directly to the theme. Which leaves me with no way to overwrite it from the WordPress backend, rendering the custom header function completely useless.
Any suggestions on how to solve this are much appreciated!
|
I solved it using the second way.
I found out that you have to register the default image also.
So after registering the svg as a default header it displays like it should!
Here is my code:
```
register_default_headers( array(
'kami-logo' => array(
'url' => get_stylesheet_directory_uri() . '/images/logo.svg',
'thumbnail_url' => get_stylesheet_directory_uri() . '/images/logo.svg',
'description' => __( 'Kami Logo', 'fun' )
)
));
add_theme_support( 'custom-header', array(
'default-image' => get_stylesheet_directory_uri() . '/images/logo.svg',
'width' => 320,
'height' => 320,
'header-selector' => '.site-title a',
'header-text' => false
) );
```
|
207,450 |
<p>My Woocommerce store has virtual products that don't require shipping. I have disabled the shipping options from the customer on checkout, but now I want to hide it on the backend as well.</p>
<p>When viewing orders on the admin side, I have 3 columns: General Details, Billing Details and Shipping Details. I want to remove the Shipping Details in the third column so that later I can add some custom fields there instead.</p>
<p>I've tried using</p>
<pre class="lang-php prettyprint-override"><code>remove_filter( 'woocommerce_admin_shipping_fields', 'filter_woocommerce_admin_shipping_fields' );
</code></pre>
<p>but that doesn't change anything on the backend.</p>
<p>I could probably do it with some deeply complicated CSS and display:none, but I'd rather just remove it programmatically, like with a remove_filter or something.</p>
|
[
{
"answer_id": 207456,
"author": "Sladix",
"author_id": 27423,
"author_profile": "https://wordpress.stackexchange.com/users/27423",
"pm_score": -1,
"selected": true,
"text": "<p>There is no \"clean\" solution for what you are asking.</p>\n\n<p>However, you can manually delete this block by editing woocommerce/includes/admin/class-wc-meta-box-order-data.php line 315-397.</p>\n"
},
{
"answer_id": 308645,
"author": "user123451",
"author_id": 69128,
"author_profile": "https://wordpress.stackexchange.com/users/69128",
"pm_score": 1,
"selected": false,
"text": "<p>Or try this</p>\n<pre><code>add_action( 'init', 'hide_shipping_details' );\nfunction hide_shipping_details() { \n if( is_admin()) { \n echo '<style> #fieldset-shipping{ display: none !important;} </style>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 381552,
"author": "Alex Albizu",
"author_id": 90842,
"author_profile": "https://wordpress.stackexchange.com/users/90842",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this woocommerce filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>//Hide Shippping and Billing form users backend\nadd_filter( 'woocommerce_customer_meta_fields', 'hide_shipping_billing' );\nfunction hide_shipping_billing( $show_fields ) {\n unset( $show_fields['shipping'] );\n unset( $show_fields['billing'] );\n return $show_fields;\n}\n</code></pre>\n"
}
] |
2015/11/03
|
[
"https://wordpress.stackexchange.com/questions/207450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1118/"
] |
My Woocommerce store has virtual products that don't require shipping. I have disabled the shipping options from the customer on checkout, but now I want to hide it on the backend as well.
When viewing orders on the admin side, I have 3 columns: General Details, Billing Details and Shipping Details. I want to remove the Shipping Details in the third column so that later I can add some custom fields there instead.
I've tried using
```php
remove_filter( 'woocommerce_admin_shipping_fields', 'filter_woocommerce_admin_shipping_fields' );
```
but that doesn't change anything on the backend.
I could probably do it with some deeply complicated CSS and display:none, but I'd rather just remove it programmatically, like with a remove\_filter or something.
|
There is no "clean" solution for what you are asking.
However, you can manually delete this block by editing woocommerce/includes/admin/class-wc-meta-box-order-data.php line 315-397.
|
207,478 |
<p>The URL of our old WordPress MU (it is WPMU, not WordPress Multisite) installation with several blogs has changed. This URL change was updated directly in the DB in the <code>wp_blogs</code> and <code>wp_site</code> tables, and elsewhere. Now the blogs are accessible, but the permalinks of all posts across all blogs are like:</p>
<pre><code>http://example.com/year/month/date/postname
</code></pre>
<p>Instead of the previous:</p>
<pre><code>http://example.com/blogname/year/month/date/postname
</code></pre>
<p>The <code>/blogname/</code> part is missing after the domain and so every blog's post links are broken (they don't load, obviously). When I visit the permalink structure settings page, or look at the permalink stored for each blog in <code>wp_[blogid]_options tables</code>, it has the standard selection of <code>/year/month/date/postname</code>.</p>
<p>Setting the specific blog name as a prefix in the custom permalink definition works for posts, but not for categories/tags. This is not how it was before (so explicitly setting the specific blog name as the prefix is not the solution).</p>
<p>Note:
To make the URL change work, the <code>wp-config.php</code> file had to be changed as follows to add the new URL (without which it redirects to the old one):</p>
<pre><code>//---> NewURL is the complete http and domain (can't post the link here)
define( 'WP_HOME', 'NewURL');
define( 'WP_SITEURL','NewURL');
define( 'NOBLOGREDIRECT', '' );
</code></pre>
<p>Questions: </p>
<ol>
<li>Where in the database, or configuration, is the part about using the
<code>blogname</code> in the links (for each blog) just after the domain name
stored? Is there any other location for this setting?</li>
<li>How do I eliminate the defines for <code>WP_HOME</code> and <code>WP_SITEURL</code> from
<code>wp-config.php</code>? I didn't need these with the previous URL.</li>
<li>The links for some of the blogs still point to the old domain. We don't have any caching plugins installed that could interfere. How can this domain change be done comprehensively?</li>
</ol>
|
[
{
"answer_id": 207456,
"author": "Sladix",
"author_id": 27423,
"author_profile": "https://wordpress.stackexchange.com/users/27423",
"pm_score": -1,
"selected": true,
"text": "<p>There is no \"clean\" solution for what you are asking.</p>\n\n<p>However, you can manually delete this block by editing woocommerce/includes/admin/class-wc-meta-box-order-data.php line 315-397.</p>\n"
},
{
"answer_id": 308645,
"author": "user123451",
"author_id": 69128,
"author_profile": "https://wordpress.stackexchange.com/users/69128",
"pm_score": 1,
"selected": false,
"text": "<p>Or try this</p>\n<pre><code>add_action( 'init', 'hide_shipping_details' );\nfunction hide_shipping_details() { \n if( is_admin()) { \n echo '<style> #fieldset-shipping{ display: none !important;} </style>';\n }\n}\n</code></pre>\n"
},
{
"answer_id": 381552,
"author": "Alex Albizu",
"author_id": 90842,
"author_profile": "https://wordpress.stackexchange.com/users/90842",
"pm_score": 0,
"selected": false,
"text": "<p>You can use this woocommerce filter:</p>\n<pre class=\"lang-php prettyprint-override\"><code>//Hide Shippping and Billing form users backend\nadd_filter( 'woocommerce_customer_meta_fields', 'hide_shipping_billing' );\nfunction hide_shipping_billing( $show_fields ) {\n unset( $show_fields['shipping'] );\n unset( $show_fields['billing'] );\n return $show_fields;\n}\n</code></pre>\n"
}
] |
2015/11/03
|
[
"https://wordpress.stackexchange.com/questions/207478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82947/"
] |
The URL of our old WordPress MU (it is WPMU, not WordPress Multisite) installation with several blogs has changed. This URL change was updated directly in the DB in the `wp_blogs` and `wp_site` tables, and elsewhere. Now the blogs are accessible, but the permalinks of all posts across all blogs are like:
```
http://example.com/year/month/date/postname
```
Instead of the previous:
```
http://example.com/blogname/year/month/date/postname
```
The `/blogname/` part is missing after the domain and so every blog's post links are broken (they don't load, obviously). When I visit the permalink structure settings page, or look at the permalink stored for each blog in `wp_[blogid]_options tables`, it has the standard selection of `/year/month/date/postname`.
Setting the specific blog name as a prefix in the custom permalink definition works for posts, but not for categories/tags. This is not how it was before (so explicitly setting the specific blog name as the prefix is not the solution).
Note:
To make the URL change work, the `wp-config.php` file had to be changed as follows to add the new URL (without which it redirects to the old one):
```
//---> NewURL is the complete http and domain (can't post the link here)
define( 'WP_HOME', 'NewURL');
define( 'WP_SITEURL','NewURL');
define( 'NOBLOGREDIRECT', '' );
```
Questions:
1. Where in the database, or configuration, is the part about using the
`blogname` in the links (for each blog) just after the domain name
stored? Is there any other location for this setting?
2. How do I eliminate the defines for `WP_HOME` and `WP_SITEURL` from
`wp-config.php`? I didn't need these with the previous URL.
3. The links for some of the blogs still point to the old domain. We don't have any caching plugins installed that could interfere. How can this domain change be done comprehensively?
|
There is no "clean" solution for what you are asking.
However, you can manually delete this block by editing woocommerce/includes/admin/class-wc-meta-box-order-data.php line 315-397.
|
207,482 |
<p>Is it possible to add a class <code>loggedout</code> on the body of every page for all logged out users using a function or JS?</p>
<p>My theme already adds a class 'loggedin' for all logged in users. </p>
|
[
{
"answer_id": 207484,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>Presumably your theme is using the <a href=\"https://developer.wordpress.org/reference/functions/body_class/\" rel=\"nofollow\"><code>body_class</code></a> function to output classes. You can <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\">add a filter</a> to remove or add your own classes.</p>\n\n<pre><code>function wpd_logged_out_body_class( $classes ) {\n if( ! is_user_logged_in() ){\n $classes[] = 'loggedout';\n }\n return $classes;\n}\nadd_filter( 'body_class', 'wpd_logged_out_body_class' );\n</code></pre>\n"
},
{
"answer_id": 207486,
"author": "Abad Rahman",
"author_id": 78440,
"author_profile": "https://wordpress.stackexchange.com/users/78440",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\">body class filter</a> and add your own classes. The example below uses <code>is_user_logged_in();</code> function which returns true or false.</p>\n\n<p>This can be added to your themes function.php file. Hope this helps.</p>\n\n<pre><code>add_filter('body_class', 'your_custom_body_classes');\nfunction your_custom_body_classes($classes) {\n if ( !is_user_logged_in() ) {\n $classes[] = 'loggedout';\n return $classes;\n }\n}\n</code></pre>\n"
}
] |
2015/11/03
|
[
"https://wordpress.stackexchange.com/questions/207482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] |
Is it possible to add a class `loggedout` on the body of every page for all logged out users using a function or JS?
My theme already adds a class 'loggedin' for all logged in users.
|
Presumably your theme is using the [`body_class`](https://developer.wordpress.org/reference/functions/body_class/) function to output classes. You can [add a filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class) to remove or add your own classes.
```
function wpd_logged_out_body_class( $classes ) {
if( ! is_user_logged_in() ){
$classes[] = 'loggedout';
}
return $classes;
}
add_filter( 'body_class', 'wpd_logged_out_body_class' );
```
|
207,502 |
<p>I'm building a custom theme for a client and I've been adding stylesheets incorrectly for a while, so I decided to do it the correct way :-).</p>
<p>However, when I add the stylesheet to my <code>functions.php</code> file like so:</p>
<pre><code>wp_enqueue_style('theme-styles', get_template_directory_uri() . '/css/all.css', array(), false , 'all');
</code></pre>
<p>It also is applying to the Wordpress Admin panel. My link colors and fonts change, and there are some layout issues as well.</p>
<p>If I enqueue it inside of a function like this:</p>
<pre><code>function theme_styles(){
wp_enqueue_style('theme-styles', get_template_directory_uri() . '/css/all.css', array(), false , 'all');
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );
</code></pre>
<p>It does not change the admin panel at all, which is good. So my question is, when researching and reading about how to enqueue stylesheets no articles mention adding styles to a function. Scripts, yes, but not styles. What is the correct way to do it to avoid changing my admin styles?</p>
|
[
{
"answer_id": 207484,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": true,
"text": "<p>Presumably your theme is using the <a href=\"https://developer.wordpress.org/reference/functions/body_class/\" rel=\"nofollow\"><code>body_class</code></a> function to output classes. You can <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\">add a filter</a> to remove or add your own classes.</p>\n\n<pre><code>function wpd_logged_out_body_class( $classes ) {\n if( ! is_user_logged_in() ){\n $classes[] = 'loggedout';\n }\n return $classes;\n}\nadd_filter( 'body_class', 'wpd_logged_out_body_class' );\n</code></pre>\n"
},
{
"answer_id": 207486,
"author": "Abad Rahman",
"author_id": 78440,
"author_profile": "https://wordpress.stackexchange.com/users/78440",
"pm_score": 0,
"selected": false,
"text": "<p>You could use the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class\" rel=\"nofollow\">body class filter</a> and add your own classes. The example below uses <code>is_user_logged_in();</code> function which returns true or false.</p>\n\n<p>This can be added to your themes function.php file. Hope this helps.</p>\n\n<pre><code>add_filter('body_class', 'your_custom_body_classes');\nfunction your_custom_body_classes($classes) {\n if ( !is_user_logged_in() ) {\n $classes[] = 'loggedout';\n return $classes;\n }\n}\n</code></pre>\n"
}
] |
2015/11/03
|
[
"https://wordpress.stackexchange.com/questions/207502",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73064/"
] |
I'm building a custom theme for a client and I've been adding stylesheets incorrectly for a while, so I decided to do it the correct way :-).
However, when I add the stylesheet to my `functions.php` file like so:
```
wp_enqueue_style('theme-styles', get_template_directory_uri() . '/css/all.css', array(), false , 'all');
```
It also is applying to the Wordpress Admin panel. My link colors and fonts change, and there are some layout issues as well.
If I enqueue it inside of a function like this:
```
function theme_styles(){
wp_enqueue_style('theme-styles', get_template_directory_uri() . '/css/all.css', array(), false , 'all');
}
add_action( 'wp_enqueue_scripts', 'theme_styles' );
```
It does not change the admin panel at all, which is good. So my question is, when researching and reading about how to enqueue stylesheets no articles mention adding styles to a function. Scripts, yes, but not styles. What is the correct way to do it to avoid changing my admin styles?
|
Presumably your theme is using the [`body_class`](https://developer.wordpress.org/reference/functions/body_class/) function to output classes. You can [add a filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/body_class) to remove or add your own classes.
```
function wpd_logged_out_body_class( $classes ) {
if( ! is_user_logged_in() ){
$classes[] = 'loggedout';
}
return $classes;
}
add_filter( 'body_class', 'wpd_logged_out_body_class' );
```
|
207,604 |
<p>My wordPress database was hacked and all users_names were changed to the same thing. I'd like to write a mySql query to replace all usernames that = "x" to the user_nicename. I'm unsure how to do this - any suggestions?</p>
|
[
{
"answer_id": 207617,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>This should be working:</p>\n\n<p>Be sure that your DB prefix is \"wp_\"</p>\n\n<pre><code>Update wp_users set wp_users.user_login=wp_users.user_nicename where wp_users.user_login=\"x\" \n</code></pre>\n"
},
{
"answer_id": 342499,
"author": "Jonathan Sanchez",
"author_id": 169875,
"author_profile": "https://wordpress.stackexchange.com/users/169875",
"pm_score": 0,
"selected": false,
"text": "<p>To update the <strong>Nickname</strong> use: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_users SET user_nicename = 'new_nick_name' WHERE user_nicename = 'x';\n</code></pre>\n"
}
] |
2015/11/04
|
[
"https://wordpress.stackexchange.com/questions/207604",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83012/"
] |
My wordPress database was hacked and all users\_names were changed to the same thing. I'd like to write a mySql query to replace all usernames that = "x" to the user\_nicename. I'm unsure how to do this - any suggestions?
|
This should be working:
Be sure that your DB prefix is "wp\_"
```
Update wp_users set wp_users.user_login=wp_users.user_nicename where wp_users.user_login="x"
```
|
207,607 |
<p>I would like to set a button on my site that links to a registration page (this registration is off site by a company called Wufoo so it will not be registering on the WordPress site)
if a visitor has not filled out the registration page before.
With Wufoo, I have embed code, so when the user clicks the button on my homepage for the first time, they will be taken to a page "/register-for-live" and on this page will be an embedded form. Upon completion of this form. The user will be given a new link to the page that actually has the live stream.</p>
<p>Trying to figure this out, is there a way that if someone has already filled that form out, the button on the home page takes them to the page that actually has the live-streaming event? Or alternatively, if the button goes to the same page when they get there, WordPress can tell they filled out the form and load the live-stream instead?</p>
|
[
{
"answer_id": 207617,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>This should be working:</p>\n\n<p>Be sure that your DB prefix is \"wp_\"</p>\n\n<pre><code>Update wp_users set wp_users.user_login=wp_users.user_nicename where wp_users.user_login=\"x\" \n</code></pre>\n"
},
{
"answer_id": 342499,
"author": "Jonathan Sanchez",
"author_id": 169875,
"author_profile": "https://wordpress.stackexchange.com/users/169875",
"pm_score": 0,
"selected": false,
"text": "<p>To update the <strong>Nickname</strong> use: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_users SET user_nicename = 'new_nick_name' WHERE user_nicename = 'x';\n</code></pre>\n"
}
] |
2015/11/04
|
[
"https://wordpress.stackexchange.com/questions/207607",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77767/"
] |
I would like to set a button on my site that links to a registration page (this registration is off site by a company called Wufoo so it will not be registering on the WordPress site)
if a visitor has not filled out the registration page before.
With Wufoo, I have embed code, so when the user clicks the button on my homepage for the first time, they will be taken to a page "/register-for-live" and on this page will be an embedded form. Upon completion of this form. The user will be given a new link to the page that actually has the live stream.
Trying to figure this out, is there a way that if someone has already filled that form out, the button on the home page takes them to the page that actually has the live-streaming event? Or alternatively, if the button goes to the same page when they get there, WordPress can tell they filled out the form and load the live-stream instead?
|
This should be working:
Be sure that your DB prefix is "wp\_"
```
Update wp_users set wp_users.user_login=wp_users.user_nicename where wp_users.user_login="x"
```
|
207,612 |
<p>When you visit any wordpress post and click on the "Post Comment" button it just post that blank data to the server and while doing the check at php level it shows this annoying error message to users:</p>
<p><a href="https://i.stack.imgur.com/eDrhk.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eDrhk.jpg" alt="enter image description here"></a></p>
<p>we all have seen it. but what I was wondering is if there is a way to add a "Back to XYZ Article" link in there. Where XYZ Artcile is the post page he way visiting while he accidentally clicked that post comment button.</p>
<p>It happens to many people many times.</p>
<p>Looking forward to your ideas.</p>
|
[
{
"answer_id": 207617,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>This should be working:</p>\n\n<p>Be sure that your DB prefix is \"wp_\"</p>\n\n<pre><code>Update wp_users set wp_users.user_login=wp_users.user_nicename where wp_users.user_login=\"x\" \n</code></pre>\n"
},
{
"answer_id": 342499,
"author": "Jonathan Sanchez",
"author_id": 169875,
"author_profile": "https://wordpress.stackexchange.com/users/169875",
"pm_score": 0,
"selected": false,
"text": "<p>To update the <strong>Nickname</strong> use: </p>\n\n<pre class=\"lang-sql prettyprint-override\"><code>UPDATE wp_users SET user_nicename = 'new_nick_name' WHERE user_nicename = 'x';\n</code></pre>\n"
}
] |
2015/11/04
|
[
"https://wordpress.stackexchange.com/questions/207612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/50584/"
] |
When you visit any wordpress post and click on the "Post Comment" button it just post that blank data to the server and while doing the check at php level it shows this annoying error message to users:
[](https://i.stack.imgur.com/eDrhk.jpg)
we all have seen it. but what I was wondering is if there is a way to add a "Back to XYZ Article" link in there. Where XYZ Artcile is the post page he way visiting while he accidentally clicked that post comment button.
It happens to many people many times.
Looking forward to your ideas.
|
This should be working:
Be sure that your DB prefix is "wp\_"
```
Update wp_users set wp_users.user_login=wp_users.user_nicename where wp_users.user_login="x"
```
|
207,633 |
<p>I have menus set corresponding to a custom field on a page. Ie I have menu1, menu2, and menu3 on three pages under custom field => MenuName. Under functions.php I have:</p>
<pre><code>/* Add Menu Locations */
add_action( 'init', 'register_my_menus' );
function register_my_menus() {
register_nav_menus(
array(
'one-menu' => __('menu1'),
'two-menu' => __('menu2'),
'three-menu' => __('menu3'),
'footerBlocka' => __('Footer Block 1'),
'footerBlockb' => __('Footer Block 2'),
'footerBlockc' => __('Footer Block 3'),
'footerBlockd' => __('Footer Block 5')
)
);
}
</code></pre>
<p>Then in my page template I have:</p>
<pre><code><?php
/* Division */
wp_nav_menu(array(
'menu' => get_post_meta( $post->ID, 'MenuName', true),
'depth' => 2,
'container' => false,
'menu_class' => 'nav navbar-nav'
));
?>
</code></pre>
<p>This works just fine as long as a) the menu exists and b) the menu actually contains menu items. If the menu exists but there are no menu items, it strangely displays a listing of all menu items from all menus on the site. If the menu does not exist, it just shows the next menu listed in functions.php.</p>
<p>So I think in my page template I need to check for the menu and if it exists then print the menu. I have seen a couple of other examples but all I could find were if the theme region exists or a menu exists. Since I'm using <code>'menu' => get_post_meta( $post->ID, 'MenuName', true),</code> to call the menu dynamically, I don't know how to check this dynamic menu before trying to print the menu.</p>
<p>So how do I check the menu that is called from <code>'menu' => get_post_meta( $post->ID, 'MenuName', true),</code> and if it exists and has menu items then print it, if not, print nothing?</p>
<p>EDIT: I tried the following:</p>
<pre><code><?php
/* Division */
wp_nav_menu(array(
'menu' => get_post_meta( $post->ID, 'MenuName', true),
'depth' => 2,
'fallback_cb' => false,
'container' => false,
'menu_class' => 'nav navbar-nav'
));
?>
</code></pre>
<p>This new addition will still render the next menu in line from the functions.php function. So if menu3 does not exist, it prints the footerBlocka menu. I am thinking my goal is to check page ID for MenuName custom field, if it exists, then check whether the menu exists and has links, if true, then print menu, else do nothing. Something like:</p>
<pre><code>$menu = get_post_meta($post->ID, 'MenuName');
if($menu){
if([wp_nav_menu == $menu AND has links]){
wp_nav_menu(array(...));
}
}
</code></pre>
<p>That's the pseudo code I think would be needed but I don't know enough about the WordPress hooks to know what it needs to be.</p>
|
[
{
"answer_id": 207634,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": true,
"text": "<p><code>wp_nav_menu</code> has the argument <code>fallback_cb</code>, which is the function called if a menu doesn't exist. This is set to <code>wp_page_menu</code> by default, which is why you see a list of pages if the menu doesn't exist. If you explicitly set that to <code>false</code>, then nothing will be output if the menu doesn't exist.</p>\n\n<p>EDIT-</p>\n\n<p>Given a menu name, you can load the menu object with <a href=\"http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object\" rel=\"nofollow\"><code>wp_get_nav_menu_object</code></a>. This will tell you if it exists, what its ID is (to pass as <code>menu</code> argument), and how many menu items it has.</p>\n\n<pre><code>$menu_name = get_post_meta( $post->ID, 'MenuName', true );\n$menu = wp_get_nav_menu_object( $menu_name );\nif( is_object( $menu ) ){\n echo 'This menu exists!';\n echo 'This menu has ' . $menu->count . ' menu items.';\n echo 'This menu ID is ' . $menu->term_id . '.';\n} else {\n echo 'A menu with that name doesn\\'t exist';\n}\n</code></pre>\n"
},
{
"answer_id": 385332,
"author": "revive",
"author_id": 8645,
"author_profile": "https://wordpress.stackexchange.com/users/8645",
"pm_score": 2,
"selected": false,
"text": "<p>A simpler approach is to just use:</p>\n<pre><code><?php if(wp_get_nav_menu_items(get_nav_menu_locations()['theme_location'])): ?>\n Do something here IF the menu location you used in the line above has any items\n<?php endif; ?>\n</code></pre>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207633",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45709/"
] |
I have menus set corresponding to a custom field on a page. Ie I have menu1, menu2, and menu3 on three pages under custom field => MenuName. Under functions.php I have:
```
/* Add Menu Locations */
add_action( 'init', 'register_my_menus' );
function register_my_menus() {
register_nav_menus(
array(
'one-menu' => __('menu1'),
'two-menu' => __('menu2'),
'three-menu' => __('menu3'),
'footerBlocka' => __('Footer Block 1'),
'footerBlockb' => __('Footer Block 2'),
'footerBlockc' => __('Footer Block 3'),
'footerBlockd' => __('Footer Block 5')
)
);
}
```
Then in my page template I have:
```
<?php
/* Division */
wp_nav_menu(array(
'menu' => get_post_meta( $post->ID, 'MenuName', true),
'depth' => 2,
'container' => false,
'menu_class' => 'nav navbar-nav'
));
?>
```
This works just fine as long as a) the menu exists and b) the menu actually contains menu items. If the menu exists but there are no menu items, it strangely displays a listing of all menu items from all menus on the site. If the menu does not exist, it just shows the next menu listed in functions.php.
So I think in my page template I need to check for the menu and if it exists then print the menu. I have seen a couple of other examples but all I could find were if the theme region exists or a menu exists. Since I'm using `'menu' => get_post_meta( $post->ID, 'MenuName', true),` to call the menu dynamically, I don't know how to check this dynamic menu before trying to print the menu.
So how do I check the menu that is called from `'menu' => get_post_meta( $post->ID, 'MenuName', true),` and if it exists and has menu items then print it, if not, print nothing?
EDIT: I tried the following:
```
<?php
/* Division */
wp_nav_menu(array(
'menu' => get_post_meta( $post->ID, 'MenuName', true),
'depth' => 2,
'fallback_cb' => false,
'container' => false,
'menu_class' => 'nav navbar-nav'
));
?>
```
This new addition will still render the next menu in line from the functions.php function. So if menu3 does not exist, it prints the footerBlocka menu. I am thinking my goal is to check page ID for MenuName custom field, if it exists, then check whether the menu exists and has links, if true, then print menu, else do nothing. Something like:
```
$menu = get_post_meta($post->ID, 'MenuName');
if($menu){
if([wp_nav_menu == $menu AND has links]){
wp_nav_menu(array(...));
}
}
```
That's the pseudo code I think would be needed but I don't know enough about the WordPress hooks to know what it needs to be.
|
`wp_nav_menu` has the argument `fallback_cb`, which is the function called if a menu doesn't exist. This is set to `wp_page_menu` by default, which is why you see a list of pages if the menu doesn't exist. If you explicitly set that to `false`, then nothing will be output if the menu doesn't exist.
EDIT-
Given a menu name, you can load the menu object with [`wp_get_nav_menu_object`](http://codex.wordpress.org/Function_Reference/wp_get_nav_menu_object). This will tell you if it exists, what its ID is (to pass as `menu` argument), and how many menu items it has.
```
$menu_name = get_post_meta( $post->ID, 'MenuName', true );
$menu = wp_get_nav_menu_object( $menu_name );
if( is_object( $menu ) ){
echo 'This menu exists!';
echo 'This menu has ' . $menu->count . ' menu items.';
echo 'This menu ID is ' . $menu->term_id . '.';
} else {
echo 'A menu with that name doesn\'t exist';
}
```
|
207,641 |
<p>I have added a new tab for profile tab using following code.</p>
<pre><code>add_action('bp_setup_nav', 'mb_bp_profile_menu_posts', 301 );
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'My Posts',
'slug' => 'posts',
'position' => 11,
'default_subnav_slug' => 'published', // We add this submenu item below
'screen_function' => 'mb_author_posts'
)
);
}
</code></pre>
<p>I need to show 5 latest posts from the user in this tab. How to do it? (Currently when click the “My Posts” tab it says 404 error.</p>
|
[
{
"answer_id": 207642,
"author": "Bharat",
"author_id": 82996,
"author_profile": "https://wordpress.stackexchange.com/users/82996",
"pm_score": 0,
"selected": false,
"text": "<p>BuddyPress plugin provides support for this question. This link will help you.\n<a href=\"https://buddypress.org/support/topic/creating-a-page-with-nav-tab-subnav-for-buddypress-profiles/\" rel=\"nofollow\">https://buddypress.org/support/topic/creating-a-page-with-nav-tab-subnav-for-buddypress-profiles/</a></p>\n"
},
{
"answer_id": 207644,
"author": "Subharanjan",
"author_id": 13615,
"author_profile": "https://wordpress.stackexchange.com/users/13615",
"pm_score": 1,
"selected": false,
"text": "<p>Please check the code below. I guess you are facing 404 because it's not getting the <code>slug</code> & the <code>url</code> properly. </p>\n\n<pre><code>add_action( 'bp_setup_nav', 'mb_bp_profile_menu_posts' );\nfunction mb_bp_profile_menu_posts() {\n global $bp;\n bp_core_new_nav_item(\n array(\n 'name' => 'My Posts',\n 'slug' => 'myposts',\n 'position' => 11,\n 'default_subnav_slug' => 'published',\n 'screen_function' => 'mb_author_posts',\n 'parent_url' => bp_displayed_user_domain() . '/myposts/',\n 'parent_slug' => $bp->profile->slug,\n 'default_subnav_slug' => 'myposts',\n )\n );\n}\n\nfunction mb_author_posts() {\n add_action( 'bp_template_title', 'mb_author_posts_title' );\n add_action( 'bp_template_content', 'mb_author_posts_content' );\n bp_core_load_template( 'buddypress/members/single/plugins' );\n}\n\nfunction mb_author_posts_title() {\n echo 'My Posts';\n}\n\nfunction mb_author_posts_content() {\n echo 'Content logic goes here...';\n}\n</code></pre>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207641",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83030/"
] |
I have added a new tab for profile tab using following code.
```
add_action('bp_setup_nav', 'mb_bp_profile_menu_posts', 301 );
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'My Posts',
'slug' => 'posts',
'position' => 11,
'default_subnav_slug' => 'published', // We add this submenu item below
'screen_function' => 'mb_author_posts'
)
);
}
```
I need to show 5 latest posts from the user in this tab. How to do it? (Currently when click the “My Posts” tab it says 404 error.
|
Please check the code below. I guess you are facing 404 because it's not getting the `slug` & the `url` properly.
```
add_action( 'bp_setup_nav', 'mb_bp_profile_menu_posts' );
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'My Posts',
'slug' => 'myposts',
'position' => 11,
'default_subnav_slug' => 'published',
'screen_function' => 'mb_author_posts',
'parent_url' => bp_displayed_user_domain() . '/myposts/',
'parent_slug' => $bp->profile->slug,
'default_subnav_slug' => 'myposts',
)
);
}
function mb_author_posts() {
add_action( 'bp_template_title', 'mb_author_posts_title' );
add_action( 'bp_template_content', 'mb_author_posts_content' );
bp_core_load_template( 'buddypress/members/single/plugins' );
}
function mb_author_posts_title() {
echo 'My Posts';
}
function mb_author_posts_content() {
echo 'Content logic goes here...';
}
```
|
207,681 |
<p>One of the major problems I have with a big site is the number of templates. So I figure I could call an optional footer within the page using a shortcode.</p>
<pre><code>function trainer_footer( ){
get_footer('rctrainer');
}
add_shortcode( 'trainer', 'trainer_footer' );
</code></pre>
<p>This works.</p>
<p>But there are two questions;</p>
<ol>
<li><p>the content of sidebar-trainer appears at the top of the content rather than in the place of the shortcode. Why?</p></li>
<li><p>I've read it's not a good idea to write PHP into a shortcode like this. Why?</p></li>
</ol>
|
[
{
"answer_id": 207642,
"author": "Bharat",
"author_id": 82996,
"author_profile": "https://wordpress.stackexchange.com/users/82996",
"pm_score": 0,
"selected": false,
"text": "<p>BuddyPress plugin provides support for this question. This link will help you.\n<a href=\"https://buddypress.org/support/topic/creating-a-page-with-nav-tab-subnav-for-buddypress-profiles/\" rel=\"nofollow\">https://buddypress.org/support/topic/creating-a-page-with-nav-tab-subnav-for-buddypress-profiles/</a></p>\n"
},
{
"answer_id": 207644,
"author": "Subharanjan",
"author_id": 13615,
"author_profile": "https://wordpress.stackexchange.com/users/13615",
"pm_score": 1,
"selected": false,
"text": "<p>Please check the code below. I guess you are facing 404 because it's not getting the <code>slug</code> & the <code>url</code> properly. </p>\n\n<pre><code>add_action( 'bp_setup_nav', 'mb_bp_profile_menu_posts' );\nfunction mb_bp_profile_menu_posts() {\n global $bp;\n bp_core_new_nav_item(\n array(\n 'name' => 'My Posts',\n 'slug' => 'myposts',\n 'position' => 11,\n 'default_subnav_slug' => 'published',\n 'screen_function' => 'mb_author_posts',\n 'parent_url' => bp_displayed_user_domain() . '/myposts/',\n 'parent_slug' => $bp->profile->slug,\n 'default_subnav_slug' => 'myposts',\n )\n );\n}\n\nfunction mb_author_posts() {\n add_action( 'bp_template_title', 'mb_author_posts_title' );\n add_action( 'bp_template_content', 'mb_author_posts_content' );\n bp_core_load_template( 'buddypress/members/single/plugins' );\n}\n\nfunction mb_author_posts_title() {\n echo 'My Posts';\n}\n\nfunction mb_author_posts_content() {\n echo 'Content logic goes here...';\n}\n</code></pre>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207681",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57686/"
] |
One of the major problems I have with a big site is the number of templates. So I figure I could call an optional footer within the page using a shortcode.
```
function trainer_footer( ){
get_footer('rctrainer');
}
add_shortcode( 'trainer', 'trainer_footer' );
```
This works.
But there are two questions;
1. the content of sidebar-trainer appears at the top of the content rather than in the place of the shortcode. Why?
2. I've read it's not a good idea to write PHP into a shortcode like this. Why?
|
Please check the code below. I guess you are facing 404 because it's not getting the `slug` & the `url` properly.
```
add_action( 'bp_setup_nav', 'mb_bp_profile_menu_posts' );
function mb_bp_profile_menu_posts() {
global $bp;
bp_core_new_nav_item(
array(
'name' => 'My Posts',
'slug' => 'myposts',
'position' => 11,
'default_subnav_slug' => 'published',
'screen_function' => 'mb_author_posts',
'parent_url' => bp_displayed_user_domain() . '/myposts/',
'parent_slug' => $bp->profile->slug,
'default_subnav_slug' => 'myposts',
)
);
}
function mb_author_posts() {
add_action( 'bp_template_title', 'mb_author_posts_title' );
add_action( 'bp_template_content', 'mb_author_posts_content' );
bp_core_load_template( 'buddypress/members/single/plugins' );
}
function mb_author_posts_title() {
echo 'My Posts';
}
function mb_author_posts_content() {
echo 'Content logic goes here...';
}
```
|
207,683 |
<p>I have the following problem. I got a plugin that is huge due to all the data needed. The data is all the countries and cities in the world and also a maxmind.mmdb database.</p>
<h2>1 - Issue</h2>
<p>Currently I got everything packed in the plugin which makes a 20mb plugin and that creates a problem for users with limited upload size which force them to unzip and manually upload by FTP the whole plugin.</p>
<h2>2 - Issue</h2>
<p>To load all the cities I got 6 csv files that I load upon activation using the following code:</p>
<pre><code>if ($wpdb->get_var( "SHOW TABLES LIKE '{$city_table_name}'") != $city_table_name) {
dbDelta( $city_table );
for ( $i = 1; $i <= 6; $i ++ ) {
$csv_file = dirname( __FILE__ ) . '/data/cities' . $i . '.csv';
$load_data = "LOAD DATA LOCAL INFILE '{$csv_file}' INTO TABLE `{$wpdb->base_prefix}geot_cities` CHARACTER SET UTF8 FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n' ( `country_code` , `city`);";
$wpdb->query( $load_data );
}
}
</code></pre>
<p>This works on almost every hosting but it fails in some of them like for example WPEngine.</p>
<h3>Posible solution</h3>
<p>So I was thinking that maybe to fix both issues at once I could upload all the data to my amazon instance and once the plugin is active the user will download and install all data by simple clicking a button.</p>
<h3>Questions</h3>
<ul>
<li>Is this something viable or doable using WordPress functions or I will face other hosting incompatibilities. Anyone have experiences using something like this?</li>
<li>In case this is doable what would be the best way to store the data ? Because instead of loading the csv I will have to replace that for some kind of insert data query in order to make it more compatible.</li>
</ul>
<p>I hope someone could throw some light at this. Thanks!</p>
|
[
{
"answer_id": 207689,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 2,
"selected": false,
"text": "<p>I can see two options:</p>\n\n<ul>\n<li>You create an API with the city info and make the plugin use the API</li>\n<li>You create separate add-ons for your plugin, like one for each CSV</li>\n</ul>\n"
},
{
"answer_id": 208768,
"author": "pwbred",
"author_id": 6154,
"author_profile": "https://wordpress.stackexchange.com/users/6154",
"pm_score": 1,
"selected": true,
"text": "<p>To directly answer your questions:</p>\n\n<p>Your proposed solution is indeed viable, just make sure your CDN solution (Amazon S3 for example) is configured to accept both secure (http) and insecure (https) connections.</p>\n\n<p>As far as your next question, CSV is by nature a great way to store a representation of a table. Another alternative (without seeing an example set of data that you are working with) is XML. That might be a good fit as well because it allows one-to-many relationships. </p>\n\n<p>JSON might also fit well to ease the transition between text and a database.</p>\n\n<p>That being said though, the hands-down best solution is to build an API service yourself and allow your plugin to communicate with it.</p>\n"
},
{
"answer_id": 208882,
"author": "Szektor",
"author_id": 83734,
"author_profile": "https://wordpress.stackexchange.com/users/83734",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Some ideas:</strong></p>\n\n<ol>\n<li>ENCLOSED BY '\\\"'</li>\n</ol>\n\n<p>It is not a must have in this case. <strong>Without</strong> \" chars you can reduce your .csv file sizes. This might help alone.</p>\n\n<ol start=\"2\">\n<li>Using SQLite can be another option. If zip codes are numbers only it may save a smaller db file than a .csv file but I haven't tested this. It does worth a try. And you can use that as a database. WP doesn't support it by default so you have to write or use other functions.</li>\n<li>Use <a href=\"http://codex.wordpress.org/HTTP_API\" rel=\"nofollow\">HTTP API functions</a>! These functions are also used by the plugin manager. So if it works there you can also use them here.</li>\n</ol>\n\n<p><strong>Storing data:</strong> my best bet (if LOAD DATA is not allowed) is to store zipped JSON or INSERT statements on your Amazon instance.</p>\n\n<p>You can also check disabled functions on <a href=\"https://wpengine.com/support/what-functions-are-enabled-on-the-server-level/\" rel=\"nofollow\">WP Engine here.</a></p>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207683",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/4130/"
] |
I have the following problem. I got a plugin that is huge due to all the data needed. The data is all the countries and cities in the world and also a maxmind.mmdb database.
1 - Issue
---------
Currently I got everything packed in the plugin which makes a 20mb plugin and that creates a problem for users with limited upload size which force them to unzip and manually upload by FTP the whole plugin.
2 - Issue
---------
To load all the cities I got 6 csv files that I load upon activation using the following code:
```
if ($wpdb->get_var( "SHOW TABLES LIKE '{$city_table_name}'") != $city_table_name) {
dbDelta( $city_table );
for ( $i = 1; $i <= 6; $i ++ ) {
$csv_file = dirname( __FILE__ ) . '/data/cities' . $i . '.csv';
$load_data = "LOAD DATA LOCAL INFILE '{$csv_file}' INTO TABLE `{$wpdb->base_prefix}geot_cities` CHARACTER SET UTF8 FIELDS TERMINATED BY ',' ENCLOSED BY '\"' ESCAPED BY '\\\' LINES TERMINATED BY '\\n' ( `country_code` , `city`);";
$wpdb->query( $load_data );
}
}
```
This works on almost every hosting but it fails in some of them like for example WPEngine.
### Posible solution
So I was thinking that maybe to fix both issues at once I could upload all the data to my amazon instance and once the plugin is active the user will download and install all data by simple clicking a button.
### Questions
* Is this something viable or doable using WordPress functions or I will face other hosting incompatibilities. Anyone have experiences using something like this?
* In case this is doable what would be the best way to store the data ? Because instead of loading the csv I will have to replace that for some kind of insert data query in order to make it more compatible.
I hope someone could throw some light at this. Thanks!
|
To directly answer your questions:
Your proposed solution is indeed viable, just make sure your CDN solution (Amazon S3 for example) is configured to accept both secure (http) and insecure (https) connections.
As far as your next question, CSV is by nature a great way to store a representation of a table. Another alternative (without seeing an example set of data that you are working with) is XML. That might be a good fit as well because it allows one-to-many relationships.
JSON might also fit well to ease the transition between text and a database.
That being said though, the hands-down best solution is to build an API service yourself and allow your plugin to communicate with it.
|
207,712 |
<p>I have a cpt called "auto" and i make a frontend form to create new post with "pending" status.
After the post submission i would receive an email with a notification of the new post.</p>
<pre><code>function newpost_notify() {
$mailadmin = '[email protected]';
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: xxx <[email protected]>' . "\r\n";
$message = 'There\'s a new post.';
wp_mail( $mailadmin, $subject, $message, $headers );
}
add_action( 'publish_post', 'newpost_notify', 10, 2 );
</code></pre>
<p>This is my code..but i didn't receive any email.</p>
<p>I would know if there's a difference between a "new post" and a "publish post", because i read something about the post status transition.</p>
<p>Thank you</p>
|
[
{
"answer_id": 207689,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 2,
"selected": false,
"text": "<p>I can see two options:</p>\n\n<ul>\n<li>You create an API with the city info and make the plugin use the API</li>\n<li>You create separate add-ons for your plugin, like one for each CSV</li>\n</ul>\n"
},
{
"answer_id": 208768,
"author": "pwbred",
"author_id": 6154,
"author_profile": "https://wordpress.stackexchange.com/users/6154",
"pm_score": 1,
"selected": true,
"text": "<p>To directly answer your questions:</p>\n\n<p>Your proposed solution is indeed viable, just make sure your CDN solution (Amazon S3 for example) is configured to accept both secure (http) and insecure (https) connections.</p>\n\n<p>As far as your next question, CSV is by nature a great way to store a representation of a table. Another alternative (without seeing an example set of data that you are working with) is XML. That might be a good fit as well because it allows one-to-many relationships. </p>\n\n<p>JSON might also fit well to ease the transition between text and a database.</p>\n\n<p>That being said though, the hands-down best solution is to build an API service yourself and allow your plugin to communicate with it.</p>\n"
},
{
"answer_id": 208882,
"author": "Szektor",
"author_id": 83734,
"author_profile": "https://wordpress.stackexchange.com/users/83734",
"pm_score": 0,
"selected": false,
"text": "<p><strong>Some ideas:</strong></p>\n\n<ol>\n<li>ENCLOSED BY '\\\"'</li>\n</ol>\n\n<p>It is not a must have in this case. <strong>Without</strong> \" chars you can reduce your .csv file sizes. This might help alone.</p>\n\n<ol start=\"2\">\n<li>Using SQLite can be another option. If zip codes are numbers only it may save a smaller db file than a .csv file but I haven't tested this. It does worth a try. And you can use that as a database. WP doesn't support it by default so you have to write or use other functions.</li>\n<li>Use <a href=\"http://codex.wordpress.org/HTTP_API\" rel=\"nofollow\">HTTP API functions</a>! These functions are also used by the plugin manager. So if it works there you can also use them here.</li>\n</ol>\n\n<p><strong>Storing data:</strong> my best bet (if LOAD DATA is not allowed) is to store zipped JSON or INSERT statements on your Amazon instance.</p>\n\n<p>You can also check disabled functions on <a href=\"https://wpengine.com/support/what-functions-are-enabled-on-the-server-level/\" rel=\"nofollow\">WP Engine here.</a></p>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207712",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71371/"
] |
I have a cpt called "auto" and i make a frontend form to create new post with "pending" status.
After the post submission i would receive an email with a notification of the new post.
```
function newpost_notify() {
$mailadmin = '[email protected]';
$subject = 'Subject';
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=UTF-8' . "\r\n";
$headers .= 'From: xxx <[email protected]>' . "\r\n";
$message = 'There\'s a new post.';
wp_mail( $mailadmin, $subject, $message, $headers );
}
add_action( 'publish_post', 'newpost_notify', 10, 2 );
```
This is my code..but i didn't receive any email.
I would know if there's a difference between a "new post" and a "publish post", because i read something about the post status transition.
Thank you
|
To directly answer your questions:
Your proposed solution is indeed viable, just make sure your CDN solution (Amazon S3 for example) is configured to accept both secure (http) and insecure (https) connections.
As far as your next question, CSV is by nature a great way to store a representation of a table. Another alternative (without seeing an example set of data that you are working with) is XML. That might be a good fit as well because it allows one-to-many relationships.
JSON might also fit well to ease the transition between text and a database.
That being said though, the hands-down best solution is to build an API service yourself and allow your plugin to communicate with it.
|
207,715 |
<p>I need to add a shortcode into one of the PHP files (replacing a search bar code that is hardcoded into the header PHP file). How do I add a shortcode to the header PHP file?</p>
<p>This is the code that I am looking at:</p>
<pre><code><?php if ( (is_front_page()) && (of_get_option('g_search_box_id') == 'yes') ) { ?>
<div class="search-form-wrap hidden-phone" data-motopress-type="static" data-motopress-static-file="static/static-search.php">
<?php get_template_part("static/static-search"); ?>
</div>
<?php } ?>
</code></pre>
<p>And I need to remove the search-form-wrap with a different shortcode search form (for mls).</p>
<p>Here is the shortcode I have to deal with:</p>
<p>[idx_search link="###########" detailed_search="off" destination="local" user_sorting="off" location_search="on" property_type_enabled="on" theme="hori_round_light" orientation="horizontal" width="730" title_font="Arial" field_font="Arial" border_style="rounded" widget_drop_shadow="off" background_color="#ffffff" title_text_color="#000000" field_text_color="#545454" detailed_search_text_color="#234c7a" submit_button_shine="shine" submit_button_background="#59cfeb" submit_button_text_color="#000000"]</p>
|
[
{
"answer_id": 207720,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>Use <a href=\"https://developer.wordpress.org/reference/functions/do_shortcode/\" rel=\"nofollow\"><code>do_shortcode</code></a> to output a shortcode in your template.</p>\n\n<pre><code>echo do_shortcode( '[theshortcode]' );\n</code></pre>\n"
},
{
"answer_id": 207721,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 3,
"selected": false,
"text": "<p>In general, inserting and executing shortcodes directly into templates files is not good idea and it is not what shortcodes are intented for. Instead, you should use the shortcode callback just like any other <a href=\"https://codex.wordpress.org/Template_Tags\" rel=\"noreferrer\">PHP function or template tag</a>.</p>\n\n<p>For example, let's imaging this shortcode:</p>\n\n<pre><code>add_shortcode('someshortocode', 'someshortocode_callback');\nfunction someshortocode_callback( $atts = array(), $content = null ) {\n\n $output = \"Echo!!!\";\n\n return $output;\n\n}\n</code></pre>\n\n<p>Then, instead of doing this:</p>\n\n<pre><code>echo do_shortcode( '[someshortocode]' );\n</code></pre>\n\n<p>You should do this:</p>\n\n<pre><code>echo someshortocode_callback();\n</code></pre>\n\n<p>Obviously, to use the shortcode callback as template tag, the shortcode must be coded in a way it allows this use, so it may be not possible (although I've never found a shortcode that don't allow the use of the callback directly, it may exist). In this case, and only in this case, I would use <code>do_shortcode( '[someshortcode]' )</code> (I've never would use it really).</p>\n\n<p>Note that shortcodes are PHP placeholders to be used where PHP code can not be inserted, that is why it has no sense for me to use them in PHP scripts.</p>\n"
},
{
"answer_id": 240982,
"author": "Charles Xavier",
"author_id": 101716,
"author_profile": "https://wordpress.stackexchange.com/users/101716",
"pm_score": 1,
"selected": false,
"text": "<p>You can use this. </p>\n\n<pre><code><?php echo do_shortcode('[Shortcode_goes_here]') ?>\n</code></pre>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207715",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83069/"
] |
I need to add a shortcode into one of the PHP files (replacing a search bar code that is hardcoded into the header PHP file). How do I add a shortcode to the header PHP file?
This is the code that I am looking at:
```
<?php if ( (is_front_page()) && (of_get_option('g_search_box_id') == 'yes') ) { ?>
<div class="search-form-wrap hidden-phone" data-motopress-type="static" data-motopress-static-file="static/static-search.php">
<?php get_template_part("static/static-search"); ?>
</div>
<?php } ?>
```
And I need to remove the search-form-wrap with a different shortcode search form (for mls).
Here is the shortcode I have to deal with:
[idx\_search link="###########" detailed\_search="off" destination="local" user\_sorting="off" location\_search="on" property\_type\_enabled="on" theme="hori\_round\_light" orientation="horizontal" width="730" title\_font="Arial" field\_font="Arial" border\_style="rounded" widget\_drop\_shadow="off" background\_color="#ffffff" title\_text\_color="#000000" field\_text\_color="#545454" detailed\_search\_text\_color="#234c7a" submit\_button\_shine="shine" submit\_button\_background="#59cfeb" submit\_button\_text\_color="#000000"]
|
In general, inserting and executing shortcodes directly into templates files is not good idea and it is not what shortcodes are intented for. Instead, you should use the shortcode callback just like any other [PHP function or template tag](https://codex.wordpress.org/Template_Tags).
For example, let's imaging this shortcode:
```
add_shortcode('someshortocode', 'someshortocode_callback');
function someshortocode_callback( $atts = array(), $content = null ) {
$output = "Echo!!!";
return $output;
}
```
Then, instead of doing this:
```
echo do_shortcode( '[someshortocode]' );
```
You should do this:
```
echo someshortocode_callback();
```
Obviously, to use the shortcode callback as template tag, the shortcode must be coded in a way it allows this use, so it may be not possible (although I've never found a shortcode that don't allow the use of the callback directly, it may exist). In this case, and only in this case, I would use `do_shortcode( '[someshortcode]' )` (I've never would use it really).
Note that shortcodes are PHP placeholders to be used where PHP code can not be inserted, that is why it has no sense for me to use them in PHP scripts.
|
207,725 |
<p>I need a way of taking a variable from a plugin's settings and write it to a small key file located in the plugin's directory. The entire contents of the key file is this: </p>
<pre><code><?php
$transaction_key = "npo7d3A0d2hhTYF5w9uo";
?>
</code></pre>
<p>I've tried to use <code>file_put_contents</code>, but I can't get it to work. Anyone know how to correctly do this?</p>
|
[
{
"answer_id": 207729,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>It is impossible especially if you also need to keep the key in secret. Just use the DB.</p>\n"
},
{
"answer_id": 207735,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 0,
"selected": false,
"text": "<p>Yes it works. You are just not passing the right file path.</p>\n\n<pre><code> $base = dirname(__FILE__); // That's the directory path\n $filename = 'key.php';\n $fileUrl = $base . '/' . $filename;\n $data = '<?php $transaction_key=\"'. get_option('option_name') . '\"?>';\n file_put_contents($fileUrl, $data);\n</code></pre>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207725",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83075/"
] |
I need a way of taking a variable from a plugin's settings and write it to a small key file located in the plugin's directory. The entire contents of the key file is this:
```
<?php
$transaction_key = "npo7d3A0d2hhTYF5w9uo";
?>
```
I've tried to use `file_put_contents`, but I can't get it to work. Anyone know how to correctly do this?
|
It is impossible especially if you also need to keep the key in secret. Just use the DB.
|
207,726 |
<p>I want to get the first blockquote from the post (even if the user writes only one, or more than one) in the Quote Post Format, in order to show it in the archive Loop. For example:</p>
<pre><code>$quote = has_post_format( 'quote' );
if ( $quote ) {
if ( *the post has no quotes* ){
// Don't show anything
} else {
// Show the blockquote from the post (if there's only one),
// or the first one (if there are more than 1)
}
}
</code></pre>
<p>Is there something like this?</p>
|
[
{
"answer_id": 207741,
"author": "MarketHubb",
"author_id": 59093,
"author_profile": "https://wordpress.stackexchange.com/users/59093",
"pm_score": 0,
"selected": false,
"text": "<p>Try something like this:</p>\n\n<pre><code><?php \n // Check is post has quote format \n if (has_post_format('quote', $post->ID)) {\n $content = trim(get_the_content());\n // Make sure content isn't empty\n if (!$content == \"\") {\n // Take each new line and put into an array (for multiple quotes)\n $quote_array = explode( \"\\n\", $content);\n // Get the first quote and do something with it\n $first_quote = array_shift( $quote_array );\n echo $first_quote;\n }\n }\n?>\n</code></pre>\n"
},
{
"answer_id": 207890,
"author": "Marga López",
"author_id": 82894,
"author_profile": "https://wordpress.stackexchange.com/users/82894",
"pm_score": 3,
"selected": true,
"text": "<p>I finally found a solution that works. In case you need it, here it is:</p>\n\n<pre><code><?php\nif (has_post_format('quote', $post->ID)) {\n $content = trim(get_the_content());\n // Take the first quote from the content\n $quote_string = extract_from_string('<blockquote>', '</blockquote>', $content);\n // Make sure there's a quote on the content\n if (!$quote_string == \"\") {\n // Get the first quote and show it on the Loop\n echo $quote_string;\n } else {\n // If not, show nothing\n }\n}\n?>\n</code></pre>\n"
}
] |
2015/11/05
|
[
"https://wordpress.stackexchange.com/questions/207726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82894/"
] |
I want to get the first blockquote from the post (even if the user writes only one, or more than one) in the Quote Post Format, in order to show it in the archive Loop. For example:
```
$quote = has_post_format( 'quote' );
if ( $quote ) {
if ( *the post has no quotes* ){
// Don't show anything
} else {
// Show the blockquote from the post (if there's only one),
// or the first one (if there are more than 1)
}
}
```
Is there something like this?
|
I finally found a solution that works. In case you need it, here it is:
```
<?php
if (has_post_format('quote', $post->ID)) {
$content = trim(get_the_content());
// Take the first quote from the content
$quote_string = extract_from_string('<blockquote>', '</blockquote>', $content);
// Make sure there's a quote on the content
if (!$quote_string == "") {
// Get the first quote and show it on the Loop
echo $quote_string;
} else {
// If not, show nothing
}
}
?>
```
|
207,751 |
<p>I've looked for plugins and couldn't find anything and I believe this should be a core feature.</p>
<p><strong>The Problem:</strong></p>
<p>The current methodology for replacing a custom link, or any menu link is by doing the following process:</p>
<ol>
<li>Remove old menu link</li>
<li>Insert new link</li>
<li>Drag new link from end of list</li>
<li>Drop new link in desired location</li>
<li>repeat steps 3 and 4 until you hit the jackpot</li>
<li>Enter menu options again (css, label etc)</li>
</ol>
<p><strong>Why is it a problem</strong></p>
<p>It is very inefficient, especially when: (a) dealing with huge menus (b) menus with many sublevels (c) replacing many menu items which have custom options</p>
<p><strong>Solution requirements</strong></p>
<ol>
<li>Retains Menu position / hierarchy</li>
<li>Retains Options (css class, label, title)</li>
<li>Choose from Pages / Posts / Categories etc</li>
</ol>
<p><strong>Demonstration</strong></p>
<p><a href="https://i.stack.imgur.com/UdEkd.png" rel="noreferrer"><img src="https://i.stack.imgur.com/UdEkd.png" alt="http://puu.sh/laSEi/81b0d41705.png"></a></p>
<p><strong>Should be that simple:</strong></p>
<p><a href="https://i.stack.imgur.com/PzCsq.gif" rel="noreferrer"><img src="https://i.stack.imgur.com/PzCsq.gif" alt="enter image description here"></a></p>
<p>Other possible ideas are duplicating / "add child link to this"/ or even adding new links to top of list instead of bottom.</p>
<p>Any feedback appreciated.</p>
|
[
{
"answer_id": 208881,
"author": "cbos",
"author_id": 83730,
"author_profile": "https://wordpress.stackexchange.com/users/83730",
"pm_score": 1,
"selected": false,
"text": "<p>Although this does not directly answer the question, the code on which it is based provides the functionality. The code set is:</p>\n\n<pre>function install_menus() {\n require_once dirname( __FILE__) . '/data.php';\n $menus = get_menus_data();\n if ( ! empty ( $menus ) ) foreach ( $menus as $menu ) {\n if ( $menu['build'] ) {\n $menu_id = create_nav_menu( $menu );\n add_items_to_menu( $menu_id, $menu['slug'], $menu['items'] );\n }\n }\n}\n\nfunction create_nav_menu( $menu ) {\n if ( $exists = wp_get_nav_menu_object( $menu['name'] ) ) {\n $menu_id = $exists -> term_id;\n if ( empty ( $menu_id ) ) {\n $menu_id = wp_create_nav_menu( $menu['name'] );\n } \n }\n else {\n $menu_id = wp_create_nav_menu( $menu['name'] );\n }\n return $menu_id;\n}\nfunction add_items_to_menu( $menu_id, $slug, $items ) {\n if ( $items ) foreach ( $items as $item ) {\n if ( $item['build'] ) {\n $slug = ( $item['title'] == 'Home' ) ? 'home' : $item['slug'];\n if ( ! menu_item_exists( $slug, $menu_id ) ) {\n wp_update_nav_menu_item( $menu_id, 0, array (\n 'menu-item-title' => __( $item['title'] ),\n 'menu-item-classes' => '',\n 'menu-item-url' => home_url( $item['slug'] . '/' ), \n 'menu-item-status' => 'publish'\n ) );\n }\n }\n }\n}\nfunction menu_item_exists( $slug, $menu_id ) {\n $args = array(\n 'order' => 'ASC',\n 'orderby' => 'menu_order',\n 'post_type' => 'nav_menu_item',\n 'post_status' => 'publish',\n 'output' => ARRAY_A,\n 'output_key' => 'menu_order',\n 'nopaging' => true,\n 'update_post_term_cache' => false ); \n\n $existing = wp_get_nav_menu_items( $menu_id, $args );\n $found = false;\n foreach ( $existing as $exists ) {\n if( strpos( $exists->post_name, $slug ) !== FALSE ) { //pretty good search (not exact).\n $found = true;\n break;\n }\n\n }\n return $found;\n}</pre>\n\n<p>and the data file is:</p>\n\n<pre>function get_menus_data() {\n $items = array ( \n array ( \n 'name' => 'Main Menu', 'slug' => 'main-menu', 'build' => 1, \n 'items' => array (\n array ( 'title' => 'Home', 'slug' => '', 'build' => 1 ), //slug should be empty\n array ( 'title' => 'Blog', 'slug' => 'blog', 'build' => 1 ),\n array ( 'title' => 'About', 'slug' => 'about', 'build' => 1 ),\n array ( 'title' => 'Contact', 'slug' => 'contact', 'build' => 1 ),\n ),\n ),\n array ( \n 'name' => 'Secondary Menu', 'slug' => 'secondary-menu', 'build' => 0,\n 'items' => array (\n array ( 'title' => 'Home', 'slug' => '', 'build' => 1 ),\n array ( 'title' => 'Blog', 'slug' => 'blog', 'build' => 1 ),\n array ( 'title' => 'About', 'slug' => 'about', 'build' => 1 ),\n array ( 'title' => 'Contact', 'slug' => 'contact', 'build' => 1 ),\n ),\n ),\n array ( \n 'name' => 'Footer Menu', 'slug' => 'footer-menu', 'build' => 1,\n 'items' => array (\n array ( 'title' => 'Terms', 'slug' => 'terms', 'build' => 1 ),\n array ( 'title' => 'Privacy', 'slug' => 'privacy', 'build' => 1 ),\n array ( 'title' => 'Contact', 'slug' => 'contact', 'build' => 1 ),\n ),\n ) \n );\n return $items;\n}</pre>\n\n<p>An interface would need to be built on top of this to allow for the selection that is asked, but this code is working and tested.</p>\n"
},
{
"answer_id": 209589,
"author": "Tim Plummer",
"author_id": 15236,
"author_profile": "https://wordpress.stackexchange.com/users/15236",
"pm_score": 1,
"selected": false,
"text": "<p>I'm not sure this is an answer, but more a discussion point.</p>\n\n<p>Has anyone ever considered Advanced Custom Fields for building WP menus? I've done this a couple of times, and it allows me to build out a custom structure along with custom menu-item attributes and build out the HTML for the menu without a complicated walker that would be needed with default WP menus.</p>\n\n<p><a href=\"https://i.stack.imgur.com/8TszI.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/8TszI.png\" alt=\"enter image description here\"></a></p>\n\n<p><strong>ACF</strong></p>\n\n<pre><code>if( function_exists('acf_add_local_field_group') ):\n\nacf_add_local_field_group(array (\n 'key' => 'group_56532ec144a4b',\n 'title' => 'Menu',\n 'fields' => array (\n array (\n 'key' => 'field_5653338918f43',\n 'label' => 'Menus',\n 'name' => 'menus',\n 'type' => 'flexible_content',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => 0,\n 'wrapper' => array (\n 'width' => '',\n 'class' => '',\n 'id' => '',\n ),\n 'button_label' => 'Add Menu',\n 'min' => '',\n 'max' => '',\n 'layouts' => array (\n array (\n 'key' => '56533396b10bc',\n 'name' => 'menu',\n 'label' => 'Menu',\n 'display' => 'block',\n 'sub_fields' => array (\n array (\n 'key' => 'field_56533fc6f25e7',\n 'label' => 'Menu Name',\n 'name' => 'menu__name',\n 'type' => 'text',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => 0,\n 'wrapper' => array (\n 'width' => '',\n 'class' => '',\n 'id' => '',\n ),\n 'default_value' => '',\n 'placeholder' => '',\n 'prepend' => '',\n 'append' => '',\n 'maxlength' => '',\n 'readonly' => 0,\n 'disabled' => 0,\n ),\n array (\n 'key' => 'field_56532ec718f40',\n 'label' => 'Menu Items',\n 'name' => 'menu__items',\n 'type' => 'flexible_content',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => 0,\n 'wrapper' => array (\n 'width' => '',\n 'class' => '',\n 'id' => '',\n ),\n 'button_label' => 'Add Menu Item',\n 'min' => '',\n 'max' => '',\n 'layouts' => array (\n array (\n 'key' => '56532eee6ef81',\n 'name' => 'menuItem',\n 'label' => 'Menu Item',\n 'display' => 'block',\n 'sub_fields' => array (\n array (\n 'key' => 'field_56532f0418f41',\n 'label' => 'Label',\n 'name' => 'menuITem__label',\n 'type' => 'text',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => 0,\n 'wrapper' => array (\n 'width' => 50,\n 'class' => '',\n 'id' => '',\n ),\n 'default_value' => '',\n 'placeholder' => '',\n 'prepend' => '',\n 'append' => '',\n 'maxlength' => '',\n 'readonly' => 0,\n 'disabled' => 0,\n ),\n array (\n 'key' => 'field_565333d218f45',\n 'label' => 'Class',\n 'name' => 'menuItem__class',\n 'type' => 'text',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => 0,\n 'wrapper' => array (\n 'width' => 50,\n 'class' => '',\n 'id' => '',\n ),\n 'default_value' => '',\n 'placeholder' => '',\n 'prepend' => '',\n 'append' => '',\n 'maxlength' => '',\n 'readonly' => 0,\n 'disabled' => 0,\n ),\n array (\n 'key' => 'field_565342ef11b29',\n 'label' => 'Link Type',\n 'name' => 'menuItem__type',\n 'type' => 'radio',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => 0,\n 'wrapper' => array (\n 'width' => 25,\n 'class' => '',\n 'id' => '',\n ),\n 'choices' => array (\n 'page' => 'Page',\n 'cat' => 'Category',\n 'url' => 'URL',\n 'cust' => 'Custom',\n ),\n 'other_choice' => 0,\n 'save_other_choice' => 0,\n 'default_value' => '',\n 'layout' => 'vertical',\n ),\n array (\n 'key' => 'field_56532f2d18f42',\n 'label' => 'Page',\n 'name' => 'menuItem__page',\n 'type' => 'page_link',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => array (\n array (\n array (\n 'field' => 'field_565342ef11b29',\n 'operator' => '==',\n 'value' => 'page',\n ),\n ),\n ),\n 'wrapper' => array (\n 'width' => 75,\n 'class' => '',\n 'id' => '',\n ),\n 'post_type' => array (\n ),\n 'taxonomy' => array (\n ),\n 'allow_null' => 0,\n 'multiple' => 0,\n ),\n array (\n 'key' => 'field_5653434f11b2a',\n 'label' => 'Category',\n 'name' => 'menuItem__cat',\n 'type' => 'taxonomy',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => array (\n array (\n array (\n 'field' => 'field_565342ef11b29',\n 'operator' => '==',\n 'value' => 'cat',\n ),\n ),\n ),\n 'wrapper' => array (\n 'width' => 75,\n 'class' => '',\n 'id' => '',\n ),\n 'taxonomy' => 'category',\n 'field_type' => 'select',\n 'allow_null' => 0,\n 'add_term' => 1,\n 'save_terms' => 0,\n 'load_terms' => 0,\n 'return_format' => 'id',\n 'multiple' => 0,\n ),\n array (\n 'key' => 'field_5653439311b2c',\n 'label' => 'Custom',\n 'name' => 'menuItem__cstm',\n 'type' => 'text',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => array (\n array (\n array (\n 'field' => 'field_565342ef11b29',\n 'operator' => '==',\n 'value' => 'cust',\n ),\n ),\n ),\n 'wrapper' => array (\n 'width' => 75,\n 'class' => '',\n 'id' => '',\n ),\n 'default_value' => '',\n 'placeholder' => '',\n 'prepend' => '',\n 'append' => '',\n 'maxlength' => '',\n 'readonly' => 0,\n 'disabled' => 0,\n ),\n array (\n 'key' => 'field_5653437011b2b',\n 'label' => 'URL',\n 'name' => 'menuItem__url',\n 'type' => 'url',\n 'instructions' => '',\n 'required' => 0,\n 'conditional_logic' => array (\n array (\n array (\n 'field' => 'field_565342ef11b29',\n 'operator' => '==',\n 'value' => 'url',\n ),\n ),\n ),\n 'wrapper' => array (\n 'width' => 75,\n 'class' => '',\n 'id' => '',\n ),\n 'default_value' => '',\n 'placeholder' => '',\n ),\n ),\n 'min' => '',\n 'max' => '',\n ),\n ),\n ),\n ),\n 'min' => '',\n 'max' => '',\n ),\n ),\n ),\n ),\n 'location' => array (\n array (\n array (\n 'param' => 'options_page',\n 'operator' => '==',\n 'value' => 'acf-options-theme-options',\n ),\n ),\n ),\n 'menu_order' => 0,\n 'position' => 'normal',\n 'style' => 'default',\n 'label_placement' => 'top',\n 'instruction_placement' => 'label',\n 'hide_on_screen' => '',\n 'active' => 1,\n 'description' => '',\n));\n\nendif;\n</code></pre>\n\n<p><strong>UX</strong></p>\n\n<pre><code>function acfMenu($name) {\n if( function_exists('get_field') ) :\n $getMenus = get_field('menus', 'option');\n foreach($getMenus as $menuData) : \n if( $menuData['menu__name'] == $name ) : \n // Do stuff to build your menu\n endif;\n endforeach;\n endif;\n}\n</code></pre>\n\n<p>This is just a quick sample, but with the options that ACF offers, you could tack all kinds of stuff onto a menu item and then code out the UI at will.</p>\n\n<p>In application to your specific question, one could in turn apply conditional selections to what type of link you're supplying (see attached image). ACF allows many different parameters such as page links, category links, or straight URLs. A conditional selection of these items would allow one to change the type of the menu item without erasing classes or other attributes.</p>\n"
},
{
"answer_id": 211000,
"author": "garth",
"author_id": 80997,
"author_profile": "https://wordpress.stackexchange.com/users/80997",
"pm_score": 0,
"selected": false,
"text": "<p>This may help define the right approach.</p>\n\n<p>The dummy-down philosophy behind WP drives the way that they have setup menus in the first place, and is just one of the reasons why WP can be a poor choice as the framework for handling a site with large amounts of oft changing content.</p>\n\n<p>In trying to make content management as dummy proof as possible it locks it into particular paradigms which often creates extra work, often for no good reason. You can't save menu templates, nor duplicate existing menus, nor safely store menu re-usable menu items without experiencing loss of config.</p>\n\n<p>I like your suggestion which would be a good alternative to the native menu formats they provide, as it's a good middle ground between the dummy-proof approach while still offering a lot more flexiblity and speed of deployment. And I'd add a sort parameter as an alternative to the annoying drag and drop process which can create so much fiddling around.</p>\n\n<p>However, while I would want the menus management in WP to be changed, pushing too far down this path is against the core WP philosophy and might mean that it is no longer catering to the lowest common denominator which is largely the reason for the popularity of WP.</p>\n"
}
] |
2015/11/06
|
[
"https://wordpress.stackexchange.com/questions/207751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82468/"
] |
I've looked for plugins and couldn't find anything and I believe this should be a core feature.
**The Problem:**
The current methodology for replacing a custom link, or any menu link is by doing the following process:
1. Remove old menu link
2. Insert new link
3. Drag new link from end of list
4. Drop new link in desired location
5. repeat steps 3 and 4 until you hit the jackpot
6. Enter menu options again (css, label etc)
**Why is it a problem**
It is very inefficient, especially when: (a) dealing with huge menus (b) menus with many sublevels (c) replacing many menu items which have custom options
**Solution requirements**
1. Retains Menu position / hierarchy
2. Retains Options (css class, label, title)
3. Choose from Pages / Posts / Categories etc
**Demonstration**
[](https://i.stack.imgur.com/UdEkd.png)
**Should be that simple:**
[](https://i.stack.imgur.com/PzCsq.gif)
Other possible ideas are duplicating / "add child link to this"/ or even adding new links to top of list instead of bottom.
Any feedback appreciated.
|
Although this does not directly answer the question, the code on which it is based provides the functionality. The code set is:
```
function install_menus() {
require_once dirname( __FILE__) . '/data.php';
$menus = get_menus_data();
if ( ! empty ( $menus ) ) foreach ( $menus as $menu ) {
if ( $menu['build'] ) {
$menu_id = create_nav_menu( $menu );
add_items_to_menu( $menu_id, $menu['slug'], $menu['items'] );
}
}
}
function create_nav_menu( $menu ) {
if ( $exists = wp_get_nav_menu_object( $menu['name'] ) ) {
$menu_id = $exists -> term_id;
if ( empty ( $menu_id ) ) {
$menu_id = wp_create_nav_menu( $menu['name'] );
}
}
else {
$menu_id = wp_create_nav_menu( $menu['name'] );
}
return $menu_id;
}
function add_items_to_menu( $menu_id, $slug, $items ) {
if ( $items ) foreach ( $items as $item ) {
if ( $item['build'] ) {
$slug = ( $item['title'] == 'Home' ) ? 'home' : $item['slug'];
if ( ! menu_item_exists( $slug, $menu_id ) ) {
wp_update_nav_menu_item( $menu_id, 0, array (
'menu-item-title' => __( $item['title'] ),
'menu-item-classes' => '',
'menu-item-url' => home_url( $item['slug'] . '/' ),
'menu-item-status' => 'publish'
) );
}
}
}
}
function menu_item_exists( $slug, $menu_id ) {
$args = array(
'order' => 'ASC',
'orderby' => 'menu_order',
'post_type' => 'nav_menu_item',
'post_status' => 'publish',
'output' => ARRAY_A,
'output_key' => 'menu_order',
'nopaging' => true,
'update_post_term_cache' => false );
$existing = wp_get_nav_menu_items( $menu_id, $args );
$found = false;
foreach ( $existing as $exists ) {
if( strpos( $exists->post_name, $slug ) !== FALSE ) { //pretty good search (not exact).
$found = true;
break;
}
}
return $found;
}
```
and the data file is:
```
function get_menus_data() {
$items = array (
array (
'name' => 'Main Menu', 'slug' => 'main-menu', 'build' => 1,
'items' => array (
array ( 'title' => 'Home', 'slug' => '', 'build' => 1 ), //slug should be empty
array ( 'title' => 'Blog', 'slug' => 'blog', 'build' => 1 ),
array ( 'title' => 'About', 'slug' => 'about', 'build' => 1 ),
array ( 'title' => 'Contact', 'slug' => 'contact', 'build' => 1 ),
),
),
array (
'name' => 'Secondary Menu', 'slug' => 'secondary-menu', 'build' => 0,
'items' => array (
array ( 'title' => 'Home', 'slug' => '', 'build' => 1 ),
array ( 'title' => 'Blog', 'slug' => 'blog', 'build' => 1 ),
array ( 'title' => 'About', 'slug' => 'about', 'build' => 1 ),
array ( 'title' => 'Contact', 'slug' => 'contact', 'build' => 1 ),
),
),
array (
'name' => 'Footer Menu', 'slug' => 'footer-menu', 'build' => 1,
'items' => array (
array ( 'title' => 'Terms', 'slug' => 'terms', 'build' => 1 ),
array ( 'title' => 'Privacy', 'slug' => 'privacy', 'build' => 1 ),
array ( 'title' => 'Contact', 'slug' => 'contact', 'build' => 1 ),
),
)
);
return $items;
}
```
An interface would need to be built on top of this to allow for the selection that is asked, but this code is working and tested.
|
207,816 |
<p>I'm building a site for ordering food online. It's not a shop (visitors will not be able to pay online, just to order for delivery). My initial idea was to define all the food and drink items as custom post types. But I haven't figured out how to set up product variations. For example, a pizza may be small, medium or large, and depending on the size selected, its price is different. Or a salad may have Italian or French dressing, which also influences its price.</p>
<p>Can this be achieved using WP custom post types?</p>
|
[
{
"answer_id": 207819,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, this is exactly the purpose for custom post types. To handle your product variations, several custom fields can be added, specific to each post type.</p>\n\n<p>A common solution for the custom fields is Elliot Condon's excellent Advanced Custom Fields plugin. No plugin is necessary for this, however, and there are other options out there for easy custom field management.</p>\n\n<p>Writing the code for your own metaboxes (to enclose groups of product options) and other headaches are managed by the plugin instead.</p>\n"
},
{
"answer_id": 207822,
"author": "hfarazm",
"author_id": 83136,
"author_profile": "https://wordpress.stackexchange.com/users/83136",
"pm_score": 1,
"selected": false,
"text": "<p>Use it can be done using CUSTOM META BOX. Add following to function.php:</p>\n\n<pre><code>/* Adds pizza size meta box to the post editing screen \n******************************************************/\nfunction prfx_custom_meta() {\n add_meta_box( 'prfx_meta', __( 'Pizza Size', 'prfx-textdomain' ), 'prfx_meta_callback', 'post' );\n}\nadd_action( 'add_meta_boxes', 'prfx_custom_meta' );\n\n\n/* Outputs the content of the meta box \n**************************************/\nfunction prfx_meta_callback( $post ) {\n wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );\n $prfx_stored_meta = get_post_meta( $post->ID );\n ?>\n\n <p>\n <label for=\"meta-text\" class=\"prfx-row-title\" style=\"clear:both; float: left; width:100%;\" ><?php _e( '<b>Enter Pizza Size</b> ', 'prfx-textdomain' )?></label>\n <textarea name=\"meta-text\" id=\"meta-text\" maxlength=\"250\" style=\"clear:left; float: left; width: 100%;\" rows=\"4\" cols=\"90\"><?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?></textarea>\n <p>You can write like: Available in: 21\" and 16\" only</p>\n </p>\n\n <?php\n}\n\n\n/* Saves the custom meta input \n******************************/\nfunction prfx_meta_save( $post_id ) {\n\n // Checks save status\n $is_autosave = wp_is_post_autosave( $post_id );\n $is_revision = wp_is_post_revision( $post_id );\n $is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';\n\n // Exits script depending on save status\n if ( $is_autosave || $is_revision || !$is_valid_nonce ) {\n return;\n }\n\n // Checks for input and sanitizes/saves if needed\n if( isset( $_POST[ 'meta-text' ] ) ) {\n update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );\n }\n\n}\nadd_action( 'save_post', 'prfx_meta_save' );\n</code></pre>\n\n<p>And then goto piece of code where you would like to show pizza sizes e.g I want to show it on single.php, so I will add the following code after description:</p>\n\n<pre><code><?php $meta_value = get_post_meta( get_the_ID(), 'meta-text', true );\n\n// Checks and displays the retrieved value\nif( !empty( $meta_value ) )\n echo $meta_value;\nelse \n echo \"No pizza sizes available\";\n?>\n</code></pre>\n"
}
] |
2015/11/06
|
[
"https://wordpress.stackexchange.com/questions/207816",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/20681/"
] |
I'm building a site for ordering food online. It's not a shop (visitors will not be able to pay online, just to order for delivery). My initial idea was to define all the food and drink items as custom post types. But I haven't figured out how to set up product variations. For example, a pizza may be small, medium or large, and depending on the size selected, its price is different. Or a salad may have Italian or French dressing, which also influences its price.
Can this be achieved using WP custom post types?
|
Use it can be done using CUSTOM META BOX. Add following to function.php:
```
/* Adds pizza size meta box to the post editing screen
******************************************************/
function prfx_custom_meta() {
add_meta_box( 'prfx_meta', __( 'Pizza Size', 'prfx-textdomain' ), 'prfx_meta_callback', 'post' );
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
/* Outputs the content of the meta box
**************************************/
function prfx_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="meta-text" class="prfx-row-title" style="clear:both; float: left; width:100%;" ><?php _e( '<b>Enter Pizza Size</b> ', 'prfx-textdomain' )?></label>
<textarea name="meta-text" id="meta-text" maxlength="250" style="clear:left; float: left; width: 100%;" rows="4" cols="90"><?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?></textarea>
<p>You can write like: Available in: 21" and 16" only</p>
</p>
<?php
}
/* Saves the custom meta input
******************************/
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
```
And then goto piece of code where you would like to show pizza sizes e.g I want to show it on single.php, so I will add the following code after description:
```
<?php $meta_value = get_post_meta( get_the_ID(), 'meta-text', true );
// Checks and displays the retrieved value
if( !empty( $meta_value ) )
echo $meta_value;
else
echo "No pizza sizes available";
?>
```
|
207,845 |
<p>I'm trying to get post meta to be updated/replaced with $wpdb and running into issues. I have working SQL, but cannot get it work when coding it up for my WP plugin. </p>
<p><strong>Extra note:</strong></p>
<p>The post meta being saved is for example is Twitter follower count that I need the number to be saved to the database so I can export the result in a table</p>
<p>Here is my working SQL. When I put this in PHPmyAdmin it updates all post meta:</p>
<pre><code>INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT wp_posts.ID, 'agency_details_seo_grade', 'test'
FROM wp_posts
WHERE wp_posts.post_status = 'publish' and wp_posts.post_type = 'agencies'";
</code></pre>
<p>Here is my failed attempt putting it in WP. Nothing happened as a result (no meta changed and no error message):</p>
<pre><code>// Failed attempt to put into functions.php
function add_grading_post_meta() {
global $wpdb;
$wpdb->prepare("SELECT ID,'','test2'", $wpdb->query("INSERT INTO wp_postmeta ($post_id,meta_key,meta_value)"));
}
</code></pre>
<p>I'm trying to get this working so I can use it with wp_cron before the next step of using it with WP scheduling functions. Any help would be appreciated for this first step, cracking a lot of hours on this project learning PHP.</p>
<p><strong>Edit:</strong></p>
<p>Here's 1 more version I tried with no success. I changed it due to @czerspalace comment, coding provided by old Stack Exchange post.</p>
<pre><code>function add_grading_post_meta() {
global $wpdb;
$twitter_followers = 'agency_details_twitter_followers';
$twitter_count = 'test3';
$sql = "INSERT INTO $wpdb->wp_postmeta (post_id,meta_key,meta_value) VALUES (%d,'%s',%s) ON DUPLICATE KEY UPDATE meta_value = %s";
$sql = $wpdb->prepare($sql,$post_id,$twitter_followers,$twitter_count);
$wpdb->query($sql);
}
</code></pre>
|
[
{
"answer_id": 207819,
"author": "jdm2112",
"author_id": 45202,
"author_profile": "https://wordpress.stackexchange.com/users/45202",
"pm_score": 0,
"selected": false,
"text": "<p>Yes, this is exactly the purpose for custom post types. To handle your product variations, several custom fields can be added, specific to each post type.</p>\n\n<p>A common solution for the custom fields is Elliot Condon's excellent Advanced Custom Fields plugin. No plugin is necessary for this, however, and there are other options out there for easy custom field management.</p>\n\n<p>Writing the code for your own metaboxes (to enclose groups of product options) and other headaches are managed by the plugin instead.</p>\n"
},
{
"answer_id": 207822,
"author": "hfarazm",
"author_id": 83136,
"author_profile": "https://wordpress.stackexchange.com/users/83136",
"pm_score": 1,
"selected": false,
"text": "<p>Use it can be done using CUSTOM META BOX. Add following to function.php:</p>\n\n<pre><code>/* Adds pizza size meta box to the post editing screen \n******************************************************/\nfunction prfx_custom_meta() {\n add_meta_box( 'prfx_meta', __( 'Pizza Size', 'prfx-textdomain' ), 'prfx_meta_callback', 'post' );\n}\nadd_action( 'add_meta_boxes', 'prfx_custom_meta' );\n\n\n/* Outputs the content of the meta box \n**************************************/\nfunction prfx_meta_callback( $post ) {\n wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );\n $prfx_stored_meta = get_post_meta( $post->ID );\n ?>\n\n <p>\n <label for=\"meta-text\" class=\"prfx-row-title\" style=\"clear:both; float: left; width:100%;\" ><?php _e( '<b>Enter Pizza Size</b> ', 'prfx-textdomain' )?></label>\n <textarea name=\"meta-text\" id=\"meta-text\" maxlength=\"250\" style=\"clear:left; float: left; width: 100%;\" rows=\"4\" cols=\"90\"><?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?></textarea>\n <p>You can write like: Available in: 21\" and 16\" only</p>\n </p>\n\n <?php\n}\n\n\n/* Saves the custom meta input \n******************************/\nfunction prfx_meta_save( $post_id ) {\n\n // Checks save status\n $is_autosave = wp_is_post_autosave( $post_id );\n $is_revision = wp_is_post_revision( $post_id );\n $is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';\n\n // Exits script depending on save status\n if ( $is_autosave || $is_revision || !$is_valid_nonce ) {\n return;\n }\n\n // Checks for input and sanitizes/saves if needed\n if( isset( $_POST[ 'meta-text' ] ) ) {\n update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );\n }\n\n}\nadd_action( 'save_post', 'prfx_meta_save' );\n</code></pre>\n\n<p>And then goto piece of code where you would like to show pizza sizes e.g I want to show it on single.php, so I will add the following code after description:</p>\n\n<pre><code><?php $meta_value = get_post_meta( get_the_ID(), 'meta-text', true );\n\n// Checks and displays the retrieved value\nif( !empty( $meta_value ) )\n echo $meta_value;\nelse \n echo \"No pizza sizes available\";\n?>\n</code></pre>\n"
}
] |
2015/11/06
|
[
"https://wordpress.stackexchange.com/questions/207845",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/66224/"
] |
I'm trying to get post meta to be updated/replaced with $wpdb and running into issues. I have working SQL, but cannot get it work when coding it up for my WP plugin.
**Extra note:**
The post meta being saved is for example is Twitter follower count that I need the number to be saved to the database so I can export the result in a table
Here is my working SQL. When I put this in PHPmyAdmin it updates all post meta:
```
INSERT INTO wp_postmeta (post_id, meta_key, meta_value)
SELECT wp_posts.ID, 'agency_details_seo_grade', 'test'
FROM wp_posts
WHERE wp_posts.post_status = 'publish' and wp_posts.post_type = 'agencies'";
```
Here is my failed attempt putting it in WP. Nothing happened as a result (no meta changed and no error message):
```
// Failed attempt to put into functions.php
function add_grading_post_meta() {
global $wpdb;
$wpdb->prepare("SELECT ID,'','test2'", $wpdb->query("INSERT INTO wp_postmeta ($post_id,meta_key,meta_value)"));
}
```
I'm trying to get this working so I can use it with wp\_cron before the next step of using it with WP scheduling functions. Any help would be appreciated for this first step, cracking a lot of hours on this project learning PHP.
**Edit:**
Here's 1 more version I tried with no success. I changed it due to @czerspalace comment, coding provided by old Stack Exchange post.
```
function add_grading_post_meta() {
global $wpdb;
$twitter_followers = 'agency_details_twitter_followers';
$twitter_count = 'test3';
$sql = "INSERT INTO $wpdb->wp_postmeta (post_id,meta_key,meta_value) VALUES (%d,'%s',%s) ON DUPLICATE KEY UPDATE meta_value = %s";
$sql = $wpdb->prepare($sql,$post_id,$twitter_followers,$twitter_count);
$wpdb->query($sql);
}
```
|
Use it can be done using CUSTOM META BOX. Add following to function.php:
```
/* Adds pizza size meta box to the post editing screen
******************************************************/
function prfx_custom_meta() {
add_meta_box( 'prfx_meta', __( 'Pizza Size', 'prfx-textdomain' ), 'prfx_meta_callback', 'post' );
}
add_action( 'add_meta_boxes', 'prfx_custom_meta' );
/* Outputs the content of the meta box
**************************************/
function prfx_meta_callback( $post ) {
wp_nonce_field( basename( __FILE__ ), 'prfx_nonce' );
$prfx_stored_meta = get_post_meta( $post->ID );
?>
<p>
<label for="meta-text" class="prfx-row-title" style="clear:both; float: left; width:100%;" ><?php _e( '<b>Enter Pizza Size</b> ', 'prfx-textdomain' )?></label>
<textarea name="meta-text" id="meta-text" maxlength="250" style="clear:left; float: left; width: 100%;" rows="4" cols="90"><?php if ( isset ( $prfx_stored_meta['meta-text'] ) ) echo $prfx_stored_meta['meta-text'][0]; ?></textarea>
<p>You can write like: Available in: 21" and 16" only</p>
</p>
<?php
}
/* Saves the custom meta input
******************************/
function prfx_meta_save( $post_id ) {
// Checks save status
$is_autosave = wp_is_post_autosave( $post_id );
$is_revision = wp_is_post_revision( $post_id );
$is_valid_nonce = ( isset( $_POST[ 'prfx_nonce' ] ) && wp_verify_nonce( $_POST[ 'prfx_nonce' ], basename( __FILE__ ) ) ) ? 'true' : 'false';
// Exits script depending on save status
if ( $is_autosave || $is_revision || !$is_valid_nonce ) {
return;
}
// Checks for input and sanitizes/saves if needed
if( isset( $_POST[ 'meta-text' ] ) ) {
update_post_meta( $post_id, 'meta-text', sanitize_text_field( $_POST[ 'meta-text' ] ) );
}
}
add_action( 'save_post', 'prfx_meta_save' );
```
And then goto piece of code where you would like to show pizza sizes e.g I want to show it on single.php, so I will add the following code after description:
```
<?php $meta_value = get_post_meta( get_the_ID(), 'meta-text', true );
// Checks and displays the retrieved value
if( !empty( $meta_value ) )
echo $meta_value;
else
echo "No pizza sizes available";
?>
```
|
207,895 |
<p>I want to get the URL of a page's "featured image", as I want to use the page's featured image as the background image for the banner at the top of the page. The background image for the banner changes according to what page I'm on, as they will have different featured images. </p>
|
[
{
"answer_id": 207898,
"author": "kittsville",
"author_id": 52428,
"author_profile": "https://wordpress.stackexchange.com/users/52428",
"pm_score": 3,
"selected": false,
"text": "<p>Adapted from <a href=\"https://wordpress.org/support/topic/retrieveing-featured-image-url\" rel=\"noreferrer\">this thread</a> on the WP forums:</p>\n\n<pre><code><?php if (has_post_thumbnail( $post->ID ) ): ?>\n<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail'); ?>\n<style>\n #banner-id {\n background-image: url('<?php echo $image[0]; ?>');\n }\n</style>\n<?php endif; ?>\n</code></pre>\n\n<p>Add this to your single page template, after <code>the_post()</code>. I'd reccommend having a default header image so that if the page doesn't have a featured image it falls back to using that.</p>\n\n<p><code>'single-post-thumbnail'</code> can instead be an array with the ideal header dimentions, such as <code>array(600, 30)</code>.</p>\n"
},
{
"answer_id": 207900,
"author": "Abhik",
"author_id": 26991,
"author_profile": "https://wordpress.stackexchange.com/users/26991",
"pm_score": 2,
"selected": false,
"text": "<p>Since you are using the image outside of the loop, you need to get the ID of the post first. Then use that to get the featured image's URL. </p>\n\n<pre><code>function wpse207895_featured_image() {\n //Execute if singular\n if ( is_singular() ) {\n\n $id = get_queried_object_id ();\n\n // Check if the post/page has featured image\n if ( has_post_thumbnail( $id ) ) {\n\n // Change thumbnail size, but I guess full is what you'll need\n $image = wp_get_attachment_image_src( get_post_thumbnail_id( $id ), 'full' );\n\n $url = $image[0];\n\n } else {\n\n //Set a default image if Featured Image isn't set\n $url = '';\n\n }\n }\n\n return $url;\n}\n</code></pre>\n\n<p>Now you can use this to echo the featured image's url at header.</p>\n\n<p><code><?php echo wpse207895_featured_image();?></code> </p>\n\n<p>For eaxmple: </p>\n\n<pre><code><header class=\"site-header\" style=\"background-image: url('<?php echo wpse207895_featured_image();?>');\">\n ....\n ....\n</header>\n</code></pre>\n"
},
{
"answer_id": 366638,
"author": "Michiel J Otto",
"author_id": 185539,
"author_profile": "https://wordpress.stackexchange.com/users/185539",
"pm_score": 0,
"selected": false,
"text": "<p><strong>I found this worked for me</strong></p>\n\n<p>You can use the page's Feature Image as a background image for an element like this --></p>\n\n<pre><code><?php $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full' );?>\n<article class=\"banner\" style=\"background-image(url('<?php echo $backgroundImg[0]; ?>'))\"></article>\n</code></pre>\n\n<p>But I would recommend using it in an image element, in the 'src' attribute --></p>\n\n<pre><code><article class=\"banner\">\n <?php $backgroundImg = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'full' );?>\n <img src=\"<?php echo $backgroundImg[0]; ?>\" alt=\"Feature Image\">\n</article>\n</code></pre>\n\n<p>and set the image size to fit whatever size the banner element is.</p>\n"
}
] |
2015/11/07
|
[
"https://wordpress.stackexchange.com/questions/207895",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83182/"
] |
I want to get the URL of a page's "featured image", as I want to use the page's featured image as the background image for the banner at the top of the page. The background image for the banner changes according to what page I'm on, as they will have different featured images.
|
Adapted from [this thread](https://wordpress.org/support/topic/retrieveing-featured-image-url) on the WP forums:
```
<?php if (has_post_thumbnail( $post->ID ) ): ?>
<?php $image = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID), 'single-post-thumbnail'); ?>
<style>
#banner-id {
background-image: url('<?php echo $image[0]; ?>');
}
</style>
<?php endif; ?>
```
Add this to your single page template, after `the_post()`. I'd reccommend having a default header image so that if the page doesn't have a featured image it falls back to using that.
`'single-post-thumbnail'` can instead be an array with the ideal header dimentions, such as `array(600, 30)`.
|
207,924 |
<p>Im trying to only show a taxonomy for the <code>editor</code> and <code>administrator</code> but I haven't found a solution on SO or here. The closest thing I was able to find was <a href="https://stackoverflow.com/questions/4249694/how-do-i-remove-a-taxonomy-from-wordpress">How do I remove a taxonomy from Wordpress?</a> on SO. What is the proper way to only allow the taxonomy for the <code>editor</code> and <code>administrator</code>?</p>
<pre><code>// remove from everyone that isn't admin or editor
function taxonomy_for_admin_and_editor_only() {
if ( !current_user_can( 'administrator' ) || !current_user_can( 'editor' ) ) {
register_taxonomy( 'foobar', array() );
}
}
add_action( 'init' , 'taxonomy_for_admin_and_editor_only' );
</code></pre>
<p>I've tried <code>add_action( 'admin' , 'taxonomy_for_admin_and_editor_only' );</code> with no luck either.</p>
|
[
{
"answer_id": 207933,
"author": "mrbobbybryant",
"author_id": 64953,
"author_profile": "https://wordpress.stackexchange.com/users/64953",
"pm_score": 4,
"selected": true,
"text": "<p>When registering your taxonomy you can pass an argument called <strong>capabilities</strong>. Simply passing capabiities that only admins and editors have. </p>\n\n<pre><code>$args = array(\n 'capabilities' => array( 'manage_options', 'edit_posts' )\n);\nregister_taxonomy( 'foobar', 'post', $args ); \n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Roles_and_Capabilities#Editor\" rel=\"noreferrer\">https://codex.wordpress.org/Roles_and_Capabilities#Editor</a></p>\n"
},
{
"answer_id": 207934,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>You want to use the <code>admin_init</code> hook:</p>\n\n<pre><code>add_action( 'admin_init' , 'taxonomy_for_admin_and_editor_only' );\n</code></pre>\n"
},
{
"answer_id": 207997,
"author": "user9447",
"author_id": 25271,
"author_profile": "https://wordpress.stackexchange.com/users/25271",
"pm_score": 2,
"selected": false,
"text": "<p>I never played with roles before so this was a fun learning experience. I'm leaving this because I've spent a lot of time researching this area and this might help the next person. I know my question is in regards to the taxonomy but I was confused with the issue so I wanted to test from a CPT level. The correct hook was <code>admin_init</code> however it was still removing the taxonomy from the <code>administrator</code> and <code>editor</code> and I did not want that. </p>\n\n<p>Before the answer I did run across \"<a href=\"https://wordpress.stackexchange.com/questions/28782/possible-to-hide-custom-post-type-ui-menu-from-specific-user-roles\">Possible to hide Custom Post Type UI/Menu from specific User Roles?</a>\" but when I use a function like:</p>\n\n<pre><code>// hide from Contributors\nfunction no_see_from_contributors() {\n if ( current_user_can( 'contributor' ) ) :\n remove_menu_page( 'edit.php' ); // Posts\n remove_menu_page( 'tools.php' ); // Tools\n remove_menu_page( 'edit-comments.php' ); // Comments\n endif;\n}\nadd_action( 'admin_menu', 'no_see_from_contributors' );\n</code></pre>\n\n<p>create a test Contributor account, even though it is not visible from the menu a Contributor can still access this area by adding <code>edit.php</code>, <code>tools.php</code> or <code>edit-comments.php</code> in the URL. I'm going to test for a solution to prevent this and make an edit with a solution if I find one.</p>\n\n<p>Further research after this led to \"<a href=\"https://wordpress.stackexchange.com/questions/54959/restrict-custom-post-type-to-only-site-administrator-role\">Restrict custom post type to only site administrator role</a>\" and \"<a href=\"https://wordpress.stackexchange.com/questions/7290/remove-custom-post-type-menu-for-non-administrator-users\">Remove Custom Post Type menu for non-administrator users</a>\" which were great reads. To learn more about capabilities you can visit <a href=\"http://codex.wordpress.org/Function_Reference/register_post_type\" rel=\"nofollow noreferrer\">Codex: register post type</a> and scroll down to <code>capability_type</code>. </p>\n\n<p>You can reference the codex for the <a href=\"http://codex.wordpress.org/Roles_and_Capabilities#Administrator\" rel=\"nofollow noreferrer\">Administrator</a> and <a href=\"http://codex.wordpress.org/Roles_and_Capabilities#Editor\" rel=\"nofollow noreferrer\">Editor</a> on what roles to use in the array. </p>\n\n<p>Final taxonomy:</p>\n\n<pre><code>function something_taxonomy() {\n $labels = array(\n 'name' => _x( 'Taxonomies', 'Taxonomy General Name', 'theme' ),\n 'singular_name' => _x( 'Taxonomy', 'Taxonomy Singular Name', 'theme' ),\n 'menu_name' => __( 'Taxonomy', 'theme' ),\n 'all_items' => __( 'All Items', 'theme' ),\n 'parent_item' => __( 'Parent Item', 'theme' ),\n 'parent_item_colon' => __( 'Parent Item:', 'theme' ),\n 'new_item_name' => __( 'New Item Name', 'theme' ),\n 'add_new_item' => __( 'Add New Item', 'theme' ),\n 'edit_item' => __( 'Edit Item', 'theme' ),\n 'update_item' => __( 'Update Item', 'theme' ),\n 'view_item' => __( 'View Item', 'theme' ),\n 'separate_items_with_commas' => __( 'Separate items with commas', 'theme' ),\n 'add_or_remove_items' => __( 'Add or remove items', 'theme' ),\n 'choose_from_most_used' => __( 'Choose from the most used', 'theme' ),\n 'popular_items' => __( 'Popular Items', 'theme' ),\n 'search_items' => __( 'Search Items', 'theme' ),\n 'not_found' => __( 'Not Found', 'theme' ),\n 'items_list' => __( 'Items list', 'theme' ),\n 'items_list_navigation' => __( 'Items list navigation', 'theme' ),\n );\n $capabilities = array(\n 'edit_post' => 'edit_pages',\n 'read_post' => 'edit_pages',\n 'delete_post' => 'edit_pages',\n 'edit_posts' => 'edit_pages',\n 'edit_others_posts' => 'edit_pages',\n 'delete_posts' => 'edit_pages',\n 'publish_posts' => 'edit_pages',\n 'read_private_posts' => 'edit_pages'\n );\n $args = array(\n 'labels' => $labels,\n 'hierarchical' => true,\n 'public' => true,\n 'show_ui' => true,\n 'show_admin_column' => true,\n 'show_in_nav_menus' => true,\n 'show_tagcloud' => true,\n 'capabilities' => $capabilities,\n );\n register_taxonomy( 'taxonomy_key', array( 'post', 'foo_key', 'bar_key' ), $args );\n}\nadd_action( 'init', 'something_taxonomy', 0 );\n</code></pre>\n\n<p>What I used to remove the meta box from Contributors:</p>\n\n<pre><code>if ( is_admin() ) {\n function remove_metabox_for_non_admin_and_editor() {\n if ( current_user_can( 'contributor' ) || current_user_can( 'subscriber' ) ) {\n remove_meta_box( 'tagsdiv-foo_key_tag', 'foo_key', 'normal' );\n remove_meta_box( 'categorydiv', 'foo_key', 'normal' );\n remove_meta_box( 'foo_keyimagediv', 'foo_key', 'normal' );\n remove_meta_box( 'authordiv', 'foo_key', 'normal' );\n remove_meta_box( 'trackbacksdiv', 'foo_key', 'normal' );\n remove_meta_box( 'commentstatusdiv', 'foo_key', 'normal' );\n remove_meta_box( 'foo_keycustom', 'foo_key', 'normal' );\n remove_meta_box( 'commentstatusdiv', 'foo_key', 'normal' );\n remove_meta_box( 'commentsdiv', 'foo_key', 'normal' );\n remove_meta_box( 'revisionsdiv', 'foo_key', 'normal' );\n remove_meta_box( 'authordiv', 'foo_key', 'normal' );\n remove_meta_box( 'slugdiv', 'foo_key', 'normal' );\n remove_meta_box( 'taxonomy_keydiv', 'foo_key', 'normal' );\n // remove pages\n remove_menu_page( 'edit-comments.php' );\n remove_menu_page( 'edit.php' );\n remove_menu_page( 'tools.php' );\n }\n }\n add_action( 'admin_menu', 'remove_metabox_for_non_admin_and_editor' );\n}\n</code></pre>\n\n<p>To find what the <code>$id</code> is for the custom meta box I used Chrome's inspect element to find the id it was creating. I chose <code>admin_menu</code> instead of <code>admin_init</code> after reading \"<a href=\"https://stackoverflow.com/questions/27137866/what-wordpress-hook-fires-first-admin-init-or-admin-menu\">What Wordpress hook fires first admin_init or admin_menu</a>\"</p>\n"
}
] |
2015/11/07
|
[
"https://wordpress.stackexchange.com/questions/207924",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] |
Im trying to only show a taxonomy for the `editor` and `administrator` but I haven't found a solution on SO or here. The closest thing I was able to find was [How do I remove a taxonomy from Wordpress?](https://stackoverflow.com/questions/4249694/how-do-i-remove-a-taxonomy-from-wordpress) on SO. What is the proper way to only allow the taxonomy for the `editor` and `administrator`?
```
// remove from everyone that isn't admin or editor
function taxonomy_for_admin_and_editor_only() {
if ( !current_user_can( 'administrator' ) || !current_user_can( 'editor' ) ) {
register_taxonomy( 'foobar', array() );
}
}
add_action( 'init' , 'taxonomy_for_admin_and_editor_only' );
```
I've tried `add_action( 'admin' , 'taxonomy_for_admin_and_editor_only' );` with no luck either.
|
When registering your taxonomy you can pass an argument called **capabilities**. Simply passing capabiities that only admins and editors have.
```
$args = array(
'capabilities' => array( 'manage_options', 'edit_posts' )
);
register_taxonomy( 'foobar', 'post', $args );
```
<https://codex.wordpress.org/Roles_and_Capabilities#Editor>
|
207,947 |
<p>I'd like to (in php) display a given user's avatar and bio (description) and some social media for them (based on their profile info fields). For example, on Page1, display user Walt Whitman's (user number 9999) picture, description (bio), and social media links, regardless of who wrote the page or who is logged in reading the page. </p>
<p>I can display the avatar:</p>
<pre><code><?php echo get_avatar( '[email protected]', 32 ); ?>
</code></pre>
<p>I've tried a couple of things, but they don't work. I get either a full display of all meta or a fatal error (various fatal errors like 'must be string' etc).</p>
<pre><code><?php the_user_meta( 'description' ); ?>
</code></pre>
<p>or</p>
<pre><code><?php $userdata = get_user_meta( 9999 ); ?><?php echo $userdata['description']; ?>
</code></pre>
<p>If I use </p>
<pre><code><?php $user = wp_get_current_user( 9999 ); if ( $user->exists() ) // is_user_logged_in() is a wrapper for this line $userdata = get_user_meta( $user->data->ID ); ?><pre><?php var_dump( $userdata ); ?></pre><?php echo $userdata['description'] ; ?>
</code></pre>
<p>I get a fatal error.</p>
|
[
{
"answer_id": 207959,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>You can make use of </p>\n\n<ul>\n<li><p><a href=\"https://codex.wordpress.org/Function_Reference/wp_get_current_user\" rel=\"noreferrer\"><code>wp_get_current_user()</code></a> or </p></li>\n<li><p><a href=\"https://codex.wordpress.org/get_currentuserinfo\" rel=\"noreferrer\"><code>get_currentuserinfo()</code></a> (<em>to which <code>wp_get_current_user()</code> is a wrapper function to</em>) or</p></li>\n<li><p><a href=\"https://developer.wordpress.org/reference/functions/get_current_user_id/\" rel=\"noreferrer\"><code>get_current_user_id()</code></a> which uses <code>wp_get_current_user()</code></p></li>\n</ul>\n\n<p>to get the current logged in user ID.</p>\n\n<p>One way or the other, you need to make sure that you have a logged in user (<em>user ID is not 0</em>) before trying to get the user's metadata from the db.</p>\n\n<p>Once you have the user ID, you can use <a href=\"https://developer.wordpress.org/reference/functions/get_user_meta/\" rel=\"noreferrer\"><code>get_user_meta()</code></a> to return the user's info from the db</p>\n\n<h2>EXAMPLE:</h2>\n\n<pre><code>$user = wp_get_current_user();\nif ( $user->exists() ) { // is_user_logged_in() is a wrapper for this line\n $userdata = get_user_meta( $user->data->ID );\n ?><pre><?php var_dump( $userdata ); ?></pre><?php\n}\n</code></pre>\n\n<h2>EDIT</h2>\n\n<p>This is very basic PHP. Here is what is returned by </p>\n\n<pre><code>$userdata = get_user_meta( 1 );\n ?><pre><?php var_dump( $userdata ); ?></pre><?php\n</code></pre>\n\n<p>The <code>var_dump()</code></p>\n\n<pre><code>array(29) {\n [\"first_name\"]=>\n array(1) {\n [0]=>\n string(6) \"Pieter\"\n }\n [\"last_name\"]=>\n array(1) {\n [0]=>\n string(6) \"Goosen\"\n }\n [\"nickname\"]=>\n array(1) {\n [0]=>\n string(12) \"pietergoosen\"\n }\n [\"description\"]=>\n array(1) {\n [0]=>\n string(349) \"My naam is Pieter Goosen BLAH BLAH BLAH\"\n }\n [\"rich_editing\"]=>\n array(1) {\n [0]=>\n string(4) \"true\"\n }\n [\"comment_shortcuts\"]=>\n array(1) {\n [0]=>\n string(5) \"false\"\n }\n [\"admin_color\"]=>\n array(1) {\n [0]=>\n string(5) \"fresh\"\n }\n [\"use_ssl\"]=>\n array(1) {\n [0]=>\n string(1) \"0\"\n }\n [\"show_admin_bar_front\"]=>\n array(1) {\n [0]=>\n string(5) \"false\"\n }\n [\"wp_capabilities\"]=>\n array(1) {\n [0]=>\n string(31) \"a:1:{s:13:\"administrator\";b:1;}\"\n }\n [\"wp_user_level\"]=>\n array(1) {\n [0]=>\n string(2) \"10\"\n }\n [\"dismissed_wp_pointers\"]=>\n array(1) {\n [0]=>\n string(143) \"wp330_toolbar,wp330_saving_widgets,wp340_choose_image_from_library,wp340_customize_current_theme_link,wp350_media,wp360_revisions,wp390_widgets\"\n }\n [\"show_welcome_panel\"]=>\n array(1) {\n [0]=>\n string(1) \"0\"\n }\n [\"wp_user-settings\"]=>\n array(1) {\n [0]=>\n string(120) \"libraryContent=browse&imgsize=full&align=right&editor=html&hidetb=1&mfold=o&unfold=1&urlbutton=post&posts_list_mode=list\"\n }\n [\"wp_user-settings-time\"]=>\n array(1) {\n [0]=>\n string(10) \"1447257892\"\n }\n [\"wp_dashboard_quick_press_last_post_id\"]=>\n array(1) {\n [0]=>\n string(3) \"463\"\n }\n [\"twitter\"]=>\n array(1) {\n [0]=>\n string(0) \"\"\n }\n [\"facebook\"]=>\n array(1) {\n [0]=>\n string(15) \"pietergoosencom\"\n }\n [\"managenav-menuscolumnshidden\"]=>\n array(1) {\n [0]=>\n string(89) \"a:4:{i:0;s:11:\"link-target\";i:1;s:11:\"css-classes\";i:2;s:3:\"xfn\";i:3;s:11:\"description\";}\"\n }\n [\"metaboxhidden_nav-menus\"]=>\n array(1) {\n [0]=>\n string(102) \"a:4:{i:0;s:8:\"add-post\";i:1;s:14:\"add-informasie\";i:2;s:12:\"add-post_tag\";i:3;s:15:\"add-post_format\";}\"\n }\n [\"nav_menu_recently_edited\"]=>\n array(1) {\n [0]=>\n string(3) \"130\"\n }\n [\"closedpostboxes_page\"]=>\n array(1) {\n [0]=>\n string(6) \"a:0:{}\"\n }\n [\"metaboxhidden_page\"]=>\n array(1) {\n [0]=>\n string(94) \"a:4:{i:0;s:10:\"postcustom\";i:1;s:16:\"commentstatusdiv\";i:2;s:7:\"slugdiv\";i:3;s:9:\"authordiv\";}\"\n }\n [\"closedpostboxes_post\"]=>\n array(1) {\n [0]=>\n string(6) \"a:0:{}\"\n }\n [\"metaboxhidden_post\"]=>\n array(1) {\n [0]=>\n string(6) \"a:0:{}\"\n }\n [\"closedpostboxes_positions\"]=>\n array(1) {\n [0]=>\n string(6) \"a:0:{}\"\n }\n [\"metaboxhidden_positions\"]=>\n array(1) {\n [0]=>\n string(6) \"a:0:{}\"\n }\n [\"rtladminbar\"]=>\n array(1) {\n [0]=>\n string(3) \"ltr\"\n }\n [\"session_tokens\"]=>\n array(1) {\n [0]=>\n string(285) \"a:1:{s:64:\"fa12574e7a42af2a8944d764c21bda64a5a5ee4572b1fbceb027d8b4af5afcd3\";a:4:{s:10:\"expiration\";i:1448467488;s:2:\"ip\";s:3:\"::1\";s:2:\"ua\";s:108:\"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36\";s:5:\"login\";i:1447257888;}}\"\n }\n}\n</code></pre>\n\n<p>So, if you need to display the description, you can do </p>\n\n<pre><code>echo $userdata['description'][0];\n</code></pre>\n\n<p>To learn how to reference values in an array, you should really need and go and learn the very basics of how arrays work and how to reference them</p>\n\n<h2>EDIT</h2>\n\n<p>The following is an exact use case</p>\n\n<pre><code>$walt_id = 1; // Make sure you have the correct ID here\n$userdata = get_user_meta( $walt_id );\necho $userdata['description'][0];\n</code></pre>\n\n<p>If this does not work, you have a serious issue somewhere which you should debug as I have stated in comments</p>\n"
},
{
"answer_id": 208006,
"author": "Mike Selander",
"author_id": 83233,
"author_profile": "https://wordpress.stackexchange.com/users/83233",
"pm_score": 1,
"selected": false,
"text": "<p>You can use <code>get_user_by</code> to get their User ID from the email address since it looks like that's the data you have available above. You can then use the <a href=\"https://codex.wordpress.org/Function_Reference/get_userdata\" rel=\"nofollow\"><code>get_userdata</code></a> or <a href=\"https://codex.wordpress.org/Function_Reference/get_user_meta\" rel=\"nofollow\"><code>get_user_meta</code></a> from that user ID to pull all of their other meta fields.</p>\n\n<h2>For example:</h2>\n\n<pre><code>$user = get_user_by( 'email', '[email protected]' );\n$userdata = get_userdata( $user->ID );\n\n$first_name = $userdata-> first_name;\n</code></pre>\n"
},
{
"answer_id": 208510,
"author": "Justin Munce",
"author_id": 73570,
"author_profile": "https://wordpress.stackexchange.com/users/73570",
"pm_score": 0,
"selected": false,
"text": "<p>(I am the op.)</p>\n\n<p>Two options to solve this. These can be used to display any information for the users registered on your website. I'm going to show you how to display one OR two (ie more) things:</p>\n\n<p><strong>1) Pieter Goosen way</strong> (I checked his answer as correct above -- thanks again, Pieter) (People, you need to go into the user profile and get their user number. Use that number instead of 9999.</p>\n\n<p>One thing:</p>\n\n<pre><code><?php $walt_id = 9999; // Make sure you have the correct ID here\n$userdata = get_user_meta( $walt_id );\necho $userdata['description'][0]; \n?>\n</code></pre>\n\n<p>More than one thing:</p>\n\n<pre><code><?php $walt_id = 9999; // Make sure you have the correct ID here\n$userdata = get_user_meta( $walt_id );\necho $userdata['description'][0]; \necho $userdata['first_name'][0]; \n?>\n</code></pre>\n\n<p><strong>2) stephencottontail way:</strong></p>\n\n<p>One thing:</p>\n\n<pre><code><?php the_author_meta( 'user_description', 9999 ); ?> </br>\n</code></pre>\n\n<p>More than one thing:</p>\n\n<pre><code><?php the_author_meta( 'user_description', 9999 ); ?> </br>\n<?php the_author_meta( 'first_name', 9999 ); ?>\n</code></pre>\n"
}
] |
2015/11/08
|
[
"https://wordpress.stackexchange.com/questions/207947",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73570/"
] |
I'd like to (in php) display a given user's avatar and bio (description) and some social media for them (based on their profile info fields). For example, on Page1, display user Walt Whitman's (user number 9999) picture, description (bio), and social media links, regardless of who wrote the page or who is logged in reading the page.
I can display the avatar:
```
<?php echo get_avatar( '[email protected]', 32 ); ?>
```
I've tried a couple of things, but they don't work. I get either a full display of all meta or a fatal error (various fatal errors like 'must be string' etc).
```
<?php the_user_meta( 'description' ); ?>
```
or
```
<?php $userdata = get_user_meta( 9999 ); ?><?php echo $userdata['description']; ?>
```
If I use
```
<?php $user = wp_get_current_user( 9999 ); if ( $user->exists() ) // is_user_logged_in() is a wrapper for this line $userdata = get_user_meta( $user->data->ID ); ?><pre><?php var_dump( $userdata ); ?></pre><?php echo $userdata['description'] ; ?>
```
I get a fatal error.
|
You can make use of
* [`wp_get_current_user()`](https://codex.wordpress.org/Function_Reference/wp_get_current_user) or
* [`get_currentuserinfo()`](https://codex.wordpress.org/get_currentuserinfo) (*to which `wp_get_current_user()` is a wrapper function to*) or
* [`get_current_user_id()`](https://developer.wordpress.org/reference/functions/get_current_user_id/) which uses `wp_get_current_user()`
to get the current logged in user ID.
One way or the other, you need to make sure that you have a logged in user (*user ID is not 0*) before trying to get the user's metadata from the db.
Once you have the user ID, you can use [`get_user_meta()`](https://developer.wordpress.org/reference/functions/get_user_meta/) to return the user's info from the db
EXAMPLE:
--------
```
$user = wp_get_current_user();
if ( $user->exists() ) { // is_user_logged_in() is a wrapper for this line
$userdata = get_user_meta( $user->data->ID );
?><pre><?php var_dump( $userdata ); ?></pre><?php
}
```
EDIT
----
This is very basic PHP. Here is what is returned by
```
$userdata = get_user_meta( 1 );
?><pre><?php var_dump( $userdata ); ?></pre><?php
```
The `var_dump()`
```
array(29) {
["first_name"]=>
array(1) {
[0]=>
string(6) "Pieter"
}
["last_name"]=>
array(1) {
[0]=>
string(6) "Goosen"
}
["nickname"]=>
array(1) {
[0]=>
string(12) "pietergoosen"
}
["description"]=>
array(1) {
[0]=>
string(349) "My naam is Pieter Goosen BLAH BLAH BLAH"
}
["rich_editing"]=>
array(1) {
[0]=>
string(4) "true"
}
["comment_shortcuts"]=>
array(1) {
[0]=>
string(5) "false"
}
["admin_color"]=>
array(1) {
[0]=>
string(5) "fresh"
}
["use_ssl"]=>
array(1) {
[0]=>
string(1) "0"
}
["show_admin_bar_front"]=>
array(1) {
[0]=>
string(5) "false"
}
["wp_capabilities"]=>
array(1) {
[0]=>
string(31) "a:1:{s:13:"administrator";b:1;}"
}
["wp_user_level"]=>
array(1) {
[0]=>
string(2) "10"
}
["dismissed_wp_pointers"]=>
array(1) {
[0]=>
string(143) "wp330_toolbar,wp330_saving_widgets,wp340_choose_image_from_library,wp340_customize_current_theme_link,wp350_media,wp360_revisions,wp390_widgets"
}
["show_welcome_panel"]=>
array(1) {
[0]=>
string(1) "0"
}
["wp_user-settings"]=>
array(1) {
[0]=>
string(120) "libraryContent=browse&imgsize=full&align=right&editor=html&hidetb=1&mfold=o&unfold=1&urlbutton=post&posts_list_mode=list"
}
["wp_user-settings-time"]=>
array(1) {
[0]=>
string(10) "1447257892"
}
["wp_dashboard_quick_press_last_post_id"]=>
array(1) {
[0]=>
string(3) "463"
}
["twitter"]=>
array(1) {
[0]=>
string(0) ""
}
["facebook"]=>
array(1) {
[0]=>
string(15) "pietergoosencom"
}
["managenav-menuscolumnshidden"]=>
array(1) {
[0]=>
string(89) "a:4:{i:0;s:11:"link-target";i:1;s:11:"css-classes";i:2;s:3:"xfn";i:3;s:11:"description";}"
}
["metaboxhidden_nav-menus"]=>
array(1) {
[0]=>
string(102) "a:4:{i:0;s:8:"add-post";i:1;s:14:"add-informasie";i:2;s:12:"add-post_tag";i:3;s:15:"add-post_format";}"
}
["nav_menu_recently_edited"]=>
array(1) {
[0]=>
string(3) "130"
}
["closedpostboxes_page"]=>
array(1) {
[0]=>
string(6) "a:0:{}"
}
["metaboxhidden_page"]=>
array(1) {
[0]=>
string(94) "a:4:{i:0;s:10:"postcustom";i:1;s:16:"commentstatusdiv";i:2;s:7:"slugdiv";i:3;s:9:"authordiv";}"
}
["closedpostboxes_post"]=>
array(1) {
[0]=>
string(6) "a:0:{}"
}
["metaboxhidden_post"]=>
array(1) {
[0]=>
string(6) "a:0:{}"
}
["closedpostboxes_positions"]=>
array(1) {
[0]=>
string(6) "a:0:{}"
}
["metaboxhidden_positions"]=>
array(1) {
[0]=>
string(6) "a:0:{}"
}
["rtladminbar"]=>
array(1) {
[0]=>
string(3) "ltr"
}
["session_tokens"]=>
array(1) {
[0]=>
string(285) "a:1:{s:64:"fa12574e7a42af2a8944d764c21bda64a5a5ee4572b1fbceb027d8b4af5afcd3";a:4:{s:10:"expiration";i:1448467488;s:2:"ip";s:3:"::1";s:2:"ua";s:108:"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/46.0.2490.80 Safari/537.36";s:5:"login";i:1447257888;}}"
}
}
```
So, if you need to display the description, you can do
```
echo $userdata['description'][0];
```
To learn how to reference values in an array, you should really need and go and learn the very basics of how arrays work and how to reference them
EDIT
----
The following is an exact use case
```
$walt_id = 1; // Make sure you have the correct ID here
$userdata = get_user_meta( $walt_id );
echo $userdata['description'][0];
```
If this does not work, you have a serious issue somewhere which you should debug as I have stated in comments
|
207,960 |
<p>I have some scheduled events in my WordPress site. For that I use a cron job, so it has created an option in the <code>wp_options</code> table. </p>
<p>After some days, my site is getting slow. When I check my database, it has more than 2MB of data in the cron field, so I am thinking to clean it now. Will that affect my site's cron operations? </p>
<p>I guess it's all about entries in the table. Due to the fuzzy entries, my site is getting slow down. Here my code. </p>
<pre><code>wp_schedule_event(time(), 'daily', 'kv_daily_post_expire_check');
function kv_daily_post_expire_check() {
$the_query = get_posts( 'post_type=job&post_status=publish' );
foreach($the_query as $single_post) {
$id=$single_post->ID;
$ad_close_date=get_post_meta($id, 'ad_close_date', true );
if($ad_close_date!=''){
$today=date("Y-m-d");
$ad_less_close_date=$ad_close_date-3;
if($ad_close_date<$today){
$update_post = array(
'ID' => $id,
'post_status' => 'expired',
'post_type' => 'job' );
wp_update_post($update_post);
}
else if($ad_less_close_date==$today){
$update_post = array(
'ID' => $id,
'post_status' => 'expired',
'post_type' => 'job' );
//wp_update_post($update_post);
kv_author_post_expiring_soon($id,3);
}
}
}
}
</code></pre>
<p>and here is the data which is there in my database table. </p>
<pre><code>a:7:{i:1447098349;a:3:{s:16:"wp_version_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}s:17:"wp_update_plugins";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}s:16:"wp_update_themes";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}}i:1447099020;a:1:{s:20:"wp_maybe_auto_update";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}}i:1447141549;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1447141669;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1447141790;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1447141909;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}s:7:"version";i:2;}
</code></pre>
|
[
{
"answer_id": 207970,
"author": "mrbobbybryant",
"author_id": 64953,
"author_profile": "https://wordpress.stackexchange.com/users/64953",
"pm_score": 0,
"selected": false,
"text": "<p>You should check out this developer plugin. It gives you fine control when working with cron. <a href=\"https://wordpress.org/plugins/wp-crontrol/\" rel=\"nofollow\">https://wordpress.org/plugins/wp-crontrol/</a></p>\n\n<p>I'd also rethink your cron processes. Sounds like you might need to have some post-cron cleanup built into your code. But i'm just speculating here.</p>\n"
},
{
"answer_id": 207975,
"author": "futuernorn",
"author_id": 83220,
"author_profile": "https://wordpress.stackexchange.com/users/83220",
"pm_score": 2,
"selected": false,
"text": "<p>If you want a quick programmatic way of looping through everything you have in the <code>cron</code> row inside wp_options and you have access to the site's database directly (either in a local development environment or on a webhost), you can run something like this via the command line:</p>\n\n<pre><code>mysql $YOUR_DB_NAME -e \"SELECT option_value FROM wp_options WHERE option_name='cron';\" | php -r '$cronArray = unserialize(file_get_contents(\"php://stdin\")); foreach ($cronArray as $timestamp => $data) { echo $timestamp.\" --> \".date(\"c\",$timestamp).\"\\n\"; print_r($data); }'\n</code></pre>\n\n<p>I feel that viewing this information outside of any other context can sometimes be very illustrative. The above one-liner will give you output like the following that can then be examined further:</p>\n\n<pre><code>1446749050 --> 2015-11-05T18:44:10+00:00\nArray\n(\n [wp_version_check] => Array\n (\n [40cd750bba9870f18aada2478b24840a] => Array\n (\n [schedule] => twicedaily\n [args] => Array\n (\n )\n\n [interval] => 43200\n )\n\n )\n\n)\n1446751800 --> 2015-11-05T19:30:00+00:00\nArray\n(\n[wp_maybe_auto_update] => Array\n[...]\n</code></pre>\n\n<p><a href=\"http://wp-cli.org/\" rel=\"nofollow\">wp-cli</a> is also a great option for viewing and editing this type of data:</p>\n\n<pre><code>$ wp option delete cron\nSuccess: Deleted 'cron' option.\n$ wp option get cron\narray (\n1447092802 =>\narray (\n'wp_version_check' =>\narray (\n '40cd750bba9870f18aada2478b24840a' =>\n array (\n 'schedule' => 'twicedaily',\n 'args' =>\n array (\n ),\n 'interval' => 43200,\n ),\n),\n'wp_update_plugins' =>\n[...]\n</code></pre>\n\n<hr>\n\n<p>The important thing to keep in mind is that the <code>cron</code> row is one of WordPress's autoloaded rows. This means that the data in this row has to be queried out of the database and processed by WordPress on <em>every single page load</em>. So you are definitely right to want to keep the size of this row as low as possible. As <a href=\"https://wordpress.stackexchange.com/users/64953/mrbobbybryant\">@mrbobbybryant</a> mentioned, there are also plugins that let you view and edit what is in this row via WordPress directly.</p>\n\n<p>When attempting to determine what should or shouldn't be a part of this data, I would recommend looking for numerous entries of one type or any other elements that seem to not belong there. Once those elements are identified, you can work back and find the code they originated from and tweak how the crons operate there.</p>\n\n<p>Also, while this shouldn't be a factor if you're up to date on your WordPress version, it is worth mentioning there was a bug that could lead to greatly increased sizes of <code>cron</code> option rows in WordPress 4.3: <a href=\"https://core.trac.wordpress.org/ticket/33423\" rel=\"nofollow\">#33423 - Arguments switched in wp_batch_split_terms Cron Job in 4.3</a>.</p>\n"
},
{
"answer_id": 208002,
"author": "kaiser",
"author_id": 385,
"author_profile": "https://wordpress.stackexchange.com/users/385",
"pm_score": 1,
"selected": false,
"text": "<p>When your Cron array gets stuffed with more than one task, then there's a high chance, that you either forgot to check if there's already an unfinished task in the queue, or you have the config wrong. The <em>config</em> array gets used to ID a task in the queue. Meaning if you for e.g. have a typo or some other difference between <code>wp_next_schedule()</code> checks and <code>wp_schedule_event()</code>, then the check will succeed and you easily end up with the task getting added over and over again. Make sure you <strong>double check</strong> that. Better just use a variable for both the hook as well as the config to not make that mistake.</p>\n\n<pre><code>add_action( 'wp_loaded', function()\n{\n $hook = 'your_custom_event';\n\n $task = new YourCronHandler();\n\n // Config: An Array of arrays\n $config = [ ( include __DIR__.'/config.php' ), ];\n\n add_action( $hook, $task );\n\n // Make sure to not run during installation or if there's already a task added\n if (\n ! defined( 'WP_INSTALLING' )\n && ! wp_next_scheduled( $hook, $config )\n ) {\n wp_schedule_event(\n time(),\n 'thirtymin',\n $hook,\n $config\n );\n }\n} );\n</code></pre>\n\n<p>Then just build your handler:</p>\n\n<pre><code>class YourCronHandler\n{\n public function __invoke( Array $config = [] )\n {\n // Bootstrap your process here\n }\n}\n</code></pre>\n\n<p>The config can easily get separated to a stand-alone file. Doing so will help to make things easier readable and in case even reusable.</p>\n\n<pre><code><?php\n\nreturn [\n 'foo' => 'bar',\n];\n</code></pre>\n\n<p>Sidenote: When your cron job is running, WP automatically adds a cron lock to the database, so you don't have to care about load balancers and different servers behind it running the same task more than once. This can't be your problem, but in such cases it's better to deactivate cron in your <code>wp-config.php</code> and just trigger cron manually from your cron tab on a single server instead.</p>\n\n<h2>Intervals</h2>\n\n<p><em>To make above example complete</em></p>\n\n<p>In case you need a different interval, it's quite easy:</p>\n\n<pre><code>add_filter( 'cron_schedules', function( Array $schedules = [] )\n{\n return $schedules + [\n 'thirtymin' => [\n 'interval' => HOUR_IN_SECONDS / 2,\n 'display' => 'Every Thirty Minutes'\n ],\n ];\n} );\n</code></pre>\n"
},
{
"answer_id": 208261,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 1,
"selected": true,
"text": "<p>Thanks for all of your comments. I found solution by myself. </p>\n\n<p>The reason is the action hook we have to use it like this. otherwise, the function will be called every page we load. so here is the code , that i used to solve it. </p>\n\n<pre><code>add_action( 'switch_theme', 'kv_event_scheduler' );\n\nfunction kv_event_scheduler() { \n wp_schedule_event(time(), 'daily', 'kv_daily_post_expire_check');\n}\n</code></pre>\n\n<p>Here the function will be hooked only once, after the theme change. So it will be hooked only once. than the cron will work daily once. </p>\n\n<p>and also cleaning the cron option value will affect the functionality. but you dont need to fear for it. once you change this function like the below, it will create entries automatically. </p>\n\n<pre><code> add_action( 'after_setup_theme', 'kv_event_scheduler' );\n\nfunction kv_event_scheduler() { \n wp_schedule_event(time(), 'daily', 'kv_daily_post_expire_check');\n}\n</code></pre>\n\n<p>once you save this refresh a page, than change the \"after_setup_theme\" into \"switch_theme\" , than your entries will be created automatically. </p>\n\n<p>I hope this one help someone who stuck on the same problem. if my solution helped anyone vote it.</p>\n"
}
] |
2015/11/08
|
[
"https://wordpress.stackexchange.com/questions/207960",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43308/"
] |
I have some scheduled events in my WordPress site. For that I use a cron job, so it has created an option in the `wp_options` table.
After some days, my site is getting slow. When I check my database, it has more than 2MB of data in the cron field, so I am thinking to clean it now. Will that affect my site's cron operations?
I guess it's all about entries in the table. Due to the fuzzy entries, my site is getting slow down. Here my code.
```
wp_schedule_event(time(), 'daily', 'kv_daily_post_expire_check');
function kv_daily_post_expire_check() {
$the_query = get_posts( 'post_type=job&post_status=publish' );
foreach($the_query as $single_post) {
$id=$single_post->ID;
$ad_close_date=get_post_meta($id, 'ad_close_date', true );
if($ad_close_date!=''){
$today=date("Y-m-d");
$ad_less_close_date=$ad_close_date-3;
if($ad_close_date<$today){
$update_post = array(
'ID' => $id,
'post_status' => 'expired',
'post_type' => 'job' );
wp_update_post($update_post);
}
else if($ad_less_close_date==$today){
$update_post = array(
'ID' => $id,
'post_status' => 'expired',
'post_type' => 'job' );
//wp_update_post($update_post);
kv_author_post_expiring_soon($id,3);
}
}
}
}
```
and here is the data which is there in my database table.
```
a:7:{i:1447098349;a:3:{s:16:"wp_version_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}s:17:"wp_update_plugins";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}s:16:"wp_update_themes";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}}i:1447099020;a:1:{s:20:"wp_maybe_auto_update";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:10:"twicedaily";s:4:"args";a:0:{}s:8:"interval";i:43200;}}}i:1447141549;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1447141669;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1447141790;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}i:1447141909;a:1:{s:26:"kv_daily_post_expire_check";a:1:{s:32:"40cd750bba9870f18aada2478b24840a";a:3:{s:8:"schedule";s:5:"daily";s:4:"args";a:0:{}s:8:"interval";i:86400;}}}s:7:"version";i:2;}
```
|
Thanks for all of your comments. I found solution by myself.
The reason is the action hook we have to use it like this. otherwise, the function will be called every page we load. so here is the code , that i used to solve it.
```
add_action( 'switch_theme', 'kv_event_scheduler' );
function kv_event_scheduler() {
wp_schedule_event(time(), 'daily', 'kv_daily_post_expire_check');
}
```
Here the function will be hooked only once, after the theme change. So it will be hooked only once. than the cron will work daily once.
and also cleaning the cron option value will affect the functionality. but you dont need to fear for it. once you change this function like the below, it will create entries automatically.
```
add_action( 'after_setup_theme', 'kv_event_scheduler' );
function kv_event_scheduler() {
wp_schedule_event(time(), 'daily', 'kv_daily_post_expire_check');
}
```
once you save this refresh a page, than change the "after\_setup\_theme" into "switch\_theme" , than your entries will be created automatically.
I hope this one help someone who stuck on the same problem. if my solution helped anyone vote it.
|
207,967 |
<p>Because I want to use jQuery 2.1 instead of 1.11, I first have to de-register jQuery. Then register it with the new values. :</p>
<pre><code>add_action( 'wp_enqueue_scripts', 'add_scripts' );
function add_scripts() {
wp_deregister_script('jquery');
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', false, '2.1.0', false);
wp_enqueue_script('jquery');
}
</code></pre>
<p>According to <a href="https://codex.wordpress.org/Function_Reference/wp_register_script" rel="nofollow">the manual</a>, this should load the script in the header. But it's loaded in the footer. Why is that?</p>
<p>I'm asking because I have a plugin that needs to have some stuff in the header. Since jquery isn't loaded until the footer, it throws some errors.</p>
<p>PS. If I do the following:</p>
<pre><code> wp_deregister_script('jquery');
wp_register_script( 'jquery-2', 'http:...');
wp_enqueue_script('jquery-2');
</code></pre>
<p>WP will not load any content at all - it completely breaks. Has anyone else experienced that?</p>
|
[
{
"answer_id": 207968,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 1,
"selected": false,
"text": "<p>No 1: you have to put your jquery deregister etc. Stuff into a function that is called with the wp_enqueue_scripts hook. Do it like this:</p>\n\n<pre><code>add_action('wp_enqueue_scripts','jquery_2_loader');\n\nfunction jquery_2_loader(){\n//insert your jquery deregister and Register\n}\n</code></pre>\n\n<p>Second question: many Plugins rely on enqueuing jquery. So if you deregister it, those Plugins can't use it anymore.</p>\n"
},
{
"answer_id": 207976,
"author": "futuernorn",
"author_id": 83220,
"author_profile": "https://wordpress.stackexchange.com/users/83220",
"pm_score": 0,
"selected": false,
"text": "<p>You are correct that passing <code>false</code> to the <code>wp_register_script</code> function call should ensure the script is placed in the page's header. Do you have any other plugins that may be modifying your scripts' location? For instance, plugins like <a href=\"https://wordpress.org/plugins/autoptimize/\" rel=\"nofollow\">Autoptimize</a> will try to \"intelligently\" place scripts in the footer to speed loading when possible.</p>\n"
},
{
"answer_id": 207979,
"author": "MacK",
"author_id": 73755,
"author_profile": "https://wordpress.stackexchange.com/users/73755",
"pm_score": 3,
"selected": true,
"text": "<p>In theory the code you wrote should work, in the practical application you are missing some good practices which it might impact on how your code is working, so it's better run through a bit of troubleshooting to tick off everything from the checklist.</p>\n\n<p>By de-registering <code>jquery</code> you are taking away both the jQuery core and the jQuery Migrate javascripts, probably what are you trying to do is to deregister just the core and keep the jQuery Migrate on.</p>\n\n<p>jQuery Migrate consists in old legacy jQuery code which ports all the functionality of legacy stuff onto the new version of jQuery.</p>\n\n<p>On the same page of the Codex you linked if you scroll down you can find a list of <a href=\"https://codex.wordpress.org/Function_Reference/wp_register_script#Handles_and_Their_Script_Paths_Registered_by_WordPress\" rel=\"nofollow\">handlers of integrated javascripts you can de-register</a>.</p>\n\n<p>As result you have to to deregister <code>jquery-core</code> instead of <code>jquery</code> to keep some of the functionalities intact, this includes plugins they might some legacy jQuery stuff to run.</p>\n\n<p>You don't need to append \"false\" at the last argument since it's already false by default, I also suggest to drop your protocol, this ensures jQuery will be always served to the browser if you want to switch to https at a later time.</p>\n\n<p>As a final touch, namespacing is very important when you are coding in a big environment where other's people code runs along with yours. <code>add_scripts()</code> seems a bit too generic for me, if you are writing your function inside the <code>functions.php</code> file try to add the name of your theme, or write something very unique so you are sure the same function doesn't get collide in the future with a function coming from a plugin or something else in your working files.</p>\n\n<pre><code>add_action( 'wp_enqueue_scripts', 'YOURTHEMENAME_scripts' );\n\nfunction YOURTHEMENAME_scripts() {\n wp_deregister_script('jquery-core');\n wp_register_script('jquery-core', '//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', false, '2.1.0');\n wp_enqueue_script('jquery-core');\n}\n</code></pre>\n\n<p>Please note that the loading order of Wordpress is the following:</p>\n\n<pre><code>Core -> Plugins -> Theme\n</code></pre>\n\n<p>If you are trying to de-register jQuery from a custom plugin then possibly your theme is taking over and messing around with the scripts queue.</p>\n\n<p>If after all of this you're still getting the Javascript into the footer then there's something horribly wrong going on into your <code>header.php</code> or <code>footer.php</code> files: one of the rookie reasons could be the location of <code>wp_head()</code> and <code>wp_footer()</code> specific hooks in your theme, I've seen this so many times which it could be easily a possibility.</p>\n\n<p><code>wp_head()</code> is a hook which adds for you meta tags, the css queue and the js queue with the last flag argument set to \"false\".</p>\n\n<p><code>wp_footer()</code> is the hook which cares about adding to you the rest of the JS with the last flag argument set to \"true\" and extra markup generated from various plugins (and for the admin bar from the WP core).</p>\n\n<p>Do a double check about the location of your hook functions, if you have <code>wp_head()</code> in your footer then it could be easily the reason why your javascript queue is being added to the footer.</p>\n"
}
] |
2015/11/08
|
[
"https://wordpress.stackexchange.com/questions/207967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1447/"
] |
Because I want to use jQuery 2.1 instead of 1.11, I first have to de-register jQuery. Then register it with the new values. :
```
add_action( 'wp_enqueue_scripts', 'add_scripts' );
function add_scripts() {
wp_deregister_script('jquery');
wp_register_script( 'jquery', 'http://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', false, '2.1.0', false);
wp_enqueue_script('jquery');
}
```
According to [the manual](https://codex.wordpress.org/Function_Reference/wp_register_script), this should load the script in the header. But it's loaded in the footer. Why is that?
I'm asking because I have a plugin that needs to have some stuff in the header. Since jquery isn't loaded until the footer, it throws some errors.
PS. If I do the following:
```
wp_deregister_script('jquery');
wp_register_script( 'jquery-2', 'http:...');
wp_enqueue_script('jquery-2');
```
WP will not load any content at all - it completely breaks. Has anyone else experienced that?
|
In theory the code you wrote should work, in the practical application you are missing some good practices which it might impact on how your code is working, so it's better run through a bit of troubleshooting to tick off everything from the checklist.
By de-registering `jquery` you are taking away both the jQuery core and the jQuery Migrate javascripts, probably what are you trying to do is to deregister just the core and keep the jQuery Migrate on.
jQuery Migrate consists in old legacy jQuery code which ports all the functionality of legacy stuff onto the new version of jQuery.
On the same page of the Codex you linked if you scroll down you can find a list of [handlers of integrated javascripts you can de-register](https://codex.wordpress.org/Function_Reference/wp_register_script#Handles_and_Their_Script_Paths_Registered_by_WordPress).
As result you have to to deregister `jquery-core` instead of `jquery` to keep some of the functionalities intact, this includes plugins they might some legacy jQuery stuff to run.
You don't need to append "false" at the last argument since it's already false by default, I also suggest to drop your protocol, this ensures jQuery will be always served to the browser if you want to switch to https at a later time.
As a final touch, namespacing is very important when you are coding in a big environment where other's people code runs along with yours. `add_scripts()` seems a bit too generic for me, if you are writing your function inside the `functions.php` file try to add the name of your theme, or write something very unique so you are sure the same function doesn't get collide in the future with a function coming from a plugin or something else in your working files.
```
add_action( 'wp_enqueue_scripts', 'YOURTHEMENAME_scripts' );
function YOURTHEMENAME_scripts() {
wp_deregister_script('jquery-core');
wp_register_script('jquery-core', '//ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js', false, '2.1.0');
wp_enqueue_script('jquery-core');
}
```
Please note that the loading order of Wordpress is the following:
```
Core -> Plugins -> Theme
```
If you are trying to de-register jQuery from a custom plugin then possibly your theme is taking over and messing around with the scripts queue.
If after all of this you're still getting the Javascript into the footer then there's something horribly wrong going on into your `header.php` or `footer.php` files: one of the rookie reasons could be the location of `wp_head()` and `wp_footer()` specific hooks in your theme, I've seen this so many times which it could be easily a possibility.
`wp_head()` is a hook which adds for you meta tags, the css queue and the js queue with the last flag argument set to "false".
`wp_footer()` is the hook which cares about adding to you the rest of the JS with the last flag argument set to "true" and extra markup generated from various plugins (and for the admin bar from the WP core).
Do a double check about the location of your hook functions, if you have `wp_head()` in your footer then it could be easily the reason why your javascript queue is being added to the footer.
|
207,990 |
<p>I'm looking for a hook that can be used before WP reads the DB to authenticate the user's login credentials, but can't seem to find one anywhere. Does one exist?</p>
<p>I tried <code>add_filter/action('authenticate', 'customcode', 30, 3)</code>, but this seems to execute as soon as the <code>wp-login.php</code> page is requested, rather than after the user hits login and the username/password is <code>POST</code>.</p>
|
[
{
"answer_id": 207998,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": false,
"text": "<p>If you look at the code for <code>wp-login.php</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-login.php#L777\" rel=\"noreferrer\">both the <code>login</code> case and the default case</a> run <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-login.php#L806\" rel=\"noreferrer\"><code>wp_signon()</code></a>. The reason, so it seems to me, is to manage cases where a user already has a valid cookie for the site. So I don't think there is a hook that fires only upon login, but it is pretty easy to compensate. The first hook along that login path and before authentication is the action hook <code>wp_authenticate</code> not <code>authenticate</code> (though that is a valid hook).</p>\n\n<pre><code>function customcode($username, $password ) {\n if (!empty($username) && !empty($password)) {\n // your code\n }\n}\nadd_action('wp_authenticate', 'customcode', 30, 2);\n</code></pre>\n"
},
{
"answer_id": 208030,
"author": "Ken",
"author_id": 83223,
"author_profile": "https://wordpress.stackexchange.com/users/83223",
"pm_score": 3,
"selected": true,
"text": "<p>Ah, turns out <code>add_filter/action('authenticate', 'customcode', 30, 3)</code> was what I was looking for...</p>\n\n<p>The problem was, I had the priority too low so whatever response I was creating with my custom code was over-ridden by the other filters.</p>\n\n<p>So dumping <code>global $wp_filter['authenticate']</code> I could see the following filters:</p>\n\n<pre><code>20, wp_authenticate_username_password\n30, wp_authenticate_cookie\n99, wp_authenticate_spam_check\n</code></pre>\n\n<p>By changing the priority to 100 (or higher), I could do the overriding instead and create the response I wanted for handling the login credentials submitted via the login page.</p>\n"
}
] |
2015/11/08
|
[
"https://wordpress.stackexchange.com/questions/207990",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83223/"
] |
I'm looking for a hook that can be used before WP reads the DB to authenticate the user's login credentials, but can't seem to find one anywhere. Does one exist?
I tried `add_filter/action('authenticate', 'customcode', 30, 3)`, but this seems to execute as soon as the `wp-login.php` page is requested, rather than after the user hits login and the username/password is `POST`.
|
Ah, turns out `add_filter/action('authenticate', 'customcode', 30, 3)` was what I was looking for...
The problem was, I had the priority too low so whatever response I was creating with my custom code was over-ridden by the other filters.
So dumping `global $wp_filter['authenticate']` I could see the following filters:
```
20, wp_authenticate_username_password
30, wp_authenticate_cookie
99, wp_authenticate_spam_check
```
By changing the priority to 100 (or higher), I could do the overriding instead and create the response I wanted for handling the login credentials submitted via the login page.
|
207,996 |
<p>I have this simple javascript file for checking boxes in a tree view menu:</p>
<h2>treeview.js</h2>
<pre><code>$(".acidjs-css3-treeview").delegate("label input:checkbox", "change", function() {
var
checkbox = $(this),
selectNestedListCheckbox = checkbox.parents("li").children("label").children("input"),
siblingCheckboxes = checkbox.parentsUntil("ul","li").children("label").children("input");
if(checkbox.is(":checked")) {
return selectNestedListCheckbox.prop("checked", true);
}
selectNestedListCheckbox.prop("checked", false);
});
</code></pre>
<p>I have this as my WP template file:</p>
<h2>template</h2>
<pre><code>get_header(); ?>
<?php
//create right sidebar template
kleo_switch_layout('right');
?>
<?php get_template_part('page-parts/general-title-section'); ?>
<?php get_template_part('page-parts/general-before-wrap'); ?>
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post(); ?>
<!-- Begin the Treeview menu -->
<form method="get" action="<?php bloginfo('url'); ?>">
<div class="form-group">
<input class="form-control" type="text" name="s" value="" placeholder="Search…" maxlength="50" required="required" />
</div>
<p>Refine search to posts containing chosen tags:</p>
<div class="acidjs-css3-treeview">
<ul>
<li><input type="checkbox" id="node-0" /><label><input type="checkbox" name="tag[]" value="node-0" /><span></span></label><label for="node-0">node-0</label>
<ul>
<li><input type="checkbox" id="node-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0" /><span></span></label><label for="node-0-0">node-0-0</label>
<ul>
<li><input type="checkbox" id="node-0-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0-0" /><span></span></label><label for="node-0-0-0">node-0-0-0</label></li>
<li><input type="checkbox" id="node-0-0-1" /><label><input type="checkbox" name="tag[]" value="node-0-0-1" /><span></span></label><label for="node-0-0-1">node-0-0-1</label></li>
</ul>
</li>
</ul>
</li>
<li><input type="checkbox" id="node-1" /><label><input type="checkbox" name="tag[]" value="node-1" /><span></span></label><label for="node-1">node-1</label>
<ul>
<li><input type="checkbox" id="node-1-0" /><label><input type="checkbox" name="tag[]" value="node-1-0" /><span></span></label><label for="node-1-0">node-1-0</label>
<ul>
<li><input type="checkbox" id="node-1-0-0" /><label><input type="checkbox" name="tag[]" value="node-1-0-0" /><span></span></label><label for="node-1-0-0">node-1-0-0</label></li>
<li><input type="checkbox" id="node-1-0-1" /><label><input type="checkbox" name="tag[]" value="node-1-0-1" /><span></span></label><label for="node-1-0-1">node-1-0-1</label></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- End the Treeview menu -->
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
<?php
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_template_directory_uri() . '-child/assets/js/treeview.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>
<?php
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', 'page' );
?>
<?php get_template_part( 'page-parts/posts-social-share' ); ?>
<?php if ( sq_option( 'page_comments', 0 ) == 1 ): ?>
<!-- Begin Comments -->
<?php comments_template( '', true ); ?>
<!-- End Comments -->
<?php endif; ?>
<?php endwhile;
endif;
?>
<?php get_template_part('page-parts/general-after-wrap'); ?>
<?php get_footer(); ?>
</code></pre>
<p>The idea of this template is to allow the user to do a search based on a search term, and select multiple tags to filter the results.</p>
<p>I have a tree view menu setup, so that if the user selects a child tag, it would automatically select all of its ancestors as well.</p>
<p><a href="http://jsfiddle.net/davellan/uzufpjke/2/" rel="nofollow noreferrer">Here is a jFiddle of what the menu would look and function like ideally.</a></p>
<h2>Problems</h2>
<ol>
<li>The javascript is not executing, so the ancestors are not being checked when a child is checked.</li>
<li>The search is not functioning properly. It returns a query string as such:</li>
</ol>
<blockquote>
<p>The URL would show <a href="http://example.com/?s=searchterm&tag[]=key-word1&tag[]=key-word2" rel="nofollow noreferrer">http://example.com/?s=searchterm&tag[]=key-word1&tag[]=key-word2</a></p>
</blockquote>
<p>This would result in the tags not being filtered. <a href="https://wordpress.stackexchange.com/questions/199240/allow-visitors-to-search-by-multiple-tags-specific-ids">I found this particular code for searching multiple tags here.</a> That link seems to suggest this won't work until WP 4.4 comes around. Any way of getting this working under current WP 4.3.1?</p>
|
[
{
"answer_id": 207998,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": false,
"text": "<p>If you look at the code for <code>wp-login.php</code> <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-login.php#L777\" rel=\"noreferrer\">both the <code>login</code> case and the default case</a> run <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-login.php#L806\" rel=\"noreferrer\"><code>wp_signon()</code></a>. The reason, so it seems to me, is to manage cases where a user already has a valid cookie for the site. So I don't think there is a hook that fires only upon login, but it is pretty easy to compensate. The first hook along that login path and before authentication is the action hook <code>wp_authenticate</code> not <code>authenticate</code> (though that is a valid hook).</p>\n\n<pre><code>function customcode($username, $password ) {\n if (!empty($username) && !empty($password)) {\n // your code\n }\n}\nadd_action('wp_authenticate', 'customcode', 30, 2);\n</code></pre>\n"
},
{
"answer_id": 208030,
"author": "Ken",
"author_id": 83223,
"author_profile": "https://wordpress.stackexchange.com/users/83223",
"pm_score": 3,
"selected": true,
"text": "<p>Ah, turns out <code>add_filter/action('authenticate', 'customcode', 30, 3)</code> was what I was looking for...</p>\n\n<p>The problem was, I had the priority too low so whatever response I was creating with my custom code was over-ridden by the other filters.</p>\n\n<p>So dumping <code>global $wp_filter['authenticate']</code> I could see the following filters:</p>\n\n<pre><code>20, wp_authenticate_username_password\n30, wp_authenticate_cookie\n99, wp_authenticate_spam_check\n</code></pre>\n\n<p>By changing the priority to 100 (or higher), I could do the overriding instead and create the response I wanted for handling the login credentials submitted via the login page.</p>\n"
}
] |
2015/11/08
|
[
"https://wordpress.stackexchange.com/questions/207996",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80327/"
] |
I have this simple javascript file for checking boxes in a tree view menu:
treeview.js
-----------
```
$(".acidjs-css3-treeview").delegate("label input:checkbox", "change", function() {
var
checkbox = $(this),
selectNestedListCheckbox = checkbox.parents("li").children("label").children("input"),
siblingCheckboxes = checkbox.parentsUntil("ul","li").children("label").children("input");
if(checkbox.is(":checked")) {
return selectNestedListCheckbox.prop("checked", true);
}
selectNestedListCheckbox.prop("checked", false);
});
```
I have this as my WP template file:
template
--------
```
get_header(); ?>
<?php
//create right sidebar template
kleo_switch_layout('right');
?>
<?php get_template_part('page-parts/general-title-section'); ?>
<?php get_template_part('page-parts/general-before-wrap'); ?>
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post(); ?>
<!-- Begin the Treeview menu -->
<form method="get" action="<?php bloginfo('url'); ?>">
<div class="form-group">
<input class="form-control" type="text" name="s" value="" placeholder="Search…" maxlength="50" required="required" />
</div>
<p>Refine search to posts containing chosen tags:</p>
<div class="acidjs-css3-treeview">
<ul>
<li><input type="checkbox" id="node-0" /><label><input type="checkbox" name="tag[]" value="node-0" /><span></span></label><label for="node-0">node-0</label>
<ul>
<li><input type="checkbox" id="node-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0" /><span></span></label><label for="node-0-0">node-0-0</label>
<ul>
<li><input type="checkbox" id="node-0-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0-0" /><span></span></label><label for="node-0-0-0">node-0-0-0</label></li>
<li><input type="checkbox" id="node-0-0-1" /><label><input type="checkbox" name="tag[]" value="node-0-0-1" /><span></span></label><label for="node-0-0-1">node-0-0-1</label></li>
</ul>
</li>
</ul>
</li>
<li><input type="checkbox" id="node-1" /><label><input type="checkbox" name="tag[]" value="node-1" /><span></span></label><label for="node-1">node-1</label>
<ul>
<li><input type="checkbox" id="node-1-0" /><label><input type="checkbox" name="tag[]" value="node-1-0" /><span></span></label><label for="node-1-0">node-1-0</label>
<ul>
<li><input type="checkbox" id="node-1-0-0" /><label><input type="checkbox" name="tag[]" value="node-1-0-0" /><span></span></label><label for="node-1-0-0">node-1-0-0</label></li>
<li><input type="checkbox" id="node-1-0-1" /><label><input type="checkbox" name="tag[]" value="node-1-0-1" /><span></span></label><label for="node-1-0-1">node-1-0-1</label></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- End the Treeview menu -->
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
<?php
function my_scripts_method() {
wp_enqueue_script(
'custom-script',
get_template_directory_uri() . '-child/assets/js/treeview.js',
array( 'jquery' )
);
}
add_action( 'wp_enqueue_scripts', 'my_scripts_method' );
?>
<?php
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', 'page' );
?>
<?php get_template_part( 'page-parts/posts-social-share' ); ?>
<?php if ( sq_option( 'page_comments', 0 ) == 1 ): ?>
<!-- Begin Comments -->
<?php comments_template( '', true ); ?>
<!-- End Comments -->
<?php endif; ?>
<?php endwhile;
endif;
?>
<?php get_template_part('page-parts/general-after-wrap'); ?>
<?php get_footer(); ?>
```
The idea of this template is to allow the user to do a search based on a search term, and select multiple tags to filter the results.
I have a tree view menu setup, so that if the user selects a child tag, it would automatically select all of its ancestors as well.
[Here is a jFiddle of what the menu would look and function like ideally.](http://jsfiddle.net/davellan/uzufpjke/2/)
Problems
--------
1. The javascript is not executing, so the ancestors are not being checked when a child is checked.
2. The search is not functioning properly. It returns a query string as such:
>
> The URL would show <http://example.com/?s=searchterm&tag[]=key-word1&tag[]=key-word2>
>
>
>
This would result in the tags not being filtered. [I found this particular code for searching multiple tags here.](https://wordpress.stackexchange.com/questions/199240/allow-visitors-to-search-by-multiple-tags-specific-ids) That link seems to suggest this won't work until WP 4.4 comes around. Any way of getting this working under current WP 4.3.1?
|
Ah, turns out `add_filter/action('authenticate', 'customcode', 30, 3)` was what I was looking for...
The problem was, I had the priority too low so whatever response I was creating with my custom code was over-ridden by the other filters.
So dumping `global $wp_filter['authenticate']` I could see the following filters:
```
20, wp_authenticate_username_password
30, wp_authenticate_cookie
99, wp_authenticate_spam_check
```
By changing the priority to 100 (or higher), I could do the overriding instead and create the response I wanted for handling the login credentials submitted via the login page.
|
208,001 |
<p>So I have a page template that is setup as follows <em>(using Kleo theme)</em>:</p>
<h2>Search template</h2>
<pre><code>get_header(); ?>
<?php
//create right sidebar template
kleo_switch_layout('right');
?>
<?php get_template_part('page-parts/general-title-section'); ?>
<?php get_template_part('page-parts/general-before-wrap'); ?>
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post(); ?>
<!-- Begin the Treeview menu -->
<form method="get" action="<?php bloginfo('url'); ?>">
<div class="form-group">
<input class="form-control" type="text" name="s" value="" placeholder="Search…" maxlength="50" required="required" />
</div>
<p>Refine search to posts containing chosen tags:</p>
<div class="acidjs-css3-treeview">
<ul>
<li><input type="checkbox" id="node-0" /><label><input type="checkbox" name="tag[]" value="node-0" /><span></span></label><label for="node-0">node-0</label>
<ul>
<li><input type="checkbox" id="node-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0" /><span></span></label><label for="node-0-0">node-0-0</label>
<ul>
<li><input type="checkbox" id="node-0-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0-0" /><span></span></label><label for="node-0-0-0">node-0-0-0</label></li>
<li><input type="checkbox" id="node-0-0-1" /><label><input type="checkbox" name="tag[]" value="node-0-0-1" /><span></span></label><label for="node-0-0-1">node-0-0-1</label></li>
</ul>
</li>
</ul>
</li>
<li><input type="checkbox" id="node-1" /><label><input type="checkbox" name="tag[]" value="node-1" /><span></span></label><label for="node-1">node-1</label>
<ul>
<li><input type="checkbox" id="node-1-0" /><label><input type="checkbox" name="tag[]" value="node-1-0" /><span></span></label><label for="node-1-0">node-1-0</label>
<ul>
<li><input type="checkbox" id="node-1-0-0" /><label><input type="checkbox" name="tag[]" value="node-1-0-0" /><span></span></label><label for="node-1-0-0">node-1-0-0</label></li>
<li><input type="checkbox" id="node-1-0-1" /><label><input type="checkbox" name="tag[]" value="node-1-0-1" /><span></span></label><label for="node-1-0-1">node-1-0-1</label></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- End the Treeview menu -->
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
<?php
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', 'page' );
?>
<?php get_template_part( 'page-parts/posts-social-share' ); ?>
<?php if ( sq_option( 'page_comments', 0 ) == 1 ): ?>
<!-- Begin Comments -->
<?php comments_template( '', true ); ?>
<!-- End Comments -->
<?php endif; ?>
<?php endwhile;
endif;
?>
<?php get_template_part('page-parts/general-after-wrap'); ?>
<?php get_footer(); ?>
</code></pre>
<h1>Problem</h1>
<p>The search is not functioning properly. It returns a query string as such:</p>
<blockquote>
<p>The URL would show <a href="http://example.com/?s=searchterm&tag[]=key-word1&tag[]=key-word2" rel="nofollow noreferrer">http://example.com/?s=searchterm&tag[]=key-word1&tag[]=key-word2</a></p>
</blockquote>
<p>This would result in the tags not being filtered. </p>
<p>I can edit the [] out to make the tag search work, but then I would only be searching the last tag element in the GET, which defeats the purpose.</p>
<p><a href="https://wordpress.stackexchange.com/questions/199240/allow-visitors-to-search-by-multiple-tags-specific-ids">I was inspired to do this particular code for searching multiple tags on this question here.</a> That link seems to suggest this won't work until WP 4.4 comes around. Any way of getting this working under current WP 4.3.1?</p>
|
[
{
"answer_id": 208049,
"author": "David Avellan",
"author_id": 80327,
"author_profile": "https://wordpress.stackexchange.com/users/80327",
"pm_score": 2,
"selected": true,
"text": "<p>Well, I got it working by making my own own parse php as follows:</p>\n<h2>parse.php</h2>\n<pre><code><?php\n\n$tags = $_POST['tag'];\n$search = $_POST['s'];\n$count = count($tags);\n\n$i = 0;\nif(!empty($search))\n $uri = "https://example.com/?s=$search&";\nelse\n $uri = "https://example.com/?tag=";\nforeach($tags as $name=>$value) {\n ++$i;\n if($i !== $count)\n $uri .= $value."+";\n else\n $uri .= $value;\n}\n\nheader("Location: $uri");\nexit;\n?>\n</code></pre>\n<p>And of course, changing the original form action to point to parse.php and the method to POST.</p>\n<p>Probably not the best way of doing this, but for now it works. If someone can give me a better or cleaner answer, please do.</p>\n"
},
{
"answer_id": 254492,
"author": "kamiel verwer",
"author_id": 111942,
"author_profile": "https://wordpress.stackexchange.com/users/111942",
"pm_score": 0,
"selected": false,
"text": "<p>I'm having the same problem. After going through hooks (pre_get_posts doesn't do the job) I decided to check for $SERVER in the template_include hook.\nsubstr($_SERVER['REQUEST_URI'],1) is the query string that we can parse. In my setup, tags are separated by a +sign in the pretty URL. All I do is str_replace that with ',' and feed it into, alas, a fresh query_post().</p>\n\n<p>This works at least with an URL like {domain}/cats+dogs+donkeys by just filtering out any instance of + in the URL and doing a fresh query.</p>\n"
}
] |
2015/11/08
|
[
"https://wordpress.stackexchange.com/questions/208001",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80327/"
] |
So I have a page template that is setup as follows *(using Kleo theme)*:
Search template
---------------
```
get_header(); ?>
<?php
//create right sidebar template
kleo_switch_layout('right');
?>
<?php get_template_part('page-parts/general-title-section'); ?>
<?php get_template_part('page-parts/general-before-wrap'); ?>
<?php
if ( have_posts() ) :
// Start the Loop.
while ( have_posts() ) : the_post(); ?>
<!-- Begin the Treeview menu -->
<form method="get" action="<?php bloginfo('url'); ?>">
<div class="form-group">
<input class="form-control" type="text" name="s" value="" placeholder="Search…" maxlength="50" required="required" />
</div>
<p>Refine search to posts containing chosen tags:</p>
<div class="acidjs-css3-treeview">
<ul>
<li><input type="checkbox" id="node-0" /><label><input type="checkbox" name="tag[]" value="node-0" /><span></span></label><label for="node-0">node-0</label>
<ul>
<li><input type="checkbox" id="node-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0" /><span></span></label><label for="node-0-0">node-0-0</label>
<ul>
<li><input type="checkbox" id="node-0-0-0" /><label><input type="checkbox" name="tag[]" value="node-0-0-0" /><span></span></label><label for="node-0-0-0">node-0-0-0</label></li>
<li><input type="checkbox" id="node-0-0-1" /><label><input type="checkbox" name="tag[]" value="node-0-0-1" /><span></span></label><label for="node-0-0-1">node-0-0-1</label></li>
</ul>
</li>
</ul>
</li>
<li><input type="checkbox" id="node-1" /><label><input type="checkbox" name="tag[]" value="node-1" /><span></span></label><label for="node-1">node-1</label>
<ul>
<li><input type="checkbox" id="node-1-0" /><label><input type="checkbox" name="tag[]" value="node-1-0" /><span></span></label><label for="node-1-0">node-1-0</label>
<ul>
<li><input type="checkbox" id="node-1-0-0" /><label><input type="checkbox" name="tag[]" value="node-1-0-0" /><span></span></label><label for="node-1-0-0">node-1-0-0</label></li>
<li><input type="checkbox" id="node-1-0-1" /><label><input type="checkbox" name="tag[]" value="node-1-0-1" /><span></span></label><label for="node-1-0-1">node-1-0-1</label></li>
</ul>
</li>
</ul>
</li>
</ul>
</div>
<!-- End the Treeview menu -->
<input class="btn btn-primary" type="submit" value="Submit" />
</form>
<?php
/*
* Include the post format-specific template for the content. If you want to
* use this in a child theme, then include a file called called content-___.php
* (where ___ is the post format) and that will be used instead.
*/
get_template_part( 'content', 'page' );
?>
<?php get_template_part( 'page-parts/posts-social-share' ); ?>
<?php if ( sq_option( 'page_comments', 0 ) == 1 ): ?>
<!-- Begin Comments -->
<?php comments_template( '', true ); ?>
<!-- End Comments -->
<?php endif; ?>
<?php endwhile;
endif;
?>
<?php get_template_part('page-parts/general-after-wrap'); ?>
<?php get_footer(); ?>
```
Problem
=======
The search is not functioning properly. It returns a query string as such:
>
> The URL would show <http://example.com/?s=searchterm&tag[]=key-word1&tag[]=key-word2>
>
>
>
This would result in the tags not being filtered.
I can edit the [] out to make the tag search work, but then I would only be searching the last tag element in the GET, which defeats the purpose.
[I was inspired to do this particular code for searching multiple tags on this question here.](https://wordpress.stackexchange.com/questions/199240/allow-visitors-to-search-by-multiple-tags-specific-ids) That link seems to suggest this won't work until WP 4.4 comes around. Any way of getting this working under current WP 4.3.1?
|
Well, I got it working by making my own own parse php as follows:
parse.php
---------
```
<?php
$tags = $_POST['tag'];
$search = $_POST['s'];
$count = count($tags);
$i = 0;
if(!empty($search))
$uri = "https://example.com/?s=$search&";
else
$uri = "https://example.com/?tag=";
foreach($tags as $name=>$value) {
++$i;
if($i !== $count)
$uri .= $value."+";
else
$uri .= $value;
}
header("Location: $uri");
exit;
?>
```
And of course, changing the original form action to point to parse.php and the method to POST.
Probably not the best way of doing this, but for now it works. If someone can give me a better or cleaner answer, please do.
|
208,044 |
<p>My posts have a custom field named <em>production</em>_date and formatted YYYYMMDD.</p>
<p>How can I form a meta_query to select only the YYYY part?</p>
<pre><code>$meta_query_args = array(
array(
'key' => 'production_date',
'value' => '2004',
'compare' => '???'
)
);
</code></pre>
|
[
{
"answer_id": 208066,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": -1,
"selected": false,
"text": "<p>You could use PHP's <a href=\"http://it2.php.net/manual/en/function.date.php\" rel=\"nofollow\"><code>date</code></a> and <a href=\"http://it2.php.net/manual/en/function.strtotime.php\" rel=\"nofollow\"><code>strtotime</code></a> functions to get a year:</p>\n\n<pre><code>$date_value = '20040619'; // from your production_date custom field\n\n$year = date( 'Y', strtotime( $date_value ) );\n\n$meta_query_args = array(\n array(\n 'key' => 'production_date',\n 'value' => $year,\n 'compare' => '???'\n )\n);\n</code></pre>\n"
},
{
"answer_id": 208067,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 4,
"selected": true,
"text": "<p>The handy thing about how ACF stores dates as <code>YYYYMMDD</code> is you can treat them like integers and get a similar level of functionality as if you were using \"true\" dates.</p>\n\n<p>For example, to get all dates after 1st Jan 2011, use <code>> 20110101</code>. Those before June 1st 2012? <code>< 20120601</code>. And for your case, all dates within 2004? <code>>= 20040101 && <= 20041231</code>.</p>\n\n<p>Translated into a meta query:</p>\n\n<pre><code>$year = '2004';\n\n$meta_query_args = array(\n array(\n 'key' => 'production_date',\n 'value' => array( $year . '0101', $year . '1231' ),\n 'compare' => 'BETWEEN',\n 'type' => 'NUMERIC',\n )\n);\n</code></pre>\n\n<p><a href=\"https://codex.wordpress.org/Class_Reference/WP_Meta_Query\" rel=\"noreferrer\">Check out the codex</a> for a full explanation of all the arguments.</p>\n"
}
] |
2015/11/09
|
[
"https://wordpress.stackexchange.com/questions/208044",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1381/"
] |
My posts have a custom field named *production*\_date and formatted YYYYMMDD.
How can I form a meta\_query to select only the YYYY part?
```
$meta_query_args = array(
array(
'key' => 'production_date',
'value' => '2004',
'compare' => '???'
)
);
```
|
The handy thing about how ACF stores dates as `YYYYMMDD` is you can treat them like integers and get a similar level of functionality as if you were using "true" dates.
For example, to get all dates after 1st Jan 2011, use `> 20110101`. Those before June 1st 2012? `< 20120601`. And for your case, all dates within 2004? `>= 20040101 && <= 20041231`.
Translated into a meta query:
```
$year = '2004';
$meta_query_args = array(
array(
'key' => 'production_date',
'value' => array( $year . '0101', $year . '1231' ),
'compare' => 'BETWEEN',
'type' => 'NUMERIC',
)
);
```
[Check out the codex](https://codex.wordpress.org/Class_Reference/WP_Meta_Query) for a full explanation of all the arguments.
|
208,051 |
<p>Yes we love to make the url more shorter ,more clean.</p>
<p>Lets say we have css url like this</p>
<pre><code>xxx.com/wp-content/theme_name/css/my_custom_css.css
</code></pre>
<p>However i would love to display it like this</p>
<pre><code>xxx.com/css/my_custom_css.css
</code></pre>
<p>So i think rewriting is best choice.</p>
<p>I created a plugin made a new file rewrite.php and included the file and inserted code in rewrite.php like this in that </p>
<pre><code><?php
function my_rewrite_rules( $wp_rewrite ) {
$non_wp_rules = array(
'css/(.*)' => 'wp-content/themes/twentyfourteen/assets/css/$1',
'js/(.*)' => 'wp-content/themes/twentyfourteen/assets/js/$1',
);
$wp_rewrite->non_wp_rules = $non_wp_rules + $wp_rewrite->non_wp_rules;
}
function my_flush_rewrite_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action( 'init', 'my_flush_rewrite_rules');
add_action('generate_rewrite_rules', 'my_rewrite_rules');
?>
</code></pre>
<p>And I installed popular Rewrite analyzer . But i see no effect.</p>
<p>dunno where was the problem .</p>
<p>But when i use <code>$wp_rewrite->wp_rules</code> instead of <code>$wp_rewrite->non_wp_rules</code> It shows but obiously it is not what we want ??</p>
<p>Where is the problem :( this is actually creating too much problem :(</p>
<p>thanks :)</p>
|
[
{
"answer_id": 208069,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": true,
"text": "<p><strike>From <a href=\"https://wordpress.stackexchange.com/a/35118/20143\">this other answer on the WP SE</a></p>\n\n<pre><code>add_action('generate_rewrite_rules', 'roots_add_rewrites');\n\nfunction roots_add_rewrites($content) {\n $theme_name = next(explode('/themes/', get_stylesheet_directory()));\n global $wp_rewrite;\n $roots_new_non_wp_rules = array(\n 'css/(.*)' => 'wp-content/themes/'. $theme_name . '/css/$1',\n 'js/(.*)' => 'wp-content/themes/'. $theme_name . '/js/$1',\n 'img/(.*)' => 'wp-content/themes/'. $theme_name . '/img/$1',\n );\n $wp_rewrite->non_wp_rules += $roots_new_non_wp_rules;\n}\n</code></pre>\n\n<p></strike>\nTheDeadMedic provided a much better version of this function:</p>\n\n<pre><code>function wpse_208051_add_rewrites( $wp_rewrite ) {\n $path = str_replace( home_url( '/' ), '', get_template_directory_uri() );\n\n $wp_rewrite->non_wp_rules += array(\n 'css/(.*)' => $path . '/css/$1',\n 'js/(.*)' => $path . '/js/$1',\n 'img/(.*)' => $path . '/img/$1',\n );\n}\n\nadd_action( 'generate_rewrite_rules', 'wpse_208051_add_rewrites' );\n</code></pre>\n"
},
{
"answer_id": 208072,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>Following @phatskat's answer, this is what I would suggest. The biggest issue with the other solutions are the assumption of pathnames, which is a big no-no in WordPress development (especially those that are intended to be distributed to the public).</p>\n\n<pre><code>function wpse_208051_add_rewrites( $wp_rewrite ) {\n $path = str_replace( home_url( '/' ), '', get_template_directory_uri() );\n\n $wp_rewrite->non_wp_rules += array(\n 'css/(.*)' => $path . '/css/$1',\n 'js/(.*)' => $path . '/js/$1',\n 'img/(.*)' => $path . '/img/$1',\n );\n}\n\nadd_action( 'generate_rewrite_rules', 'wpse_208051_add_rewrites' );\n</code></pre>\n"
}
] |
2015/11/09
|
[
"https://wordpress.stackexchange.com/questions/208051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82119/"
] |
Yes we love to make the url more shorter ,more clean.
Lets say we have css url like this
```
xxx.com/wp-content/theme_name/css/my_custom_css.css
```
However i would love to display it like this
```
xxx.com/css/my_custom_css.css
```
So i think rewriting is best choice.
I created a plugin made a new file rewrite.php and included the file and inserted code in rewrite.php like this in that
```
<?php
function my_rewrite_rules( $wp_rewrite ) {
$non_wp_rules = array(
'css/(.*)' => 'wp-content/themes/twentyfourteen/assets/css/$1',
'js/(.*)' => 'wp-content/themes/twentyfourteen/assets/js/$1',
);
$wp_rewrite->non_wp_rules = $non_wp_rules + $wp_rewrite->non_wp_rules;
}
function my_flush_rewrite_rules() {
global $wp_rewrite;
$wp_rewrite->flush_rules();
}
add_action( 'init', 'my_flush_rewrite_rules');
add_action('generate_rewrite_rules', 'my_rewrite_rules');
?>
```
And I installed popular Rewrite analyzer . But i see no effect.
dunno where was the problem .
But when i use `$wp_rewrite->wp_rules` instead of `$wp_rewrite->non_wp_rules` It shows but obiously it is not what we want ??
Where is the problem :( this is actually creating too much problem :(
thanks :)
|
From [this other answer on the WP SE](https://wordpress.stackexchange.com/a/35118/20143)
```
add_action('generate_rewrite_rules', 'roots_add_rewrites');
function roots_add_rewrites($content) {
$theme_name = next(explode('/themes/', get_stylesheet_directory()));
global $wp_rewrite;
$roots_new_non_wp_rules = array(
'css/(.*)' => 'wp-content/themes/'. $theme_name . '/css/$1',
'js/(.*)' => 'wp-content/themes/'. $theme_name . '/js/$1',
'img/(.*)' => 'wp-content/themes/'. $theme_name . '/img/$1',
);
$wp_rewrite->non_wp_rules += $roots_new_non_wp_rules;
}
```
TheDeadMedic provided a much better version of this function:
```
function wpse_208051_add_rewrites( $wp_rewrite ) {
$path = str_replace( home_url( '/' ), '', get_template_directory_uri() );
$wp_rewrite->non_wp_rules += array(
'css/(.*)' => $path . '/css/$1',
'js/(.*)' => $path . '/js/$1',
'img/(.*)' => $path . '/img/$1',
);
}
add_action( 'generate_rewrite_rules', 'wpse_208051_add_rewrites' );
```
|
208,058 |
<p>I am trying to loop through custom post types and the code makes the page completely white but when I view source I can see my error:</p>
<pre><code>Parse error: syntax error, unexpected 'else' (T_ELSE)
</code></pre>
<p>Here is my code, I am not sure why this is breaking as it was copy and pasted from a tutorial, I have tried it in numerous different template files and I get the same error so the error is secluded to this hunk of code:</p>
<pre><code> <?
$args = array( 'post_type' => 'members_features', 'posts_per_page' => 6 );
$the_query = new WP_Query( $args );
?>
<? if ( $the_query->have_posts() ) : ?>
<? while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><? the_title(); ?></h2>
<div class="entry-content">
<? the_content(); ?>
</div>
<? wp_reset_postdata(); ?>
<? else: ?>
<p><? _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<? endif; ?>
</code></pre>
<p>The query recieves 1 row of data when I dump it and the query works fine, just the PHP notice is breaking my site, can any one help?</p>
|
[
{
"answer_id": 208069,
"author": "phatskat",
"author_id": 20143,
"author_profile": "https://wordpress.stackexchange.com/users/20143",
"pm_score": 1,
"selected": true,
"text": "<p><strike>From <a href=\"https://wordpress.stackexchange.com/a/35118/20143\">this other answer on the WP SE</a></p>\n\n<pre><code>add_action('generate_rewrite_rules', 'roots_add_rewrites');\n\nfunction roots_add_rewrites($content) {\n $theme_name = next(explode('/themes/', get_stylesheet_directory()));\n global $wp_rewrite;\n $roots_new_non_wp_rules = array(\n 'css/(.*)' => 'wp-content/themes/'. $theme_name . '/css/$1',\n 'js/(.*)' => 'wp-content/themes/'. $theme_name . '/js/$1',\n 'img/(.*)' => 'wp-content/themes/'. $theme_name . '/img/$1',\n );\n $wp_rewrite->non_wp_rules += $roots_new_non_wp_rules;\n}\n</code></pre>\n\n<p></strike>\nTheDeadMedic provided a much better version of this function:</p>\n\n<pre><code>function wpse_208051_add_rewrites( $wp_rewrite ) {\n $path = str_replace( home_url( '/' ), '', get_template_directory_uri() );\n\n $wp_rewrite->non_wp_rules += array(\n 'css/(.*)' => $path . '/css/$1',\n 'js/(.*)' => $path . '/js/$1',\n 'img/(.*)' => $path . '/img/$1',\n );\n}\n\nadd_action( 'generate_rewrite_rules', 'wpse_208051_add_rewrites' );\n</code></pre>\n"
},
{
"answer_id": 208072,
"author": "TheDeadMedic",
"author_id": 1685,
"author_profile": "https://wordpress.stackexchange.com/users/1685",
"pm_score": 1,
"selected": false,
"text": "<p>Following @phatskat's answer, this is what I would suggest. The biggest issue with the other solutions are the assumption of pathnames, which is a big no-no in WordPress development (especially those that are intended to be distributed to the public).</p>\n\n<pre><code>function wpse_208051_add_rewrites( $wp_rewrite ) {\n $path = str_replace( home_url( '/' ), '', get_template_directory_uri() );\n\n $wp_rewrite->non_wp_rules += array(\n 'css/(.*)' => $path . '/css/$1',\n 'js/(.*)' => $path . '/js/$1',\n 'img/(.*)' => $path . '/img/$1',\n );\n}\n\nadd_action( 'generate_rewrite_rules', 'wpse_208051_add_rewrites' );\n</code></pre>\n"
}
] |
2015/11/09
|
[
"https://wordpress.stackexchange.com/questions/208058",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83271/"
] |
I am trying to loop through custom post types and the code makes the page completely white but when I view source I can see my error:
```
Parse error: syntax error, unexpected 'else' (T_ELSE)
```
Here is my code, I am not sure why this is breaking as it was copy and pasted from a tutorial, I have tried it in numerous different template files and I get the same error so the error is secluded to this hunk of code:
```
<?
$args = array( 'post_type' => 'members_features', 'posts_per_page' => 6 );
$the_query = new WP_Query( $args );
?>
<? if ( $the_query->have_posts() ) : ?>
<? while ( $the_query->have_posts() ) : $the_query->the_post(); ?>
<h2><? the_title(); ?></h2>
<div class="entry-content">
<? the_content(); ?>
</div>
<? wp_reset_postdata(); ?>
<? else: ?>
<p><? _e( 'Sorry, no posts matched your criteria.' ); ?></p>
<? endif; ?>
```
The query recieves 1 row of data when I dump it and the query works fine, just the PHP notice is breaking my site, can any one help?
|
From [this other answer on the WP SE](https://wordpress.stackexchange.com/a/35118/20143)
```
add_action('generate_rewrite_rules', 'roots_add_rewrites');
function roots_add_rewrites($content) {
$theme_name = next(explode('/themes/', get_stylesheet_directory()));
global $wp_rewrite;
$roots_new_non_wp_rules = array(
'css/(.*)' => 'wp-content/themes/'. $theme_name . '/css/$1',
'js/(.*)' => 'wp-content/themes/'. $theme_name . '/js/$1',
'img/(.*)' => 'wp-content/themes/'. $theme_name . '/img/$1',
);
$wp_rewrite->non_wp_rules += $roots_new_non_wp_rules;
}
```
TheDeadMedic provided a much better version of this function:
```
function wpse_208051_add_rewrites( $wp_rewrite ) {
$path = str_replace( home_url( '/' ), '', get_template_directory_uri() );
$wp_rewrite->non_wp_rules += array(
'css/(.*)' => $path . '/css/$1',
'js/(.*)' => $path . '/js/$1',
'img/(.*)' => $path . '/img/$1',
);
}
add_action( 'generate_rewrite_rules', 'wpse_208051_add_rewrites' );
```
|
208,076 |
<p>I am currently trying to make a plugin which updates the stock count of my WooCommerce products.
So I wanted to access the wc_update_product_stock function, but an error got returned instead.</p>
<p>Code in plugin php file:</p>
<blockquote>
<p>wc_update_product_stock($id,$stock);</p>
</blockquote>
<p>error in log:</p>
<blockquote>
<p>Fatal error: Call to undefined function wc_update_product_stock()</p>
</blockquote>
<p>I read somewhere, that a normal call of all WC functions should be possible, if the WooCommerce Plugin is activated.</p>
<p><strong>Update:</strong></p>
<p>I tried your code inside a function as Scriptonomy suggested</p>
<blockquote>
<pre><code> function updateWCProduct($product)
{
$wcproduct = new WC_Product($product->get_id());
var_dump($wcproduct);
$wcproduct->set_stock($product->get_stock(),'set');
$wcproduct->set_price($product->get_price());
}
</code></pre>
</blockquote>
<p>but I get a empty product object back</p>
<blockquote>
<p>object(WC_Product)#9573 (5) { ["id"]=> int(9834) ["post"]=><br>
NULL ["product_type"]=> NULL ["shipping_class":protected]=><br>
string(0) "" ["shipping_class_id":protected]=> int(0) }</p>
</blockquote>
<p><strong>Update:</strong>
To get the product by sku use the code here:
<a href="https://www.skyverge.com/blog/find-product-sku-woocommerce/" rel="nofollow">https://www.skyverge.com/blog/find-product-sku-woocommerce/</a></p>
|
[
{
"answer_id": 208078,
"author": "akasapriya",
"author_id": 82007,
"author_profile": "https://wordpress.stackexchange.com/users/82007",
"pm_score": 2,
"selected": true,
"text": "<p>If you've already invoked the product, e.g. with</p>\n\n<p><code>$product = new WC_Product($id);</code></p>\n\n<p>then you can update the stock level with </p>\n\n<p><code>$product->set_stock($stock);</code></p>\n\n<p>For more information check the documentation:</p>\n\n<p><a href=\"https://docs.woothemes.com/wc-apidocs/class-WC_Product.html#_set_stock\" rel=\"nofollow\">https://docs.woothemes.com/wc-apidocs/class-WC_Product.html#_set_stock</a></p>\n"
},
{
"answer_id": 208079,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 2,
"selected": false,
"text": "<p>The Woocommerce plugin must be loaded and initiated before you can call any functions of the sort.</p>\n\n<p>Hook onto the <code>woocommerce_init</code> action and execute your code there.</p>\n\n<p><code>add_action( 'woocommerce_init', 'callback');</code></p>\n"
}
] |
2015/11/09
|
[
"https://wordpress.stackexchange.com/questions/208076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83278/"
] |
I am currently trying to make a plugin which updates the stock count of my WooCommerce products.
So I wanted to access the wc\_update\_product\_stock function, but an error got returned instead.
Code in plugin php file:
>
> wc\_update\_product\_stock($id,$stock);
>
>
>
error in log:
>
> Fatal error: Call to undefined function wc\_update\_product\_stock()
>
>
>
I read somewhere, that a normal call of all WC functions should be possible, if the WooCommerce Plugin is activated.
**Update:**
I tried your code inside a function as Scriptonomy suggested
>
>
> ```
> function updateWCProduct($product)
> {
> $wcproduct = new WC_Product($product->get_id());
> var_dump($wcproduct);
> $wcproduct->set_stock($product->get_stock(),'set');
> $wcproduct->set_price($product->get_price());
> }
>
> ```
>
>
but I get a empty product object back
>
> object(WC\_Product)#9573 (5) { ["id"]=> int(9834) ["post"]=>
>
> NULL ["product\_type"]=> NULL ["shipping\_class":protected]=>
>
> string(0) "" ["shipping\_class\_id":protected]=> int(0) }
>
>
>
**Update:**
To get the product by sku use the code here:
<https://www.skyverge.com/blog/find-product-sku-woocommerce/>
|
If you've already invoked the product, e.g. with
`$product = new WC_Product($id);`
then you can update the stock level with
`$product->set_stock($stock);`
For more information check the documentation:
<https://docs.woothemes.com/wc-apidocs/class-WC_Product.html#_set_stock>
|
208,094 |
<p>Ok, so we know Wordpress comes with a built in search form. However, I've created a custom archive page that lists posts from a specific post type. I would like to integrate a search box that only searches for posts related to that specific post.</p>
<p>I see a lot of people approaching this in several ways but no working examples. Any ideas how I could get this done?</p>
<p>Thanks!</p>
|
[
{
"answer_id": 208101,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 0,
"selected": false,
"text": "<p>You can edit the search form redirecting it to your custom archive page. Then, in the custom archive page code, you can detect when a search is triggered (either with $_POST or $_GET) and change the main query to include the search term. Something like this:</p>\n\n<p>Searchform:</p>\n\n<pre><code><form method=\"GET\" action=\"<?php echo get_post_type_archive_link( $post_type ); ?>\">\n <input name=\"s\" type=\"text\">\n <input type=\"submit\">\n</form>\n</code></pre>\n\n<p>Archive:</p>\n\n<pre><code><?php\nif (isset($_GET['s'])\n query_posts('s='. $_GET['s']);\n\nwhile ( have_posts() ) : the_post();\n //do stuff\nendwhile;\n?>\n</code></pre>\n"
},
{
"answer_id": 369180,
"author": "thenomadicmann",
"author_id": 179844,
"author_profile": "https://wordpress.stackexchange.com/users/179844",
"pm_score": 2,
"selected": false,
"text": "<p>To enable search on a custom post type archive, I use the <a href=\"https://developer.wordpress.org/reference/hooks/pre_get_posts/\" rel=\"nofollow noreferrer\">pre_get_posts</a> hook. Add this code to your theme functions.php file. Here is an example of enabling search on a post type called "resource":</p>\n<pre><code>// Enable resource search\n add_action('pre_get_posts','pk_enable_resource_search', 1000);\n function pk_enable_resource_search( $query ) {\n\n if ( $query->is_archive('resource') && $query->is_main_query() && ! is_admin() ) {\n\n $search = ! empty($_GET['rs']) ? $_GET['rs'] : false;\n\n //Check for custom search\n if($search) {\n $query->set( 's', $_GET['rs'] );\n }\n }\n }\n</code></pre>\n<p>Then on the archive page, you'll need to set up your search form:</p>\n<pre><code><form class="archive-resource__search-form" action="<?php echo get_post_type_archive_link('resource'); ?>">\n <input type="text" placeholder="Search Resources" value="<?php echo $search_term; ?>" name="rs">\n <button type="submit" class="far fa-search"></button>\n</form>\n</code></pre>\n<p>Lastly, don't forget to look for and set your search term on your archive page. Add these variables to the top of your search form template part/archive template:</p>\n<pre><code>$is_search = ! empty( $_GET['rs'] ) ? true : false;\n$search_term = $is_search ? $_GET['rs'] : '';\n</code></pre>\n"
}
] |
2015/11/09
|
[
"https://wordpress.stackexchange.com/questions/208094",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/21245/"
] |
Ok, so we know Wordpress comes with a built in search form. However, I've created a custom archive page that lists posts from a specific post type. I would like to integrate a search box that only searches for posts related to that specific post.
I see a lot of people approaching this in several ways but no working examples. Any ideas how I could get this done?
Thanks!
|
To enable search on a custom post type archive, I use the [pre\_get\_posts](https://developer.wordpress.org/reference/hooks/pre_get_posts/) hook. Add this code to your theme functions.php file. Here is an example of enabling search on a post type called "resource":
```
// Enable resource search
add_action('pre_get_posts','pk_enable_resource_search', 1000);
function pk_enable_resource_search( $query ) {
if ( $query->is_archive('resource') && $query->is_main_query() && ! is_admin() ) {
$search = ! empty($_GET['rs']) ? $_GET['rs'] : false;
//Check for custom search
if($search) {
$query->set( 's', $_GET['rs'] );
}
}
}
```
Then on the archive page, you'll need to set up your search form:
```
<form class="archive-resource__search-form" action="<?php echo get_post_type_archive_link('resource'); ?>">
<input type="text" placeholder="Search Resources" value="<?php echo $search_term; ?>" name="rs">
<button type="submit" class="far fa-search"></button>
</form>
```
Lastly, don't forget to look for and set your search term on your archive page. Add these variables to the top of your search form template part/archive template:
```
$is_search = ! empty( $_GET['rs'] ) ? true : false;
$search_term = $is_search ? $_GET['rs'] : '';
```
|
208,111 |
<p>I need to run <code>wp_enqueue</code> on javascript files after the DOM has been populated because I need to target a div. </p>
<p><strong>EDIT</strong></p>
<p>I am trying to add the following three scripts:</p>
<pre><code>wp_enqueue_script('react_js', '/scripts/react.min.js' );
wp_enqueue_script('startReact_js', '/scripts/test.js', array('react_js'), '', true);
wp_enqueue_script('app_js', '/scripts//App.js', array('startReact_js'), '', true);
</code></pre>
<p>The first one will load in the react source code, the second script will create a div on the page for the most parent react component to render in, and the last script will
load the most parent react component into said div.</p>
<p>I need the page to load before running the last script b/c React needs a DOM element to render into BUT I can't figure out how to load the script in the footer.</p>
<p>I can successfully add the script to the header. I have read that there is a $in_footer parameter. Every time I try adding my javascript to the footer using the $in_footer param, it disappears entirely from the DOM. Any thoughts?</p>
<p>@Blaine I tried adding the enqueue scripts to my functions.php per your example but I got the white screen of death. </p>
<pre><code>function addScriptsForEducatePage(){
if(is_page(5274)){
wp_enqueue_script('react_js', '/scripts/react.min.js' );
wp_enqueue_script('startReact_js', '/scripts/pages/test.js', array('react_js'), '', true);
wp_enqueue_script('app_js', '/scripts/pages/build/App.js', array('startReact_js'), '', true );
}
return;
}
add_action('wp_enqueue_scripts', 'addScriptsForEducatePage')
</code></pre>
<p>Any thoughts?</p>
|
[
{
"answer_id": 208172,
"author": "Blaine",
"author_id": 68877,
"author_profile": "https://wordpress.stackexchange.com/users/68877",
"pm_score": 1,
"selected": false,
"text": "<p>Have you looked at <a href=\"https://codex.wordpress.org/Function_Reference/wp_enqueue_script\" rel=\"nofollow\">wp_enqueue_script</a> in the WordPress codex? You'll most likely need to add this to <code>functions.php</code> in your theme's directory.</p>\n\n<p>Also, where are you enqueuing the <code>startapp_js</code> dependency?</p>\n\n<pre><code>function prefix_enqueue_scripts() {\n wp_enqueue_script( 'startapp-js', get_template_directory_uri() . '/scripts/Startapp.js', array(), '', true ); \n wp_enqueue_script( 'app-js', get_template_directory_uri() . '/scripts/App.js', array( 'startapp-js' ), '', true );\n}\nadd_action( 'wp_enqueue_scripts', 'prefix_enqueue_scripts' );\n</code></pre>\n"
},
{
"answer_id": 208239,
"author": "Jake.JS",
"author_id": 83013,
"author_profile": "https://wordpress.stackexchange.com/users/83013",
"pm_score": 0,
"selected": false,
"text": "<p>I got it! The footer parameter was not working because I did not have a <code><?php wp_footer(); ?></code> at the bottom of the page. We were using the footer <code><?php get_footer(); ?></code> which apparently works differently. I got the answer from the following post <a href=\"https://wordpress.stackexchange.com/questions/37960/cant-enqueue-scripts-in-the-footer?rq=1\">Can't enqueue scripts in the footer?</a>.</p>\n\n<p>I was able to keep the enqueue scripts in the original php page so there was no need for putting it in functions.php although I'm sure it would work.</p>\n\n<p>Big thanks everyone who helped out!</p>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83013/"
] |
I need to run `wp_enqueue` on javascript files after the DOM has been populated because I need to target a div.
**EDIT**
I am trying to add the following three scripts:
```
wp_enqueue_script('react_js', '/scripts/react.min.js' );
wp_enqueue_script('startReact_js', '/scripts/test.js', array('react_js'), '', true);
wp_enqueue_script('app_js', '/scripts//App.js', array('startReact_js'), '', true);
```
The first one will load in the react source code, the second script will create a div on the page for the most parent react component to render in, and the last script will
load the most parent react component into said div.
I need the page to load before running the last script b/c React needs a DOM element to render into BUT I can't figure out how to load the script in the footer.
I can successfully add the script to the header. I have read that there is a $in\_footer parameter. Every time I try adding my javascript to the footer using the $in\_footer param, it disappears entirely from the DOM. Any thoughts?
@Blaine I tried adding the enqueue scripts to my functions.php per your example but I got the white screen of death.
```
function addScriptsForEducatePage(){
if(is_page(5274)){
wp_enqueue_script('react_js', '/scripts/react.min.js' );
wp_enqueue_script('startReact_js', '/scripts/pages/test.js', array('react_js'), '', true);
wp_enqueue_script('app_js', '/scripts/pages/build/App.js', array('startReact_js'), '', true );
}
return;
}
add_action('wp_enqueue_scripts', 'addScriptsForEducatePage')
```
Any thoughts?
|
Have you looked at [wp\_enqueue\_script](https://codex.wordpress.org/Function_Reference/wp_enqueue_script) in the WordPress codex? You'll most likely need to add this to `functions.php` in your theme's directory.
Also, where are you enqueuing the `startapp_js` dependency?
```
function prefix_enqueue_scripts() {
wp_enqueue_script( 'startapp-js', get_template_directory_uri() . '/scripts/Startapp.js', array(), '', true );
wp_enqueue_script( 'app-js', get_template_directory_uri() . '/scripts/App.js', array( 'startapp-js' ), '', true );
}
add_action( 'wp_enqueue_scripts', 'prefix_enqueue_scripts' );
```
|
208,129 |
<p>How to hide/disable any plugin notices for non admin users in dashboard? Can you please help me with this? Thanks</p>
|
[
{
"answer_id": 208137,
"author": "Adrian Spiac",
"author_id": 26990,
"author_profile": "https://wordpress.stackexchange.com/users/26990",
"pm_score": 2,
"selected": false,
"text": "<p>The simplest way would be to hide the notifications via CSS, see below:</p>\n\n<pre><code> function hide_update_msg_non_admins(){\n if (!current_user_can( 'manage_options' )) { // non-admin users\n echo '<style>#setting-error-tgmpa>.updated settings-error notice is-dismissible, .update-nag, .updated { display: none; }</style>';\n }\n }\n add_action( 'admin_head', 'hide_update_msg_non_admins');\n</code></pre>\n\n<p>A more detailed answer can be found <a href=\"https://wordpress.stackexchange.com/questions/76503/remove-time-to-upgrade-message-from-dashboard\">here</a>.</p>\n"
},
{
"answer_id": 214581,
"author": "Zaheer Ahmad Khan",
"author_id": 85975,
"author_profile": "https://wordpress.stackexchange.com/users/85975",
"pm_score": 1,
"selected": false,
"text": "<p>You can try following piece of code in your functions.php</p>\n\n<pre>\nif ( current_user_can( 'manage_options' ) ) {\n} else {\necho \".update-nag , .error, .updated{ display:none; }\";\n}\n</pre>\n"
},
{
"answer_id": 325749,
"author": "Riccardo",
"author_id": 1210,
"author_profile": "https://wordpress.stackexchange.com/users/1210",
"pm_score": 0,
"selected": false,
"text": "<p>This works for me:</p>\n\n<pre><code>add_action('admin_head', 'admin_only_warnings');\n\nfunction admin_only_warnings() {\nif(is_admin() && !current_user_can('administrator') ) {\n echo '<style>\n <!-- add your classes/ids below -->\n .warning, .error, .updated {display:none !important;}\n } \n </style>';\n}\n}\n</code></pre>\n"
},
{
"answer_id": 348785,
"author": "Amit Kumar PRO",
"author_id": 173478,
"author_profile": "https://wordpress.stackexchange.com/users/173478",
"pm_score": 0,
"selected": false,
"text": "<p>Try this one</p>\n\n<pre><code>function am_disable_admin_notices() {\nglobal $wp_filter;\nif (!current_user_can( 'manage_options' )) {\n if (isset($wp_filter['user_admin_notices'])) {\n unset( $wp_filter['user_admin_notices']);\n }\n}\nadd_action( 'admin_print_scripts', 'am_disable_admin_notices' );\n</code></pre>\n"
},
{
"answer_id": 409506,
"author": "user3445598",
"author_id": 224901,
"author_profile": "https://wordpress.stackexchange.com/users/224901",
"pm_score": 0,
"selected": false,
"text": "<p>I found the best solution on Kingsta. I prefer do not interfere to admin CSS.</p>\n<p>// Hide dashboard update notifications for non-admin users\nfunction kinsta_hide_update_nag() {\nif ( ! current_user_can( 'update_core' ) ) {\nremove_action( 'admin_notices', 'update_nag', 3 );\n}\n}</p>\n<p>add_action('admin_menu','kinsta_hide_update_nag');</p>\n<p>Source:\n<a href=\"https://kinsta.com/knowledgebase/disable-wordpress-update-notification/\" rel=\"nofollow noreferrer\">https://kinsta.com/knowledgebase/disable-wordpress-update-notification/</a></p>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208129",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32573/"
] |
How to hide/disable any plugin notices for non admin users in dashboard? Can you please help me with this? Thanks
|
The simplest way would be to hide the notifications via CSS, see below:
```
function hide_update_msg_non_admins(){
if (!current_user_can( 'manage_options' )) { // non-admin users
echo '<style>#setting-error-tgmpa>.updated settings-error notice is-dismissible, .update-nag, .updated { display: none; }</style>';
}
}
add_action( 'admin_head', 'hide_update_msg_non_admins');
```
A more detailed answer can be found [here](https://wordpress.stackexchange.com/questions/76503/remove-time-to-upgrade-message-from-dashboard).
|
208,135 |
<p>I have a function to be run every 5 minutes.
I've referred following from the codex:</p>
<pre><code><?php wp_schedule_event(time(), 'hourly', 'my_schedule_hook', $args); ?>
</code></pre>
<p>I want to run this function just every 5 minuets regardless of when to start.
How can I this?</p>
<p>Also it says codex says cron will be run when a visitor visits to the site.
Is there any way to run the cron just as per minutes and not waiting for a visit?</p>
<p>let's say the following function should be run every 5 minutes then how can I do that using <code>wp_schedule_event()</code> or <code>wp_cron</code>?</p>
<pre><code>function run_evry_five_minutes(){
// codes go here
}
</code></pre>
|
[
{
"answer_id": 208141,
"author": "Andrew Welch",
"author_id": 17862,
"author_profile": "https://wordpress.stackexchange.com/users/17862",
"pm_score": 1,
"selected": false,
"text": "<p>I'm afraid that other than waiting for someone to visit your site which runs a function, the only other option is to set up a cron job on your server using something like this <a href=\"https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash\">https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash</a> or if you have a cpanel style interface on your server, sometimes there is a gui for setting this up.</p>\n"
},
{
"answer_id": 208152,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 2,
"selected": false,
"text": "<p>If your site does get heavy traffic then you could try using <code>set_transient()</code> to run it (very approximately) every 5 minutes, eg:</p>\n\n<pre><code>function run_every_five_minutes() {\n // Could probably do with some logic here to stop it running if just after running.\n // codes go here\n}\n\nif ( ! get_transient( 'every_5_minutes' ) ) {\n set_transient( 'every_5_minutes', true, 5 * MINUTE_IN_SECONDS );\n run_every_five_minutes();\n\n // It's better use a hook to call a function in the plugin/theme\n //add_action( 'init', 'run_every_five_minutes' );\n}\n</code></pre>\n"
},
{
"answer_id": 208167,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 0,
"selected": false,
"text": "<p>I have a possible solution using a schedule function and a recursive WP Ajax function.</p>\n\n<ol>\n<li>Create a schedule event of 60 minutes to run a function</li>\n<li>This function will trigger a recursive function using Ajax through <code>file_get_contents()</code></li>\n<li>The ajax function will have a counter on the database with a total number of 60 (for each minute inside the hour).</li>\n<li>This ajax function will check your counter to:</li>\n</ol>\n\n<p>If counter equal or higher than 60 it will reset counter and await for the next cron job. </p>\n\n<p>If counter multiple of 5 (so at each 5 minutes) it will execute your desired function</p>\n\n<p>And, besides the conditions, it will sleep for 59 seconds <code>sleep(59);</code> (assuming your function it's a quick one). After the sleep, it will trigger itself using <code>file_get_contents()</code>again.</p>\n\n<p>Important things to note:</p>\n\n<ol>\n<li>Create a way to interrupt the process (i.e. checking a value on the DB)</li>\n<li>Create a way to prevent 2 processes at same time</li>\n<li>On file_get_contents set the time limit on header to 2 or 3 seconds, otherwise the server may have various processes waiting for nothing</li>\n<li>You may want to use the <code>set_time_limit(90);</code> to try prevent server to break your function before the sleep</li>\n</ol>\n\n<p>It's a solution, not a good one, and it may get blocked by the server. Using an external cron you can set a simple function and the server will use resources on it once at each 5 minutes. Using this solution, the server will be using resources on it all the time.</p>\n"
},
{
"answer_id": 216121,
"author": "Johano Fierra",
"author_id": 68427,
"author_profile": "https://wordpress.stackexchange.com/users/68427",
"pm_score": 5,
"selected": false,
"text": "<p>You can create new schedule times via cron_schedules:</p>\n\n<pre><code>function my_cron_schedules($schedules){\n if(!isset($schedules[\"5min\"])){\n $schedules[\"5min\"] = array(\n 'interval' => 5*60,\n 'display' => __('Once every 5 minutes'));\n }\n if(!isset($schedules[\"30min\"])){\n $schedules[\"30min\"] = array(\n 'interval' => 30*60,\n 'display' => __('Once every 30 minutes'));\n }\n return $schedules;\n}\nadd_filter('cron_schedules','my_cron_schedules');\n</code></pre>\n\n<p>Now you can schedule your function:</p>\n\n<pre><code>wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);\n</code></pre>\n\n<p>To only schedule it once, wrap it in a function and check before running it:</p>\n\n<pre><code>$args = array(false);\nfunction schedule_my_cron(){\n wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);\n}\nif(!wp_next_scheduled('my_schedule_hook',$args)){\n add_action('init', 'schedule_my_cron');\n}\n</code></pre>\n\n<p>Note the $args parameter! Not specifying the $args parameter in wp_next_scheduled, but having $args for wp_schedule_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).</p>\n\n<p>Finally, create the actual function that you would like to run:</p>\n\n<pre><code>function my_schedule_hook(){\n // codes go here\n}\n</code></pre>\n\n<p>I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.</p>\n\n<p>So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.</p>\n\n<p>The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).</p>\n\n<p><a href=\"https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/\" rel=\"noreferrer\">Lucas Rolff</a> explains the problem and gives the solution in detail.</p>\n\n<p>As an alternative, you could use a free 3rd party service like <a href=\"https://uptimerobot.com/\" rel=\"noreferrer\">UptimeRobot</a> to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.</p>\n"
},
{
"answer_id": 216128,
"author": "Marco",
"author_id": 68416,
"author_profile": "https://wordpress.stackexchange.com/users/68416",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://wordpress.org/plugins/cronjob-scheduler/\" rel=\"nofollow\">Cronjob Scheduler</a> plugin allows you to run frequent tasks reliably and timely without anyone having to visit your site, all you need is at least 1 action and a Unix Crontab schedule.</p>\n\n<p>It's very easy to use, and very flexible. You create your own function, and define an action within it. Then you can choose your action from the plugin menu and fire it whenever you want.</p>\n"
},
{
"answer_id": 279078,
"author": "Mike",
"author_id": 52894,
"author_profile": "https://wordpress.stackexchange.com/users/52894",
"pm_score": 1,
"selected": false,
"text": "<p>@johano's answer correctly explains how to set up a custom interval for WP cron job.\nThe second question isn't answered though, which is how to run a cron every minute:</p>\n\n<ol>\n<li><p>In the file <code>wp-config.php</code>, add the following code:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre></li>\n<li><p>Add a cron job (<code>crontab -e</code> on unix/linux):</p>\n\n<pre><code>1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron\n</code></pre></li>\n</ol>\n\n<p>The first part (step 1) will disable WordPress internal cron job. The second part (step 2) will manually run WordPress cron job every minute.</p>\n\n<p>With @Johano's answer (how to run a task every 5 minutes) and mine (how to manually run the cron), you should be able to achieve your goal.</p>\n"
},
{
"answer_id": 295814,
"author": "Régis Ramillien",
"author_id": 138014,
"author_profile": "https://wordpress.stackexchange.com/users/138014",
"pm_score": 2,
"selected": false,
"text": "<p>You can trigger it in plugin activation instead of on each plugin call:\n \n\n<pre><code>//Add a utility function to handle logs more nicely.\nif ( ! function_exists('write_log')) {\n function write_log ( $log ) {\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 * Do not let plugin be accessed directly\n **/\nif ( ! defined( 'ABSPATH' ) ) {\n write_log( \"Plugin should not be accessed directly!\" );\n exit; // Exit if accessed directly\n}\n\n/**\n * -----------------------------------------------------------------------------------------------------------\n * Do not forget to trigger a system call to wp-cron page at least each 30mn.\n * Otherwise we cannot be sure that trigger will be called.\n * -----------------------------------------------------------------------------------------------------------\n * Linux command:\n * crontab -e\n * 30 * * * * wget http://<url>/wp-cron.php\n */\n\n/**\n * Add a custom schedule to wp.\n * @param $schedules array The existing schedules\n *\n * @return mixed The existing + new schedules.\n */\nfunction woocsp_schedules( $schedules ) {\n write_log(\"Creating custom schedule.\");\n if ( ! isset( $schedules[\"10s\"] ) ) {\n $schedules[\"10s\"] = array(\n 'interval' => 10,\n 'display' => __( 'Once every 10 seconds' )\n );\n }\n\n write_log(\"Custom schedule created.\");\n return $schedules;\n}\n\n//Add cron schedules filter with upper defined schedule.\nadd_filter( 'cron_schedules', 'woocsp_schedules' );\n\n//Custom function to be called on schedule triggered.\nfunction scheduleTriggered() {\n write_log( \"Scheduler triggered!\" );\n}\nadd_action( 'woocsp_cron_delivery', 'scheduleTriggered' );\n\n// Register an activation hook to perform operation only on plugin activation\nregister_activation_hook(__FILE__, 'woocsp_activation');\nfunction woocsp_activation() {\n write_log(\"Plugin activating.\");\n\n //Trigger our method on our custom schedule event.\n if ( ! wp_get_schedule( 'woocsp_cron_delivery' ) ) {\n wp_schedule_event( time(), '10s', 'woocsp_cron_delivery' );\n }\n\n write_log(\"Plugin activated.\");\n}\n\n// Deactivate scheduled events on plugin deactivation.\nregister_deactivation_hook(__FILE__, 'woocsp_deactivation');\nfunction woocsp_deactivation() {\n write_log(\"Plugin deactivating.\");\n\n //Remove our scheduled hook.\n wp_clear_scheduled_hook('woocsp_cron_delivery');\n\n write_log(\"Plugin deactivated.\");\n}\n</code></pre>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/69828/"
] |
I have a function to be run every 5 minutes.
I've referred following from the codex:
```
<?php wp_schedule_event(time(), 'hourly', 'my_schedule_hook', $args); ?>
```
I want to run this function just every 5 minuets regardless of when to start.
How can I this?
Also it says codex says cron will be run when a visitor visits to the site.
Is there any way to run the cron just as per minutes and not waiting for a visit?
let's say the following function should be run every 5 minutes then how can I do that using `wp_schedule_event()` or `wp_cron`?
```
function run_evry_five_minutes(){
// codes go here
}
```
|
You can create new schedule times via cron\_schedules:
```
function my_cron_schedules($schedules){
if(!isset($schedules["5min"])){
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Once every 5 minutes'));
}
if(!isset($schedules["30min"])){
$schedules["30min"] = array(
'interval' => 30*60,
'display' => __('Once every 30 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','my_cron_schedules');
```
Now you can schedule your function:
```
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
```
To only schedule it once, wrap it in a function and check before running it:
```
$args = array(false);
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
}
if(!wp_next_scheduled('my_schedule_hook',$args)){
add_action('init', 'schedule_my_cron');
}
```
Note the $args parameter! Not specifying the $args parameter in wp\_next\_scheduled, but having $args for wp\_schedule\_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).
Finally, create the actual function that you would like to run:
```
function my_schedule_hook(){
// codes go here
}
```
I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.
So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.
The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).
[Lucas Rolff](https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/) explains the problem and gives the solution in detail.
As an alternative, you could use a free 3rd party service like [UptimeRobot](https://uptimerobot.com/) to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.
|
208,149 |
<p>I tried to set up a custom post type in Wordpress, and everything worked just fine.</p>
<p>Until displaying a single post from my custom post type.
First it didn't automatically use the <code>single.php</code> (as it should), and then I tried to create a custom <code>single-{custom_post_type}.php</code> but it doesn't even use that one :/</p>
<p>I'm kind of confused now.</p>
<p><strong>//Edit:</strong> </p>
<p>Solved the problem. Just had to add <code>flush_rewrite_rules();</code> after register post type in functions.php</p>
<pre><code>register_post_type( 'communitydeals' , $args );
flush_rewrite_rules();
</code></pre>
|
[
{
"answer_id": 208141,
"author": "Andrew Welch",
"author_id": 17862,
"author_profile": "https://wordpress.stackexchange.com/users/17862",
"pm_score": 1,
"selected": false,
"text": "<p>I'm afraid that other than waiting for someone to visit your site which runs a function, the only other option is to set up a cron job on your server using something like this <a href=\"https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash\">https://stackoverflow.com/questions/878600/how-to-create-cronjob-using-bash</a> or if you have a cpanel style interface on your server, sometimes there is a gui for setting this up.</p>\n"
},
{
"answer_id": 208152,
"author": "bonger",
"author_id": 57034,
"author_profile": "https://wordpress.stackexchange.com/users/57034",
"pm_score": 2,
"selected": false,
"text": "<p>If your site does get heavy traffic then you could try using <code>set_transient()</code> to run it (very approximately) every 5 minutes, eg:</p>\n\n<pre><code>function run_every_five_minutes() {\n // Could probably do with some logic here to stop it running if just after running.\n // codes go here\n}\n\nif ( ! get_transient( 'every_5_minutes' ) ) {\n set_transient( 'every_5_minutes', true, 5 * MINUTE_IN_SECONDS );\n run_every_five_minutes();\n\n // It's better use a hook to call a function in the plugin/theme\n //add_action( 'init', 'run_every_five_minutes' );\n}\n</code></pre>\n"
},
{
"answer_id": 208167,
"author": "Bruno Cantuaria",
"author_id": 65717,
"author_profile": "https://wordpress.stackexchange.com/users/65717",
"pm_score": 0,
"selected": false,
"text": "<p>I have a possible solution using a schedule function and a recursive WP Ajax function.</p>\n\n<ol>\n<li>Create a schedule event of 60 minutes to run a function</li>\n<li>This function will trigger a recursive function using Ajax through <code>file_get_contents()</code></li>\n<li>The ajax function will have a counter on the database with a total number of 60 (for each minute inside the hour).</li>\n<li>This ajax function will check your counter to:</li>\n</ol>\n\n<p>If counter equal or higher than 60 it will reset counter and await for the next cron job. </p>\n\n<p>If counter multiple of 5 (so at each 5 minutes) it will execute your desired function</p>\n\n<p>And, besides the conditions, it will sleep for 59 seconds <code>sleep(59);</code> (assuming your function it's a quick one). After the sleep, it will trigger itself using <code>file_get_contents()</code>again.</p>\n\n<p>Important things to note:</p>\n\n<ol>\n<li>Create a way to interrupt the process (i.e. checking a value on the DB)</li>\n<li>Create a way to prevent 2 processes at same time</li>\n<li>On file_get_contents set the time limit on header to 2 or 3 seconds, otherwise the server may have various processes waiting for nothing</li>\n<li>You may want to use the <code>set_time_limit(90);</code> to try prevent server to break your function before the sleep</li>\n</ol>\n\n<p>It's a solution, not a good one, and it may get blocked by the server. Using an external cron you can set a simple function and the server will use resources on it once at each 5 minutes. Using this solution, the server will be using resources on it all the time.</p>\n"
},
{
"answer_id": 216121,
"author": "Johano Fierra",
"author_id": 68427,
"author_profile": "https://wordpress.stackexchange.com/users/68427",
"pm_score": 5,
"selected": false,
"text": "<p>You can create new schedule times via cron_schedules:</p>\n\n<pre><code>function my_cron_schedules($schedules){\n if(!isset($schedules[\"5min\"])){\n $schedules[\"5min\"] = array(\n 'interval' => 5*60,\n 'display' => __('Once every 5 minutes'));\n }\n if(!isset($schedules[\"30min\"])){\n $schedules[\"30min\"] = array(\n 'interval' => 30*60,\n 'display' => __('Once every 30 minutes'));\n }\n return $schedules;\n}\nadd_filter('cron_schedules','my_cron_schedules');\n</code></pre>\n\n<p>Now you can schedule your function:</p>\n\n<pre><code>wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);\n</code></pre>\n\n<p>To only schedule it once, wrap it in a function and check before running it:</p>\n\n<pre><code>$args = array(false);\nfunction schedule_my_cron(){\n wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);\n}\nif(!wp_next_scheduled('my_schedule_hook',$args)){\n add_action('init', 'schedule_my_cron');\n}\n</code></pre>\n\n<p>Note the $args parameter! Not specifying the $args parameter in wp_next_scheduled, but having $args for wp_schedule_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).</p>\n\n<p>Finally, create the actual function that you would like to run:</p>\n\n<pre><code>function my_schedule_hook(){\n // codes go here\n}\n</code></pre>\n\n<p>I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.</p>\n\n<p>So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.</p>\n\n<p>The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).</p>\n\n<p><a href=\"https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/\" rel=\"noreferrer\">Lucas Rolff</a> explains the problem and gives the solution in detail.</p>\n\n<p>As an alternative, you could use a free 3rd party service like <a href=\"https://uptimerobot.com/\" rel=\"noreferrer\">UptimeRobot</a> to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.</p>\n"
},
{
"answer_id": 216128,
"author": "Marco",
"author_id": 68416,
"author_profile": "https://wordpress.stackexchange.com/users/68416",
"pm_score": 1,
"selected": false,
"text": "<p>The <a href=\"https://wordpress.org/plugins/cronjob-scheduler/\" rel=\"nofollow\">Cronjob Scheduler</a> plugin allows you to run frequent tasks reliably and timely without anyone having to visit your site, all you need is at least 1 action and a Unix Crontab schedule.</p>\n\n<p>It's very easy to use, and very flexible. You create your own function, and define an action within it. Then you can choose your action from the plugin menu and fire it whenever you want.</p>\n"
},
{
"answer_id": 279078,
"author": "Mike",
"author_id": 52894,
"author_profile": "https://wordpress.stackexchange.com/users/52894",
"pm_score": 1,
"selected": false,
"text": "<p>@johano's answer correctly explains how to set up a custom interval for WP cron job.\nThe second question isn't answered though, which is how to run a cron every minute:</p>\n\n<ol>\n<li><p>In the file <code>wp-config.php</code>, add the following code:</p>\n\n<pre><code>define('DISABLE_WP_CRON', true);\n</code></pre></li>\n<li><p>Add a cron job (<code>crontab -e</code> on unix/linux):</p>\n\n<pre><code>1 * * * * wget -q -O - http://example.com/wp-cron.php?doing_wp_cron\n</code></pre></li>\n</ol>\n\n<p>The first part (step 1) will disable WordPress internal cron job. The second part (step 2) will manually run WordPress cron job every minute.</p>\n\n<p>With @Johano's answer (how to run a task every 5 minutes) and mine (how to manually run the cron), you should be able to achieve your goal.</p>\n"
},
{
"answer_id": 295814,
"author": "Régis Ramillien",
"author_id": 138014,
"author_profile": "https://wordpress.stackexchange.com/users/138014",
"pm_score": 2,
"selected": false,
"text": "<p>You can trigger it in plugin activation instead of on each plugin call:\n \n\n<pre><code>//Add a utility function to handle logs more nicely.\nif ( ! function_exists('write_log')) {\n function write_log ( $log ) {\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 * Do not let plugin be accessed directly\n **/\nif ( ! defined( 'ABSPATH' ) ) {\n write_log( \"Plugin should not be accessed directly!\" );\n exit; // Exit if accessed directly\n}\n\n/**\n * -----------------------------------------------------------------------------------------------------------\n * Do not forget to trigger a system call to wp-cron page at least each 30mn.\n * Otherwise we cannot be sure that trigger will be called.\n * -----------------------------------------------------------------------------------------------------------\n * Linux command:\n * crontab -e\n * 30 * * * * wget http://<url>/wp-cron.php\n */\n\n/**\n * Add a custom schedule to wp.\n * @param $schedules array The existing schedules\n *\n * @return mixed The existing + new schedules.\n */\nfunction woocsp_schedules( $schedules ) {\n write_log(\"Creating custom schedule.\");\n if ( ! isset( $schedules[\"10s\"] ) ) {\n $schedules[\"10s\"] = array(\n 'interval' => 10,\n 'display' => __( 'Once every 10 seconds' )\n );\n }\n\n write_log(\"Custom schedule created.\");\n return $schedules;\n}\n\n//Add cron schedules filter with upper defined schedule.\nadd_filter( 'cron_schedules', 'woocsp_schedules' );\n\n//Custom function to be called on schedule triggered.\nfunction scheduleTriggered() {\n write_log( \"Scheduler triggered!\" );\n}\nadd_action( 'woocsp_cron_delivery', 'scheduleTriggered' );\n\n// Register an activation hook to perform operation only on plugin activation\nregister_activation_hook(__FILE__, 'woocsp_activation');\nfunction woocsp_activation() {\n write_log(\"Plugin activating.\");\n\n //Trigger our method on our custom schedule event.\n if ( ! wp_get_schedule( 'woocsp_cron_delivery' ) ) {\n wp_schedule_event( time(), '10s', 'woocsp_cron_delivery' );\n }\n\n write_log(\"Plugin activated.\");\n}\n\n// Deactivate scheduled events on plugin deactivation.\nregister_deactivation_hook(__FILE__, 'woocsp_deactivation');\nfunction woocsp_deactivation() {\n write_log(\"Plugin deactivating.\");\n\n //Remove our scheduled hook.\n wp_clear_scheduled_hook('woocsp_cron_delivery');\n\n write_log(\"Plugin deactivated.\");\n}\n</code></pre>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208149",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/76549/"
] |
I tried to set up a custom post type in Wordpress, and everything worked just fine.
Until displaying a single post from my custom post type.
First it didn't automatically use the `single.php` (as it should), and then I tried to create a custom `single-{custom_post_type}.php` but it doesn't even use that one :/
I'm kind of confused now.
**//Edit:**
Solved the problem. Just had to add `flush_rewrite_rules();` after register post type in functions.php
```
register_post_type( 'communitydeals' , $args );
flush_rewrite_rules();
```
|
You can create new schedule times via cron\_schedules:
```
function my_cron_schedules($schedules){
if(!isset($schedules["5min"])){
$schedules["5min"] = array(
'interval' => 5*60,
'display' => __('Once every 5 minutes'));
}
if(!isset($schedules["30min"])){
$schedules["30min"] = array(
'interval' => 30*60,
'display' => __('Once every 30 minutes'));
}
return $schedules;
}
add_filter('cron_schedules','my_cron_schedules');
```
Now you can schedule your function:
```
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
```
To only schedule it once, wrap it in a function and check before running it:
```
$args = array(false);
function schedule_my_cron(){
wp_schedule_event(time(), '5min', 'my_schedule_hook', $args);
}
if(!wp_next_scheduled('my_schedule_hook',$args)){
add_action('init', 'schedule_my_cron');
}
```
Note the $args parameter! Not specifying the $args parameter in wp\_next\_scheduled, but having $args for wp\_schedule\_event, will cause an almost infinite number of the same event to be scheduled (instead of just one).
Finally, create the actual function that you would like to run:
```
function my_schedule_hook(){
// codes go here
}
```
I think it is important to mention that wp-cron is checking the schedule and running due scheduled jobs each time a page is loaded.
So, if you have a low traffic website that only has 1 visitor an hour, wp-cron will only run when that visitor browses your site (once an hour). If your have a high traffic site with visitors requesting a page every second, wp-cron will be triggered every second causing extra load on the server.
The solution is to deactivate wp-cron and trigger it via a real cron job in the time interval of you fastest repeating scheduled wp-cron job (5 min in your case).
[Lucas Rolff](https://www.lucasrolff.com/wordpress/why-wp-cron-sucks/) explains the problem and gives the solution in detail.
As an alternative, you could use a free 3rd party service like [UptimeRobot](https://uptimerobot.com/) to query your site (and trigger wp-cron) every 5 minutes, if you do not want to deactivate wp-cron and trigger it via a real cron job.
|
208,154 |
<p>Happily coding along all of a sudden I realise my homepage is now showing blog posts and the setting to set a static home page is missing from the reading option (see screen shot).</p>
<p>In the database the option show_on_front was now magically set to posts as well. </p>
<p>Some people have said that it is because there are no pages or no public pages. However, I have pages which are also public. </p>
<p>I have done the following for the moment</p>
<pre><code>function force_static_page(){
update_option( 'show_on_front', 'page', true);
update_option( 'page_on_front', 28, true);
}
add_action('init', __NAMESPACE__ . '\\force_static_page');
</code></pre>
<p><a href="https://i.stack.imgur.com/nbFzw.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/nbFzw.jpg" alt="enter image description here"></a></p>
|
[
{
"answer_id": 242682,
"author": "Koen de Graaf",
"author_id": 104925,
"author_profile": "https://wordpress.stackexchange.com/users/104925",
"pm_score": 4,
"selected": false,
"text": "<p>I just had the same problem but fixed it quickly! :-)</p>\n\n<p>In my case, my homepage was on <em>draft</em>. Apparently, the settings then can't find the homepage anymore. It thinks it's gone and disables the option to set a default homepage.</p>\n\n<p>So turn on your homepage to visible. (also name it \"Home\") Hope it works for you!</p>\n\n<p>Cheers, Koen</p>\n"
},
{
"answer_id": 266899,
"author": "Jesse",
"author_id": 119670,
"author_profile": "https://wordpress.stackexchange.com/users/119670",
"pm_score": 3,
"selected": false,
"text": "<p>For me it was a simple fix - have at least 1 page published.</p>\n\n<p>For any theme developers out there, something to note is that the 'static_blog_page' section in the customizer will also disappear if users don't have at least 1 page published.</p>\n"
},
{
"answer_id": 295067,
"author": "user658182",
"author_id": 37934,
"author_profile": "https://wordpress.stackexchange.com/users/37934",
"pm_score": 1,
"selected": false,
"text": "<p>I an also confirm that this happens if a page is published, but set to private. I thought that doing a batch edit to make all pages private would give me a way to develop without the public seeing the pages. That's still possible, but for those settings to re-appear, one has to have at least 1 published page that is public.</p>\n"
},
{
"answer_id": 296318,
"author": "Nick Robinson",
"author_id": 138312,
"author_profile": "https://wordpress.stackexchange.com/users/138312",
"pm_score": 0,
"selected": false,
"text": "<p>A little late to the party I know, but I just had this error, I had a public, published page, but could set it as a static page.\nTurns out it was because I changed my timezone and this upset the page published date somehow (even though it was well in the past).\nI just reset the publish date and I was on my way!\ngood luck!</p>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208154",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17862/"
] |
Happily coding along all of a sudden I realise my homepage is now showing blog posts and the setting to set a static home page is missing from the reading option (see screen shot).
In the database the option show\_on\_front was now magically set to posts as well.
Some people have said that it is because there are no pages or no public pages. However, I have pages which are also public.
I have done the following for the moment
```
function force_static_page(){
update_option( 'show_on_front', 'page', true);
update_option( 'page_on_front', 28, true);
}
add_action('init', __NAMESPACE__ . '\\force_static_page');
```
[](https://i.stack.imgur.com/nbFzw.jpg)
|
I just had the same problem but fixed it quickly! :-)
In my case, my homepage was on *draft*. Apparently, the settings then can't find the homepage anymore. It thinks it's gone and disables the option to set a default homepage.
So turn on your homepage to visible. (also name it "Home") Hope it works for you!
Cheers, Koen
|
208,164 |
<p>I work a bit with the wordpress API and I want to try to include a <code><meta></code>-tag into my head area of my website.</p>
<p><strong>This is my code (<em>works everything fine!</em>):</strong></p>
<pre><code>class dmd_noindex_options_page{
function __construct() {
add_action( 'wp_head', array( $this, 'set_meta') );
}
function set_meta(){
$pages = get_option('dmd_noindex_pages');
$pages_id = explode(',', $pages);
for($i = 0; count($pages_id) > $i; $i++){
if(is_page($pages_id[$i])){
echo '<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">';
}
}
}
}
new dmd_noindex_options_page;
</code></pre>
<p><strong>My problem:</strong></p>
<p>I use the WP PlugIn Yoast SEO and if I take a look into my code of the website I see this above of my <code><meta></code>-tag.</p>
<pre><code><!-- This site is optimized with the Yoast SEO plugin v2.3.5 - https://yoast.com/wordpress/plugins/seo/ -->
<meta name="robots" content="noindex,follow"/>
<meta name="description" content="Impressum von EK Immobilien und Kontaktaufnahme"/>
<link rel="canonical" href="http://ek.dimadirekt.com/de/impressum/" />
<meta property="og:locale" content="de_DE" />
<meta property="og:type" content="article" />
<meta property="og:title" content="Impressum -" />
<meta property="og:description" content="Impressum von EK Immobilien und Kontaktaufnahme" />
<meta property="og:url" content="http://ek.dimadirekt.com/de/impressum/" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:description" content="Impressum von EK Immobilien und Kontaktaufnahme"/>
<meta name="twitter:title" content="Impressum -"/>
<!-- / Yoast SEO plugin. -->
</code></pre>
<p>I <strong>don't want</strong> deactivate this Yoast SEO PlugIn! I tried to set a higher priority of my <strong>add_action</strong> but that doesn't work.</p>
<p>E.g.:</p>
<pre><code>add_action( 'wp_head', array( $this, 'set_meta', 2,1) );
</code></pre>
<p><strong>My question is:</strong></p>
<p>How can I include my <code><meta></code>-tag above the <code><meta></code>-tags of the Yoast SEO Plugin?
Can I include my code first of all plugins?</p>
|
[
{
"answer_id": 208165,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I just skimmed through the <code>WPSEO_Frontend</code> class and found the <code>wpseo_robots</code> filter for the <em>meta robots content</em> string.</p>\n\n<p>You might try something like: </p>\n\n<pre><code>add_filter( 'wpseo_robots', function( $content )\n{\n // your logic here ...\n return $content; \n} );\n</code></pre>\n\n<p>to override the <em>robots meta content</em> from that plugin.</p>\n\n<p>ps: You should consider moving the <code>add_action</code> out of the class constructor. </p>\n"
},
{
"answer_id": 208166,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Including it higher is probably not the right thing that you want as you are most likely to enter an \"undefined functionality\" on google side when encountering conflicting tags.</p>\n\n<p>If you don't want the yoast SEO to output its tags you will need to find in its code how to disable or override the specific functionality.</p>\n\n<p>But probably the most robust thing you can do is disallow those pages in robots.txt instead of \"fighting\" with all the SEO plugins. You can use the do_robotstxt action for that. something like (taken from here <a href=\"https://vip.wordpress.com/documentation/vip-development-tips-tricks/robots-txt/\" rel=\"nofollow\">https://vip.wordpress.com/documentation/vip-development-tips-tricks/robots-txt/</a>)</p>\n\n<pre><code>function my_disallow_directory() {\n echo \"User-agent: *\" . PHP_EOL;\n echo \"Disallow: /path/to/your/directory/\" . PHP_EOL;\n}\nadd_action( 'do_robotstxt', 'my_disallow_directory' );\n</code></pre>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208164",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/78481/"
] |
I work a bit with the wordpress API and I want to try to include a `<meta>`-tag into my head area of my website.
**This is my code (*works everything fine!*):**
```
class dmd_noindex_options_page{
function __construct() {
add_action( 'wp_head', array( $this, 'set_meta') );
}
function set_meta(){
$pages = get_option('dmd_noindex_pages');
$pages_id = explode(',', $pages);
for($i = 0; count($pages_id) > $i; $i++){
if(is_page($pages_id[$i])){
echo '<META NAME="ROBOTS" CONTENT="NOINDEX, NOFOLLOW">';
}
}
}
}
new dmd_noindex_options_page;
```
**My problem:**
I use the WP PlugIn Yoast SEO and if I take a look into my code of the website I see this above of my `<meta>`-tag.
```
<!-- This site is optimized with the Yoast SEO plugin v2.3.5 - https://yoast.com/wordpress/plugins/seo/ -->
<meta name="robots" content="noindex,follow"/>
<meta name="description" content="Impressum von EK Immobilien und Kontaktaufnahme"/>
<link rel="canonical" href="http://ek.dimadirekt.com/de/impressum/" />
<meta property="og:locale" content="de_DE" />
<meta property="og:type" content="article" />
<meta property="og:title" content="Impressum -" />
<meta property="og:description" content="Impressum von EK Immobilien und Kontaktaufnahme" />
<meta property="og:url" content="http://ek.dimadirekt.com/de/impressum/" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:description" content="Impressum von EK Immobilien und Kontaktaufnahme"/>
<meta name="twitter:title" content="Impressum -"/>
<!-- / Yoast SEO plugin. -->
```
I **don't want** deactivate this Yoast SEO PlugIn! I tried to set a higher priority of my **add\_action** but that doesn't work.
E.g.:
```
add_action( 'wp_head', array( $this, 'set_meta', 2,1) );
```
**My question is:**
How can I include my `<meta>`-tag above the `<meta>`-tags of the Yoast SEO Plugin?
Can I include my code first of all plugins?
|
I just skimmed through the `WPSEO_Frontend` class and found the `wpseo_robots` filter for the *meta robots content* string.
You might try something like:
```
add_filter( 'wpseo_robots', function( $content )
{
// your logic here ...
return $content;
} );
```
to override the *robots meta content* from that plugin.
ps: You should consider moving the `add_action` out of the class constructor.
|
208,174 |
<p>Here's the situation. I needed to create a copy of the website online so that I could redesign it and collaborate with others to redo the content. Consequently: </p>
<ul>
<li>I copied a website (example.org) to test.example.org. (Copied the example.org folder entire via ssh command) </li>
<li>modified the wp-config file to connect to a new database. </li>
<li>The 4 parameters are definitely correct in wp-config. I can access the new db via chrome using the DB_host and Db_user and Db_password values I've input-ed into the wp-config. </li>
<li>Consequently, I know that the database itself is fine. Just something is creating a problem in the connection between WP and the DB. I have no idea what, and I've spent an hour trying to diagnose and solve it already. </li>
</ul>
<p>Please help! </p>
<p>Ps. The website is hosted on Dreamhost. Additionally, while I can access the DB manually, the dreamhost control panel shows that the database's size is unavailable. I don't know if this is simply because it has no data, or if this is indicative of some deeper issue. Google-Fu hasn't helped. </p>
|
[
{
"answer_id": 208165,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I just skimmed through the <code>WPSEO_Frontend</code> class and found the <code>wpseo_robots</code> filter for the <em>meta robots content</em> string.</p>\n\n<p>You might try something like: </p>\n\n<pre><code>add_filter( 'wpseo_robots', function( $content )\n{\n // your logic here ...\n return $content; \n} );\n</code></pre>\n\n<p>to override the <em>robots meta content</em> from that plugin.</p>\n\n<p>ps: You should consider moving the <code>add_action</code> out of the class constructor. </p>\n"
},
{
"answer_id": 208166,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Including it higher is probably not the right thing that you want as you are most likely to enter an \"undefined functionality\" on google side when encountering conflicting tags.</p>\n\n<p>If you don't want the yoast SEO to output its tags you will need to find in its code how to disable or override the specific functionality.</p>\n\n<p>But probably the most robust thing you can do is disallow those pages in robots.txt instead of \"fighting\" with all the SEO plugins. You can use the do_robotstxt action for that. something like (taken from here <a href=\"https://vip.wordpress.com/documentation/vip-development-tips-tricks/robots-txt/\" rel=\"nofollow\">https://vip.wordpress.com/documentation/vip-development-tips-tricks/robots-txt/</a>)</p>\n\n<pre><code>function my_disallow_directory() {\n echo \"User-agent: *\" . PHP_EOL;\n echo \"Disallow: /path/to/your/directory/\" . PHP_EOL;\n}\nadd_action( 'do_robotstxt', 'my_disallow_directory' );\n</code></pre>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208174",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83338/"
] |
Here's the situation. I needed to create a copy of the website online so that I could redesign it and collaborate with others to redo the content. Consequently:
* I copied a website (example.org) to test.example.org. (Copied the example.org folder entire via ssh command)
* modified the wp-config file to connect to a new database.
* The 4 parameters are definitely correct in wp-config. I can access the new db via chrome using the DB\_host and Db\_user and Db\_password values I've input-ed into the wp-config.
* Consequently, I know that the database itself is fine. Just something is creating a problem in the connection between WP and the DB. I have no idea what, and I've spent an hour trying to diagnose and solve it already.
Please help!
Ps. The website is hosted on Dreamhost. Additionally, while I can access the DB manually, the dreamhost control panel shows that the database's size is unavailable. I don't know if this is simply because it has no data, or if this is indicative of some deeper issue. Google-Fu hasn't helped.
|
I just skimmed through the `WPSEO_Frontend` class and found the `wpseo_robots` filter for the *meta robots content* string.
You might try something like:
```
add_filter( 'wpseo_robots', function( $content )
{
// your logic here ...
return $content;
} );
```
to override the *robots meta content* from that plugin.
ps: You should consider moving the `add_action` out of the class constructor.
|
208,181 |
<p>I want to add a custom template for a custom post (<code>'post_type' => 'matches'</code>).</p>
<p>I am writing a plugin.I keep my template in the <code>templates/fp-fixture-template.php</code> file.</p>
<p>Here is the function:</p>
<pre><code>function fixture_template( $template_path ) {
if ( get_post_type() == 'matches' ) {
if ( is_single() ) {
// checks if the file exists in the theme first,
// otherwise serve the file from the plugin
if ( $theme_file = locate_template( array ( 'fp-fixture-template.php' ) ) ) {
$template_path = $theme_file;
} else {
$template_path = plugin_dir_path( FILE )
. 'templates/fp-fixture-template.php';
}
}
}
return $template_path;
}
</code></pre>
<p>Here is the filter:</p>
<pre><code>add_filter( 'template_include', 'fixture_template');
</code></pre>
<p>Code in the <code>fp-fixture-template.php</code> file:</p>
<pre><code><?php
/*Template Name: Matches Template
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access
?>
<div id="primary">
<div id="content" role="main">
<?php
$mypost = array( 'post_type' => 'matches', );
$loop = new WP_Query( $mypost );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php endwhile; ?>
</div>
</div>
</code></pre>
|
[
{
"answer_id": 208182,
"author": "ville6000",
"author_id": 62041,
"author_profile": "https://wordpress.stackexchange.com/users/62041",
"pm_score": 3,
"selected": false,
"text": "<p>This plugin looks for <code>page_contact.php</code> from active theme's folder and uses plugin's <code>templates/page_contact.php</code> as a fallback.</p>\n\n<pre><code><?php\n/**\n * Plugin Name: Test Plugin\n */\n\nadd_filter( 'template_include', 'contact_page_template', 99 );\n\nfunction contact_page_template( $template ) {\n $file_name = 'page_contact.php';\n\n if ( is_page( 'contact' ) ) {\n if ( locate_template( $file_name ) ) {\n $template = locate_template( $file_name );\n } else {\n // Template not found in theme's folder, use plugin's template as a fallback\n $template = dirname( __FILE__ ) . '/templates/' . $file_name;\n }\n }\n\n return $template;\n}\n</code></pre>\n\n<p>Create page \"Contact\" and then <code>templates/page_contact.php</code> in your plugins folder. Now you should see your template content instead of normal template.</p>\n"
},
{
"answer_id": 385981,
"author": "jnhghy - Alexandru Jantea",
"author_id": 37181,
"author_profile": "https://wordpress.stackexchange.com/users/37181",
"pm_score": 0,
"selected": false,
"text": "<p>For my solution first of all you need to decide the type of the template you want to overwrite.\nSo let's look at the following example: you want to overwrite/customize the single template for your custom post type.</p>\n<ol>\n<li>First of all in your plugin create the custom folder and add the template to it.</li>\n<li>Filter the single template using:</li>\n</ol>\n<p><code>add_filter( 'single_template', 'load_custom_template', 10, 3 );</code></p>\n<ol start=\"3\">\n<li>Add your plugin's template:</li>\n</ol>\n<pre><code>\nfunction load_custom_template( $template, $type, $templates ) {\n foreach( $templates as $tlp ) {\n if ( file_exists( plugin_dir_path(__FILE__) . '{custom_folder}/' . $tlp ) ) {\n $template = plugin_dir_path(__FILE__) . '{custom_folder}/' . $tlp;\n }\n }\n\n return $template;\n}\n</code></pre>\n<p>*For different types of templates change the hook to <code>$type_template</code></p>\n<p>More information about the hook <a href=\"https://developer.wordpress.org/reference/hooks/type_template/\" rel=\"nofollow noreferrer\">here</a></p>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208181",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83330/"
] |
I want to add a custom template for a custom post (`'post_type' => 'matches'`).
I am writing a plugin.I keep my template in the `templates/fp-fixture-template.php` file.
Here is the function:
```
function fixture_template( $template_path ) {
if ( get_post_type() == 'matches' ) {
if ( is_single() ) {
// checks if the file exists in the theme first,
// otherwise serve the file from the plugin
if ( $theme_file = locate_template( array ( 'fp-fixture-template.php' ) ) ) {
$template_path = $theme_file;
} else {
$template_path = plugin_dir_path( FILE )
. 'templates/fp-fixture-template.php';
}
}
}
return $template_path;
}
```
Here is the filter:
```
add_filter( 'template_include', 'fixture_template');
```
Code in the `fp-fixture-template.php` file:
```
<?php
/*Template Name: Matches Template
*/
if ( ! defined( 'ABSPATH' ) ) exit; // Don't allow direct access
?>
<div id="primary">
<div id="content" role="main">
<?php
$mypost = array( 'post_type' => 'matches', );
$loop = new WP_Query( $mypost );
?>
<?php while ( $loop->have_posts() ) : $loop->the_post();?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<?php endwhile; ?>
</div>
</div>
```
|
This plugin looks for `page_contact.php` from active theme's folder and uses plugin's `templates/page_contact.php` as a fallback.
```
<?php
/**
* Plugin Name: Test Plugin
*/
add_filter( 'template_include', 'contact_page_template', 99 );
function contact_page_template( $template ) {
$file_name = 'page_contact.php';
if ( is_page( 'contact' ) ) {
if ( locate_template( $file_name ) ) {
$template = locate_template( $file_name );
} else {
// Template not found in theme's folder, use plugin's template as a fallback
$template = dirname( __FILE__ ) . '/templates/' . $file_name;
}
}
return $template;
}
```
Create page "Contact" and then `templates/page_contact.php` in your plugins folder. Now you should see your template content instead of normal template.
|
208,218 |
<p>We use the latest versions of WordPress with the Woocommerce plugin. I'm searching for the best way to apply jquery to custom post types such as WC. I have a lot of hooks already for Woocommerce, so for now I have added some jquery into a meta box that I have previously added to the edit.php page. For instance, I'm using jquery to click on the address buttons to display all the address fields and to hide the Refund button from non-admin users upon loading the page. I'm sure there must be a better apply jquery as I'm doing now below?</p>
<pre><code>add_action( 'add_meta_boxes', 'my_add_meta_boxes' );
function my_add_meta_boxes(){
add_meta_box(
'woocommerce-order-my-custom',
__( 'My Meta Box' ),
'order_my_custom',
'shop_order',
'side',
'default'
);
}
// Add fields to the metabox
function order_my_custom( $post ){
//<code omitted that places fields in meta box>
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(".edit_address").click();
$(".add-line-item").click();
});
</script>
<?php
}
</code></pre>
<p>I have used admin_enqueue_scripts to add my own common jquery functions, but what is the best way to add your own jquery to a specific post type?</p>
|
[
{
"answer_id": 208222,
"author": "Dan Wist",
"author_id": 83360,
"author_profile": "https://wordpress.stackexchange.com/users/83360",
"pm_score": 0,
"selected": false,
"text": "<p>You can use the get_current_screen() function...it returns an object that contains lots of useful information about the screen that you are viewing inside of wp-admin. </p>\n\n<p>For your purposes you'll want the post_type property of that object which will return the post type that the current admin screen is working with.</p>\n\n<pre><code><?\n$screen = get_current_screen();\nif ( $screen->post_type == \"ENTERYOURPOSTTYPE\" ) {\n?>\n <script>\n JAVASCRIPT HERE\n </script>\n\n<?\n}\n?>\n</code></pre>\n\n<p>In your specific example you'll want to add the javascript where I've indicated and then attach that function to the admin_head hook.</p>\n\n<pre><code>add_action( 'admin_head', 'woocommerce_admin_init' );\n\nfunction woocommerce_admin_init() {\n\n $screen = get_current_screen();\n\n if ( $screen->post_type == \"shop_order\" ) {\n ?>\n\n <script type=\"text/javascript\">\n jQuery(document).ready(function ($) {\n $(\".edit_address\").click();\n $(\".add-line-item\").click();\n });\n </script>\n\n <?php\n }\n\n}\n</code></pre>\n\n<p>Reference: <a href=\"http://codex.wordpress.org/Function_Reference/get_current_screen\" rel=\"nofollow\">http://codex.wordpress.org/Function_Reference/get_current_screen</a></p>\n"
},
{
"answer_id": 208226,
"author": "Robert Fitzpatrick",
"author_id": 83280,
"author_profile": "https://wordpress.stackexchange.com/users/83280",
"pm_score": 2,
"selected": true,
"text": "<p>The previous answer works good with my example above using this hook:</p>\n\n<pre><code>add_action( 'admin_head', 'woocommerce_admin_init' );\nfunction woocommerce_admin_init() {\n $screen = get_current_screen();\n if ( $screen->post_type == \"shop_order\" ) {\n ?>\n <script type=\"text/javascript\">\n jQuery(document).ready(function ($) {\n $(\".edit_address\").click();\n $(\".add-line-item\").click();\n });\n </script>\n <?php\n }\n}\n</code></pre>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208218",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83280/"
] |
We use the latest versions of WordPress with the Woocommerce plugin. I'm searching for the best way to apply jquery to custom post types such as WC. I have a lot of hooks already for Woocommerce, so for now I have added some jquery into a meta box that I have previously added to the edit.php page. For instance, I'm using jquery to click on the address buttons to display all the address fields and to hide the Refund button from non-admin users upon loading the page. I'm sure there must be a better apply jquery as I'm doing now below?
```
add_action( 'add_meta_boxes', 'my_add_meta_boxes' );
function my_add_meta_boxes(){
add_meta_box(
'woocommerce-order-my-custom',
__( 'My Meta Box' ),
'order_my_custom',
'shop_order',
'side',
'default'
);
}
// Add fields to the metabox
function order_my_custom( $post ){
//<code omitted that places fields in meta box>
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(".edit_address").click();
$(".add-line-item").click();
});
</script>
<?php
}
```
I have used admin\_enqueue\_scripts to add my own common jquery functions, but what is the best way to add your own jquery to a specific post type?
|
The previous answer works good with my example above using this hook:
```
add_action( 'admin_head', 'woocommerce_admin_init' );
function woocommerce_admin_init() {
$screen = get_current_screen();
if ( $screen->post_type == "shop_order" ) {
?>
<script type="text/javascript">
jQuery(document).ready(function ($) {
$(".edit_address").click();
$(".add-line-item").click();
});
</script>
<?php
}
}
```
|
208,225 |
<p>Looking for a reason why <code>get_post_meta()</code> doesn't work with <code>home.php</code>. From my reading I understand that it's a template and not a post or page, per "<a href="https://wordpress.stackexchange.com/questions/92285/custom-fields-wont-display-on-my-blog-page?lq=1">Custom fields won't display on my blog page</a>". The closest page I was able to find from searching was "<a href="https://wordpress.stackexchange.com/questions/152088/get-post-meta-fields-dont-show-up-on-posts-page">get_post_meta fields don't show up on posts page</a>" but alas the answer doesn't go into detail why. I have coded a custom meta box, it works, for the <code>front_page.php</code> and all custom post types but not within <code>home.php</code>. I am using a conditional <code>is_home()</code> and it works but it seems <code>get_the_ID()</code> doesn't, the code:</p>
<pre><code>if ( is_home() ) {
// variables
$check_meta = get_post_meta( get_the_ID(), 'checkbox', true );
$header_meta = get_post_meta( get_the_ID(), 'header', true );
$textarea_meta = get_post_meta( get_the_ID(), 'textarea', true );
// condition
if ( ( $check_meta == 'yes' ) && !empty( $textarea_meta ) && !empty( $header_meta ) ) {
// code
}
}
</code></pre>
<p>Why does <code>get_the_ID()</code> appear to not work with <code>get_post_meta()</code> in <code>home.php</code> located in <code>header.php</code>?</p>
<hr>
<p>Edit:</p>
<p>Per the comments I thought I would edit this question to help someone else in the future. I am setting the the front page and the posts page in <code>Settings -> Reading</code>. The below worked in my conditional for <code>is_home()</code>:</p>
<pre><code>$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );
$header_meta = get_post_meta( get_queried_object_id(), 'header', true );
$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );
</code></pre>
|
[
{
"answer_id": 208229,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>The home page (<em>this goes for the blogpage any archive page as well</em>) does not have a post ID as it is not a post neither a page. These are virtual pages and does not actually exist as they where not created in back end. </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID()</code></a> uses <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow\"><code>get_post()</code></a> which uses the <code>$post</code> global to return the ID of a post or a page. Inside the loop, the <code>$post</code> global will always be set to the current post being looped through through <code>the_post()</code>. </p>\n\n<p>Outside the loop, in the main query, before the loop, the <code>$post</code> global will be automatically be set and hold the post object of the first post in the query. You can check this with <code>var_dump( $post );</code>. The <code>$post</code> global will be set to the last post in the query if checked after the loop has run (<em>because <code>the_post()</code> has changed the value</em>).</p>\n\n<p>On single post pages and true pages, the first post (<em>which will always be the only post</em>) will be the post that was queried, so the post ID will always (<em>if you are not using <code>query_posts</code>, <code>query_posts</code> will break this stuffing you big time</em>)correspond with the correct ID of the post or page. On any archive page, the post ID returned by <code>get_the_ID()</code> will always be the first or last post in the query depending on where it is used outside the loop.</p>\n\n<p>Archive pages also cannot have post meta, as they are not posts or pages and they do not have ID's. </p>\n\n<p>So, in short, <code>get_the_ID()</code> will always return <code>false</code> (<em>if <code>$post</code> is ever to be empty</em>), or the ID of the first or last post in the query outside the loop on any type of archive page</p>\n"
},
{
"answer_id": 208231,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 0,
"selected": false,
"text": "<p>In order to use <code>get_post_meta()</code> you need to have a post id. These are your options:</p>\n\n<ol>\n<li>Set a post id manually</li>\n<li>Run your code in the loop and <code>get_the_ID()</code> usually <em>loop.php</em></li>\n<li>Run your code in a single page or post usually <em>page.php</em> or <em>single.php</em></li>\n</ol>\n\n<p>Expanding answer using TwentyFifteen theme:</p>\n\n<ol>\n<li>Open <em>index.php</em></li>\n<li>Locate the loop code starting with <code>while ( have_posts() ) : the_post();</code></li>\n<li>Insert your code after code in step 2, <code>$meta = get_post_meta( get_the_ID() );</code></li>\n</ol>\n"
},
{
"answer_id": 208237,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": true,
"text": "<p>If your posts page is a static page selected under Settings > Reading > <strong>Front page displays</strong>, then <code>get_queried_object_id()</code> will return the ID for that page which you can use to fetch meta data.</p>\n\n<pre><code>$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );\n$header_meta = get_post_meta( get_queried_object_id(), 'header', true ); \n$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );\n</code></pre>\n"
}
] |
2015/11/10
|
[
"https://wordpress.stackexchange.com/questions/208225",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25271/"
] |
Looking for a reason why `get_post_meta()` doesn't work with `home.php`. From my reading I understand that it's a template and not a post or page, per "[Custom fields won't display on my blog page](https://wordpress.stackexchange.com/questions/92285/custom-fields-wont-display-on-my-blog-page?lq=1)". The closest page I was able to find from searching was "[get\_post\_meta fields don't show up on posts page](https://wordpress.stackexchange.com/questions/152088/get-post-meta-fields-dont-show-up-on-posts-page)" but alas the answer doesn't go into detail why. I have coded a custom meta box, it works, for the `front_page.php` and all custom post types but not within `home.php`. I am using a conditional `is_home()` and it works but it seems `get_the_ID()` doesn't, the code:
```
if ( is_home() ) {
// variables
$check_meta = get_post_meta( get_the_ID(), 'checkbox', true );
$header_meta = get_post_meta( get_the_ID(), 'header', true );
$textarea_meta = get_post_meta( get_the_ID(), 'textarea', true );
// condition
if ( ( $check_meta == 'yes' ) && !empty( $textarea_meta ) && !empty( $header_meta ) ) {
// code
}
}
```
Why does `get_the_ID()` appear to not work with `get_post_meta()` in `home.php` located in `header.php`?
---
Edit:
Per the comments I thought I would edit this question to help someone else in the future. I am setting the the front page and the posts page in `Settings -> Reading`. The below worked in my conditional for `is_home()`:
```
$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );
$header_meta = get_post_meta( get_queried_object_id(), 'header', true );
$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );
```
|
If your posts page is a static page selected under Settings > Reading > **Front page displays**, then `get_queried_object_id()` will return the ID for that page which you can use to fetch meta data.
```
$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );
$header_meta = get_post_meta( get_queried_object_id(), 'header', true );
$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );
```
|
208,259 |
<p><strong>There is an Edit at the end of this question.</strong></p>
<p>I want to to include a file, in a script tag, from the js sub directory of the theme's directory. I want to do so in the theme's index, search, single, archive, etc. php files.</p>
<p>The URL of the theme I'm using is: <a href="http://www.example.com/welg/wp-content/themes/mytheme" rel="nofollow">http://www.example.com/welg/wp-content/themes/mytheme</a></p>
<p>The script tag would be: </p>
<pre><code><script type="text/javascript" src="/welg/wp-content/themes/themename/js/filename.js">
</code></pre>
<p>I tried the get_theme_root() function but I get nonsense. Well, at least nonsense in terms of a directory usable for my purposes.</p>
<p>What is be returned is a path that starts pretty much at the top of the hosting server's directory structure.</p>
<pre><code>/hermes/bosoraweb081/b1107/myd.sugarcatsimon/public_html/pdmeoff/pdroot/welg/wp-content/themes
</code></pre>
<p>That output is useless for any purpose except, perhaps direct access, via the operating system, on the server itself by someone at the server's console.</p>
<p>The return value I expected from get_theme_root() was:</p>
<pre><code>/welg/wp-content/themes/themedir (with or without a trailing slash)
</code></pre>
<p>I tried all the "get" theme functions I could find and the site_url and home_url</p>
<p>Here's the ouput from all of them (I added h's to the front of the http:// text to get past my limit of only being able to post two links. Just ignore the extra h's.</p>
<p>Here's the output from the various functions:</p>
<pre><code>get_theme_root_uri()-- http://www.example.com/welg/wp-content/themes
get_theme_root() -- /hermes/bosoraweb081/b1107/myd.sugarcatsimon/public_html/pdmeoff/pdroot/welg/wp-content/themes
get_theme_roots() -- /themes
site_url -- http://www.example.com/welg
home_url http://www.example.com/welg
</code></pre>
<p>Am I missing something? Is there another function which will return the path, relative to the site root or WP root, for the currently used theme's directory?</p>
<p>I guess I could use the output from get_them_url(), make my link a fully qualified link, not a relative link, and suffix the name of the theme and the /js/filename.js but I'd like a better solution which does not rely on knowing any of the directory names, such as the current theme's name/directory.</p>
<p>One other thing - I habitually use www.example.com as the domain in examples I post online, and most sites tell you to use it, but I had never really thought it through.</p>
<p>I just realized that there my be an actual site with that domain name. So, I entered www.example.com into the browser address bar and I got - well, try it yourself. It is very interesting.</p>
<p><strong>EDIT</strong> </p>
<p>In response to the person who wrote the answer saying that I should enqueue and register scripts -</p>
<p>What does it mean in WP Land when the words enqueue and register are used?</p>
<p>What are the benefits, as regards WP, of enqueuing and registering functions as you show it being done?</p>
<p>Just because those who wrote WP do something in a particular way does not mean it can only be done that way or it is the best way.</p>
<p>I would really like to know the principles of enqueuing and registering functions as apply to WP.</p>
<p>I am new to WP but most certainly new to computing. I've been in computing since 1973, some 42+ years. </p>
<p>In the PC world, it is far too often the case that words which have been in use for decades, with specific agreed upon meanings, are used for new meanings.</p>
<p>There is also a propensity for the invention of new terms for meanings that are already covered by existing terminology.</p>
<p>Quite often, what an "old timer" calls a rose is actually not a rose, in the PC world. When terms with established meanings are used in computing (or any technical area) for other purposes, communication suffers.</p>
<p>Poor communications breeds poor design and code.</p>
<p>Thanks for the reply and I really would like to understand those words in relation to WP.</p>
|
[
{
"answer_id": 208229,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 2,
"selected": false,
"text": "<p>The home page (<em>this goes for the blogpage any archive page as well</em>) does not have a post ID as it is not a post neither a page. These are virtual pages and does not actually exist as they where not created in back end. </p>\n\n<p><a href=\"https://developer.wordpress.org/reference/functions/get_the_id/\" rel=\"nofollow\"><code>get_the_ID()</code></a> uses <a href=\"https://developer.wordpress.org/reference/functions/get_post/\" rel=\"nofollow\"><code>get_post()</code></a> which uses the <code>$post</code> global to return the ID of a post or a page. Inside the loop, the <code>$post</code> global will always be set to the current post being looped through through <code>the_post()</code>. </p>\n\n<p>Outside the loop, in the main query, before the loop, the <code>$post</code> global will be automatically be set and hold the post object of the first post in the query. You can check this with <code>var_dump( $post );</code>. The <code>$post</code> global will be set to the last post in the query if checked after the loop has run (<em>because <code>the_post()</code> has changed the value</em>).</p>\n\n<p>On single post pages and true pages, the first post (<em>which will always be the only post</em>) will be the post that was queried, so the post ID will always (<em>if you are not using <code>query_posts</code>, <code>query_posts</code> will break this stuffing you big time</em>)correspond with the correct ID of the post or page. On any archive page, the post ID returned by <code>get_the_ID()</code> will always be the first or last post in the query depending on where it is used outside the loop.</p>\n\n<p>Archive pages also cannot have post meta, as they are not posts or pages and they do not have ID's. </p>\n\n<p>So, in short, <code>get_the_ID()</code> will always return <code>false</code> (<em>if <code>$post</code> is ever to be empty</em>), or the ID of the first or last post in the query outside the loop on any type of archive page</p>\n"
},
{
"answer_id": 208231,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 0,
"selected": false,
"text": "<p>In order to use <code>get_post_meta()</code> you need to have a post id. These are your options:</p>\n\n<ol>\n<li>Set a post id manually</li>\n<li>Run your code in the loop and <code>get_the_ID()</code> usually <em>loop.php</em></li>\n<li>Run your code in a single page or post usually <em>page.php</em> or <em>single.php</em></li>\n</ol>\n\n<p>Expanding answer using TwentyFifteen theme:</p>\n\n<ol>\n<li>Open <em>index.php</em></li>\n<li>Locate the loop code starting with <code>while ( have_posts() ) : the_post();</code></li>\n<li>Insert your code after code in step 2, <code>$meta = get_post_meta( get_the_ID() );</code></li>\n</ol>\n"
},
{
"answer_id": 208237,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": true,
"text": "<p>If your posts page is a static page selected under Settings > Reading > <strong>Front page displays</strong>, then <code>get_queried_object_id()</code> will return the ID for that page which you can use to fetch meta data.</p>\n\n<pre><code>$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );\n$header_meta = get_post_meta( get_queried_object_id(), 'header', true ); \n$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208259",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83376/"
] |
**There is an Edit at the end of this question.**
I want to to include a file, in a script tag, from the js sub directory of the theme's directory. I want to do so in the theme's index, search, single, archive, etc. php files.
The URL of the theme I'm using is: <http://www.example.com/welg/wp-content/themes/mytheme>
The script tag would be:
```
<script type="text/javascript" src="/welg/wp-content/themes/themename/js/filename.js">
```
I tried the get\_theme\_root() function but I get nonsense. Well, at least nonsense in terms of a directory usable for my purposes.
What is be returned is a path that starts pretty much at the top of the hosting server's directory structure.
```
/hermes/bosoraweb081/b1107/myd.sugarcatsimon/public_html/pdmeoff/pdroot/welg/wp-content/themes
```
That output is useless for any purpose except, perhaps direct access, via the operating system, on the server itself by someone at the server's console.
The return value I expected from get\_theme\_root() was:
```
/welg/wp-content/themes/themedir (with or without a trailing slash)
```
I tried all the "get" theme functions I could find and the site\_url and home\_url
Here's the ouput from all of them (I added h's to the front of the http:// text to get past my limit of only being able to post two links. Just ignore the extra h's.
Here's the output from the various functions:
```
get_theme_root_uri()-- http://www.example.com/welg/wp-content/themes
get_theme_root() -- /hermes/bosoraweb081/b1107/myd.sugarcatsimon/public_html/pdmeoff/pdroot/welg/wp-content/themes
get_theme_roots() -- /themes
site_url -- http://www.example.com/welg
home_url http://www.example.com/welg
```
Am I missing something? Is there another function which will return the path, relative to the site root or WP root, for the currently used theme's directory?
I guess I could use the output from get\_them\_url(), make my link a fully qualified link, not a relative link, and suffix the name of the theme and the /js/filename.js but I'd like a better solution which does not rely on knowing any of the directory names, such as the current theme's name/directory.
One other thing - I habitually use www.example.com as the domain in examples I post online, and most sites tell you to use it, but I had never really thought it through.
I just realized that there my be an actual site with that domain name. So, I entered www.example.com into the browser address bar and I got - well, try it yourself. It is very interesting.
**EDIT**
In response to the person who wrote the answer saying that I should enqueue and register scripts -
What does it mean in WP Land when the words enqueue and register are used?
What are the benefits, as regards WP, of enqueuing and registering functions as you show it being done?
Just because those who wrote WP do something in a particular way does not mean it can only be done that way or it is the best way.
I would really like to know the principles of enqueuing and registering functions as apply to WP.
I am new to WP but most certainly new to computing. I've been in computing since 1973, some 42+ years.
In the PC world, it is far too often the case that words which have been in use for decades, with specific agreed upon meanings, are used for new meanings.
There is also a propensity for the invention of new terms for meanings that are already covered by existing terminology.
Quite often, what an "old timer" calls a rose is actually not a rose, in the PC world. When terms with established meanings are used in computing (or any technical area) for other purposes, communication suffers.
Poor communications breeds poor design and code.
Thanks for the reply and I really would like to understand those words in relation to WP.
|
If your posts page is a static page selected under Settings > Reading > **Front page displays**, then `get_queried_object_id()` will return the ID for that page which you can use to fetch meta data.
```
$check_meta = get_post_meta( get_queried_object_id(), 'checkbox', true );
$header_meta = get_post_meta( get_queried_object_id(), 'header', true );
$textarea_meta = get_post_meta( get_queried_object_id(), 'textarea', true );
```
|
208,300 |
<p>Metadata is information about an image, and can be included in JPEG image files.</p>
<p>EXIF metadata is information about the image recorded directly from the camera – for example, the exposure time and the date the photo was taken.</p>
<p>WordPress preserves EXIF information in full size images loaded to your website. It will also extract the Exif data to make it available for plugin developers.</p>
<p>When WordPress uploads images, in addition to uploading the Full Size image it automatically creates several differently sized versions of the image. By default: a Large, Medium and Thumbnail version.</p>
<p>The problem is that Wordpress is stripping the EXIF data when resizing images. The resized images become "orphan".</p>
<p>An "orphan" work is a work to which copyright cannot be determined or a work where the determined copyright holder cannot be contacted.</p>
<p>In the era of responsive images, it cannot be that the solution to keep the EXIF data of an image is to use the image in full-size.</p>
<p><strong>Question:</strong></p>
<ul>
<li>How to force Wordpress to keep EXIF data?</li>
</ul>
<p><strong>Digging further:</strong></p>
<ul>
<li>Is there a way to insert the EXIF data in resized images once they have been resized?</li>
<li>Is there a way to force wordpress to use another Image Processing System that is not stripping metadata from images?</li>
</ul>
|
[
{
"answer_id": 238971,
"author": "cjbj",
"author_id": 75495,
"author_profile": "https://wordpress.stackexchange.com/users/75495",
"pm_score": 2,
"selected": false,
"text": "<p>This issue has been fixed <a href=\"https://developer.wordpress.org/reference/hooks/image_strip_meta/\" rel=\"nofollow\">with a filter</a> in Wordpress 4.5. If you want to preserve the exif data when resizing use</p>\n\n<pre><code>add_filter ('image_strip_meta', false);\n</code></pre>\n"
},
{
"answer_id": 239001,
"author": "John Nivav",
"author_id": 102666,
"author_profile": "https://wordpress.stackexchange.com/users/102666",
"pm_score": 2,
"selected": false,
"text": "<p><strong>1) How to force Wordpress to keep EXIF data?</strong></p>\n\n<p>Use imagick instead of GD. If imagick is installed in your server, wordpress will use it instead of GD. Problem is, that many servers and shared hostings dont have imagick and the user has to install it, which can be a hassle. Many shared hostings don't even allow to install other php extensions. Some hostings provide imagick by default. It's always a great idea to check if the hosting has it (and if not, if its possible to install it) before attempting to build a website that will require such metadata.</p>\n\n<p>Last time I did a project that required EXIF, my client had a server that didnt allow the installation of imagick. We migrated server, installed imagick and solved the issue.</p>\n\n<p><strong>There is an important note concerning regenerate thumbnails plugins:</strong> even if you have imagick installed in your server, some of these plugins <em>will remove</em> the metadata when regenerating images. Carefully read each plugin description and make sure they dont remove metadata before using them.</p>\n\n<hr>\n\n<p><strong>2) Is there a way to insert the EXIF data in resized images once they have been resized?</strong></p>\n\n<p>This metadata is stored in db tables, but why would you attempt to do that if you can keep the metadata using imagick?</p>\n\n<hr>\n\n<p><strong>3) Is there a way to force wordpress to use another Image Processing System that is not stripping metadata from images?</strong> </p>\n\n<p>Yes, imagick.</p>\n"
},
{
"answer_id": 248158,
"author": "Steve",
"author_id": 108187,
"author_profile": "https://wordpress.stackexchange.com/users/108187",
"pm_score": -1,
"selected": false,
"text": "<p>The work around is to simply download the images created by Wordpress to your computer, add the metadata with a program like Photoshop, and the upload them to the same folder, replacing the originals with the one now containing the metadata. It's not that convenient, but doesn't require any knowledge other than how to download files (I use FTP) and how to add metadata. </p>\n\n<p>You won't be able to add back camera data, but you can add copyright information, credit information, and who to contact in order to get permission to use the photos. </p>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208300",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/47846/"
] |
Metadata is information about an image, and can be included in JPEG image files.
EXIF metadata is information about the image recorded directly from the camera – for example, the exposure time and the date the photo was taken.
WordPress preserves EXIF information in full size images loaded to your website. It will also extract the Exif data to make it available for plugin developers.
When WordPress uploads images, in addition to uploading the Full Size image it automatically creates several differently sized versions of the image. By default: a Large, Medium and Thumbnail version.
The problem is that Wordpress is stripping the EXIF data when resizing images. The resized images become "orphan".
An "orphan" work is a work to which copyright cannot be determined or a work where the determined copyright holder cannot be contacted.
In the era of responsive images, it cannot be that the solution to keep the EXIF data of an image is to use the image in full-size.
**Question:**
* How to force Wordpress to keep EXIF data?
**Digging further:**
* Is there a way to insert the EXIF data in resized images once they have been resized?
* Is there a way to force wordpress to use another Image Processing System that is not stripping metadata from images?
|
This issue has been fixed [with a filter](https://developer.wordpress.org/reference/hooks/image_strip_meta/) in Wordpress 4.5. If you want to preserve the exif data when resizing use
```
add_filter ('image_strip_meta', false);
```
|
208,306 |
<p>I only do a SELECT on a whole table - and the table is defined in a variable:</p>
<pre><code>$table = $wpdb->prefix . 'members';
</code></pre>
<p>Do I have to bind a parameter to this variable?</p>
<p>This caused an error:</p>
<pre><code>$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM %s", $table, ARRAY_A));
</code></pre>
<p>But if I skip the "%s", this gives an error as well:</p>
<pre><code>$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table", ARRAY_A));
</code></pre>
<p>Should I skip "prepare" in this case?</p>
|
[
{
"answer_id": 208309,
"author": "CapitanFindus",
"author_id": 63722,
"author_profile": "https://wordpress.stackexchange.com/users/63722",
"pm_score": 0,
"selected": false,
"text": "<p>It's just a wrong bracket closing, <code>$wpdb->prepare</code> only requires the <code>query string</code> and <code>query parameters</code>. Then, on <code>get_results</code> you can define what kind of results do you need, so:</p>\n\n<pre><code>$result = $wpdb->get_results(\n $wpdb->prepare( \"SELECT * FROM %s\", $table ),\n ARRAY_A\n) or die ( $wpdb->last_error );\n</code></pre>\n\n<p>Edit: you can check for <code>$wpdb</code> last SQL error by using this updated code</p>\n"
},
{
"answer_id": 208381,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 3,
"selected": true,
"text": "<p>No, you do not want to swap out the tablename. If you do, the table name will be wrapped in quotes and it will trigger a SQL error. Try:</p>\n\n<pre><code>$table = $wpdb->prefix . 'members';\n$qry = $wpdb->prepare(\"SELECT * FROM %s\", $table); \nvar_dump($qry);\n\n$qry = \"SELECT * FROM $table\";\nvar_dump($result);\n</code></pre>\n\n<p>The first string is invalid SQL. The second should work provided that you have a table of the correct name.</p>\n\n<p><code>prepare()</code> is meant to operate on user supplied data-- data that could be from questionable sourced with malicious intent. You do not need to swap out data, like your table name, that is not from a questionable source.</p>\n\n<p>What you want is:</p>\n\n<pre><code>$table = $wpdb->prefix . 'members';\n$qry = \"SELECT * FROM $table\";\n$result = $wpdb->get_results($qry, ARRAY_A);\nvar_dump($result); \n</code></pre>\n\n<p>By the way, your parenthesis are wrong here (even if the rest worked):</p>\n\n<pre><code>$result = $wpdb->get_results($wpdb->prepare(\"SELECT * FROM %s\", $table, ARRAY_A));\n</code></pre>\n\n<p>The <code>ARRAY_A</code> is an argument to the <code>prepare</code> and not to the <code>get_results</code>. It should be (though the value swapping is wrong as explained above):</p>\n\n<pre><code>$result = $wpdb->get_results(\n $wpdb->prepare(\"SELECT * FROM %s\", $table), \n ARRAY_A\n);\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208306",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82394/"
] |
I only do a SELECT on a whole table - and the table is defined in a variable:
```
$table = $wpdb->prefix . 'members';
```
Do I have to bind a parameter to this variable?
This caused an error:
```
$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM %s", $table, ARRAY_A));
```
But if I skip the "%s", this gives an error as well:
```
$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM $table", ARRAY_A));
```
Should I skip "prepare" in this case?
|
No, you do not want to swap out the tablename. If you do, the table name will be wrapped in quotes and it will trigger a SQL error. Try:
```
$table = $wpdb->prefix . 'members';
$qry = $wpdb->prepare("SELECT * FROM %s", $table);
var_dump($qry);
$qry = "SELECT * FROM $table";
var_dump($result);
```
The first string is invalid SQL. The second should work provided that you have a table of the correct name.
`prepare()` is meant to operate on user supplied data-- data that could be from questionable sourced with malicious intent. You do not need to swap out data, like your table name, that is not from a questionable source.
What you want is:
```
$table = $wpdb->prefix . 'members';
$qry = "SELECT * FROM $table";
$result = $wpdb->get_results($qry, ARRAY_A);
var_dump($result);
```
By the way, your parenthesis are wrong here (even if the rest worked):
```
$result = $wpdb->get_results($wpdb->prepare("SELECT * FROM %s", $table, ARRAY_A));
```
The `ARRAY_A` is an argument to the `prepare` and not to the `get_results`. It should be (though the value swapping is wrong as explained above):
```
$result = $wpdb->get_results(
$wpdb->prepare("SELECT * FROM %s", $table),
ARRAY_A
);
```
|
208,307 |
<p>I'm using this code for generating a Feed from lasted modified post</p>
<pre><code>mysqli_query( $conn,
"SELECT * FROM wp_posts
WHERE post_status = 'publish'
AND post_type = 'post'
AND DATE(post_modified) > DATE(post_date)
ORDER BY post_modified DESC
LIMIT 50"
);
</code></pre>
<p>and it works perfect, now I need to reproduce in a WordPress plugin and I use this code:</p>
<pre><code> $lastupdated_args = array(
'paged' => $paged,
'orderby' => 'modified',
'ignore_sticky_posts' => '1'
);
</code></pre>
<p>but in this case it shows all posts ordered my latest modification and not only modified post. </p>
<p>Is it possible to fix?</p>
|
[
{
"answer_id": 208314,
"author": "Bharat",
"author_id": 83408,
"author_profile": "https://wordpress.stackexchange.com/users/83408",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$lastupdated_args = array(\n 'paged' => $paged,\n 'post_status' => 'publish',\n 'post_type' = 'post',\n 'orderby' => 'modified',\n 'ignore_sticky_posts' => '1'\n);\n</code></pre>\n\n<p>I think this will help you.</p>\n"
},
{
"answer_id": 208338,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <code>posts_where</code> filter:</p>\n\n<pre><code>// Add custom filter\nadd_filter( 'posts_where', 'wpse_modified' );\n\n// Fetch posts\n$query = new WP_Query( $lastupdated_args );\n</code></pre>\n\n<p>where you can define the filter callback as:</p>\n\n<pre><code>function wpse_modified( $where )\n{\n global $wpdb;\n // Run only once:\n remove_filter( current_filter(), __FUNCTION__ );\n // Append custom SQL\n return $where . \" AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';\n}\n</code></pre>\n\n<p>Though it would be handy to be able to use this kind of <em>date queries</em>:</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ 'before' => 'post_modified' ]\n ],\n];\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ \n 'column' => 'post_modified_gmt', \n 'after' => 'post_date_gmt', \n 'inclusive' => false \n ]\n ],\n];\n</code></pre>\n\n<p>That's maybe an idea for a core ticket! ;-)</p>\n"
},
{
"answer_id": 348600,
"author": "Amin",
"author_id": 113633,
"author_profile": "https://wordpress.stackexchange.com/users/113633",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe something like this will help, i had a situation where i needed to get posts that were modified at least 1 day after they were created: </p>\n\n<pre><code>function dw_get_modified_posts($author, $post_type = 'post') {\n global $wpdb;\n\n $result = $wpdb->get_results(\n $wpdb->prepare(\"\n SELECT ID\n FROM `$wpdb->posts`\n WHERE UNIX_TIMESTAMP(post_modified_gmt) - UNIX_TIMESTAMP(post_date_gmt) > 86400\n AND post_type = %s\n AND post_author = %d\n \", $post_type, $author)\n );\n\n return array_map(function ($post) {\n return $post->ID;\n\n }, (array) $result);\n}\n</code></pre>\n\n<p><code>86400</code> is the 1 day margin which you can edit it, now you can make a wp_query out of it:</p>\n\n<pre><code>$posts_list = new WP_Query([\n 'post__in' => dw_get_modified_posts() ?: [0]\n]);\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208307",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/-1/"
] |
I'm using this code for generating a Feed from lasted modified post
```
mysqli_query( $conn,
"SELECT * FROM wp_posts
WHERE post_status = 'publish'
AND post_type = 'post'
AND DATE(post_modified) > DATE(post_date)
ORDER BY post_modified DESC
LIMIT 50"
);
```
and it works perfect, now I need to reproduce in a WordPress plugin and I use this code:
```
$lastupdated_args = array(
'paged' => $paged,
'orderby' => 'modified',
'ignore_sticky_posts' => '1'
);
```
but in this case it shows all posts ordered my latest modification and not only modified post.
Is it possible to fix?
|
You can use the `posts_where` filter:
```
// Add custom filter
add_filter( 'posts_where', 'wpse_modified' );
// Fetch posts
$query = new WP_Query( $lastupdated_args );
```
where you can define the filter callback as:
```
function wpse_modified( $where )
{
global $wpdb;
// Run only once:
remove_filter( current_filter(), __FUNCTION__ );
// Append custom SQL
return $where . " AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';
}
```
Though it would be handy to be able to use this kind of *date queries*:
```
$args = [
'date_query' => [
[ 'before' => 'post_modified' ]
],
];
```
and
```
$args = [
'date_query' => [
[
'column' => 'post_modified_gmt',
'after' => 'post_date_gmt',
'inclusive' => false
]
],
];
```
That's maybe an idea for a core ticket! ;-)
|
208,339 |
<p>I've got a custom post type called <code>course</code>. Within a course post, I have a number of custom fields, specifically (all AFC select dropdowns): <code>course_or_project</code>, <code>time_to_complete_project</code>, <code>time_to_complete_course</code> and <code>difficulty</code>. I also have a taxonomy called <code>course_project_category</code>.</p>
<p>My aim is to be able to create a number of dropdown/sliders, build a URL by reading the values of said dropdowns/sliders and on click of a search button, use the query string I've put together (jQuery) to filter just the right posts. This functionality is all working. Well... sometimes the results are a little confused i.e. only filtering by some of the parameters.</p>
<p>On to the code.</p>
<p>I've added a function in to expose my custom fields:</p>
<pre><code>function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
// only modify queries for 'course' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'course' ) {
// allow the url to alter the query
if( isset($_GET['course_or_project']) ) {
$query->set('meta_key', 'course_or_project');
$query->set('meta_value', $_GET['course_or_project']);
}
if( isset($_GET['time_to_complete_project']) ) {
$query->set('meta_key', 'time_to_complete_project');
$query->set('meta_value', $_GET['time_to_complete_project']);
}
if( isset($_GET['time_to_complete_course']) ) {
$query->set('meta_key', 'time_to_complete_course');
$query->set('meta_value', $_GET['time_to_complete_course']);
}
if( isset($_GET['difficulty']) ) {
$query->set('meta_key', 'difficulty');
$query->set('meta_value', $_GET['difficulty']);
}
}
// return
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
</code></pre>
<p>Querying the taxonomy appears to work out-of-the-box.</p>
<p>So an example of my completed URL might be:</p>
<pre><code>http://localhost:3000/courses/?course_project_category=jokes&course_or_project=project&difficulty=easy&time_to_complete_project=15
</code></pre>
<p>My results are a mixed bag at this point.</p>
<p>From the above query, I've returned 2 posts which mostly match my criteria but as a specific example, one post has a <code>time_to_complete_project</code> value as <code>30</code> even though the query specified <code>15</code>.</p>
<p>I cannot figure this out. I can see the parameters are all there as expected through Chrome dev tools:</p>
<p><a href="https://i.stack.imgur.com/3Co9R.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3Co9R.png" alt="enter image description here"></a></p>
<p>Any ideas?!</p>
<p><strong>Update</strong></p>
<p>Here's a new approach I have that is working (but is lacking validation and sanitation):</p>
<pre><code>// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array(
'field_1' => 'course_or_project',
'field_2' => 'difficulty',
'field_3' => 'time_to_complete_project',
'field_4' => 'time_to_complete_course'
);
// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) {
return;
}
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'course' ) {
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
// update meta query
$query->set('meta_query', $meta_query);
}
}
</code></pre>
|
[
{
"answer_id": 208314,
"author": "Bharat",
"author_id": 83408,
"author_profile": "https://wordpress.stackexchange.com/users/83408",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$lastupdated_args = array(\n 'paged' => $paged,\n 'post_status' => 'publish',\n 'post_type' = 'post',\n 'orderby' => 'modified',\n 'ignore_sticky_posts' => '1'\n);\n</code></pre>\n\n<p>I think this will help you.</p>\n"
},
{
"answer_id": 208338,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <code>posts_where</code> filter:</p>\n\n<pre><code>// Add custom filter\nadd_filter( 'posts_where', 'wpse_modified' );\n\n// Fetch posts\n$query = new WP_Query( $lastupdated_args );\n</code></pre>\n\n<p>where you can define the filter callback as:</p>\n\n<pre><code>function wpse_modified( $where )\n{\n global $wpdb;\n // Run only once:\n remove_filter( current_filter(), __FUNCTION__ );\n // Append custom SQL\n return $where . \" AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';\n}\n</code></pre>\n\n<p>Though it would be handy to be able to use this kind of <em>date queries</em>:</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ 'before' => 'post_modified' ]\n ],\n];\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ \n 'column' => 'post_modified_gmt', \n 'after' => 'post_date_gmt', \n 'inclusive' => false \n ]\n ],\n];\n</code></pre>\n\n<p>That's maybe an idea for a core ticket! ;-)</p>\n"
},
{
"answer_id": 348600,
"author": "Amin",
"author_id": 113633,
"author_profile": "https://wordpress.stackexchange.com/users/113633",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe something like this will help, i had a situation where i needed to get posts that were modified at least 1 day after they were created: </p>\n\n<pre><code>function dw_get_modified_posts($author, $post_type = 'post') {\n global $wpdb;\n\n $result = $wpdb->get_results(\n $wpdb->prepare(\"\n SELECT ID\n FROM `$wpdb->posts`\n WHERE UNIX_TIMESTAMP(post_modified_gmt) - UNIX_TIMESTAMP(post_date_gmt) > 86400\n AND post_type = %s\n AND post_author = %d\n \", $post_type, $author)\n );\n\n return array_map(function ($post) {\n return $post->ID;\n\n }, (array) $result);\n}\n</code></pre>\n\n<p><code>86400</code> is the 1 day margin which you can edit it, now you can make a wp_query out of it:</p>\n\n<pre><code>$posts_list = new WP_Query([\n 'post__in' => dw_get_modified_posts() ?: [0]\n]);\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208339",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/36920/"
] |
I've got a custom post type called `course`. Within a course post, I have a number of custom fields, specifically (all AFC select dropdowns): `course_or_project`, `time_to_complete_project`, `time_to_complete_course` and `difficulty`. I also have a taxonomy called `course_project_category`.
My aim is to be able to create a number of dropdown/sliders, build a URL by reading the values of said dropdowns/sliders and on click of a search button, use the query string I've put together (jQuery) to filter just the right posts. This functionality is all working. Well... sometimes the results are a little confused i.e. only filtering by some of the parameters.
On to the code.
I've added a function in to expose my custom fields:
```
function my_pre_get_posts( $query ) {
// do not modify queries in the admin
if( is_admin() ) {
return $query;
}
// only modify queries for 'course' post type
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'course' ) {
// allow the url to alter the query
if( isset($_GET['course_or_project']) ) {
$query->set('meta_key', 'course_or_project');
$query->set('meta_value', $_GET['course_or_project']);
}
if( isset($_GET['time_to_complete_project']) ) {
$query->set('meta_key', 'time_to_complete_project');
$query->set('meta_value', $_GET['time_to_complete_project']);
}
if( isset($_GET['time_to_complete_course']) ) {
$query->set('meta_key', 'time_to_complete_course');
$query->set('meta_value', $_GET['time_to_complete_course']);
}
if( isset($_GET['difficulty']) ) {
$query->set('meta_key', 'difficulty');
$query->set('meta_value', $_GET['difficulty']);
}
}
// return
return $query;
}
add_action('pre_get_posts', 'my_pre_get_posts');
```
Querying the taxonomy appears to work out-of-the-box.
So an example of my completed URL might be:
```
http://localhost:3000/courses/?course_project_category=jokes&course_or_project=project&difficulty=easy&time_to_complete_project=15
```
My results are a mixed bag at this point.
From the above query, I've returned 2 posts which mostly match my criteria but as a specific example, one post has a `time_to_complete_project` value as `30` even though the query specified `15`.
I cannot figure this out. I can see the parameters are all there as expected through Chrome dev tools:
[](https://i.stack.imgur.com/3Co9R.png)
Any ideas?!
**Update**
Here's a new approach I have that is working (but is lacking validation and sanitation):
```
// array of filters (field key => field name)
$GLOBALS['my_query_filters'] = array(
'field_1' => 'course_or_project',
'field_2' => 'difficulty',
'field_3' => 'time_to_complete_project',
'field_4' => 'time_to_complete_course'
);
// action
add_action('pre_get_posts', 'my_pre_get_posts', 10, 1);
function my_pre_get_posts( $query ) {
// bail early if is in admin
if( is_admin() ) {
return;
}
if( isset($query->query_vars['post_type']) && $query->query_vars['post_type'] == 'course' ) {
// get meta query
$meta_query = $query->get('meta_query');
// loop over filters
foreach( $GLOBALS['my_query_filters'] as $key => $name ) {
// continue if not found in url
if( empty($_GET[ $name ]) ) {
continue;
}
// get the value for this filter
// eg: http://www.website.com/events?city=melbourne,sydney
$value = explode(',', $_GET[ $name ]);
// append meta query
$meta_query[] = array(
'key' => $name,
'value' => $value,
'compare' => 'IN',
);
}
// update meta query
$query->set('meta_query', $meta_query);
}
}
```
|
You can use the `posts_where` filter:
```
// Add custom filter
add_filter( 'posts_where', 'wpse_modified' );
// Fetch posts
$query = new WP_Query( $lastupdated_args );
```
where you can define the filter callback as:
```
function wpse_modified( $where )
{
global $wpdb;
// Run only once:
remove_filter( current_filter(), __FUNCTION__ );
// Append custom SQL
return $where . " AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';
}
```
Though it would be handy to be able to use this kind of *date queries*:
```
$args = [
'date_query' => [
[ 'before' => 'post_modified' ]
],
];
```
and
```
$args = [
'date_query' => [
[
'column' => 'post_modified_gmt',
'after' => 'post_date_gmt',
'inclusive' => false
]
],
];
```
That's maybe an idea for a core ticket! ;-)
|
208,347 |
<p>take <code>the_category()</code> as an example:</p>
<p>Here is the output of the_category function in the wordpress loop:</p>
<pre><code> <ul class="post-categories">
<li>
<a href="http://example.com/category/another-category/" rel="category tag">
Another Category
</a>
</li>
<li>
<a href="http://example.com/category/uncategorized/" rel="category tag">
Uncategorized
</a>
</li>
</ul>
</code></pre>
<p>so we need a way to add attributes like some other classes, data attributes and ... to the list so it outputs something like this:</p>
<pre><code><ul id="drop1" class="f-dropdown" data-dropdown-content aria-hidden="true" tabindex="-1">
<li>
<a href="http://example.com/category/another-category/" rel="category tag">
Another Category
</a>
</li>
<li>
<a href="http://example.com/category/uncategorized/" rel="category tag">
Uncategorized
</a>
</li>
</ul>
</code></pre>
|
[
{
"answer_id": 208314,
"author": "Bharat",
"author_id": 83408,
"author_profile": "https://wordpress.stackexchange.com/users/83408",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$lastupdated_args = array(\n 'paged' => $paged,\n 'post_status' => 'publish',\n 'post_type' = 'post',\n 'orderby' => 'modified',\n 'ignore_sticky_posts' => '1'\n);\n</code></pre>\n\n<p>I think this will help you.</p>\n"
},
{
"answer_id": 208338,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <code>posts_where</code> filter:</p>\n\n<pre><code>// Add custom filter\nadd_filter( 'posts_where', 'wpse_modified' );\n\n// Fetch posts\n$query = new WP_Query( $lastupdated_args );\n</code></pre>\n\n<p>where you can define the filter callback as:</p>\n\n<pre><code>function wpse_modified( $where )\n{\n global $wpdb;\n // Run only once:\n remove_filter( current_filter(), __FUNCTION__ );\n // Append custom SQL\n return $where . \" AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';\n}\n</code></pre>\n\n<p>Though it would be handy to be able to use this kind of <em>date queries</em>:</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ 'before' => 'post_modified' ]\n ],\n];\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ \n 'column' => 'post_modified_gmt', \n 'after' => 'post_date_gmt', \n 'inclusive' => false \n ]\n ],\n];\n</code></pre>\n\n<p>That's maybe an idea for a core ticket! ;-)</p>\n"
},
{
"answer_id": 348600,
"author": "Amin",
"author_id": 113633,
"author_profile": "https://wordpress.stackexchange.com/users/113633",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe something like this will help, i had a situation where i needed to get posts that were modified at least 1 day after they were created: </p>\n\n<pre><code>function dw_get_modified_posts($author, $post_type = 'post') {\n global $wpdb;\n\n $result = $wpdb->get_results(\n $wpdb->prepare(\"\n SELECT ID\n FROM `$wpdb->posts`\n WHERE UNIX_TIMESTAMP(post_modified_gmt) - UNIX_TIMESTAMP(post_date_gmt) > 86400\n AND post_type = %s\n AND post_author = %d\n \", $post_type, $author)\n );\n\n return array_map(function ($post) {\n return $post->ID;\n\n }, (array) $result);\n}\n</code></pre>\n\n<p><code>86400</code> is the 1 day margin which you can edit it, now you can make a wp_query out of it:</p>\n\n<pre><code>$posts_list = new WP_Query([\n 'post__in' => dw_get_modified_posts() ?: [0]\n]);\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208347",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83191/"
] |
take `the_category()` as an example:
Here is the output of the\_category function in the wordpress loop:
```
<ul class="post-categories">
<li>
<a href="http://example.com/category/another-category/" rel="category tag">
Another Category
</a>
</li>
<li>
<a href="http://example.com/category/uncategorized/" rel="category tag">
Uncategorized
</a>
</li>
</ul>
```
so we need a way to add attributes like some other classes, data attributes and ... to the list so it outputs something like this:
```
<ul id="drop1" class="f-dropdown" data-dropdown-content aria-hidden="true" tabindex="-1">
<li>
<a href="http://example.com/category/another-category/" rel="category tag">
Another Category
</a>
</li>
<li>
<a href="http://example.com/category/uncategorized/" rel="category tag">
Uncategorized
</a>
</li>
</ul>
```
|
You can use the `posts_where` filter:
```
// Add custom filter
add_filter( 'posts_where', 'wpse_modified' );
// Fetch posts
$query = new WP_Query( $lastupdated_args );
```
where you can define the filter callback as:
```
function wpse_modified( $where )
{
global $wpdb;
// Run only once:
remove_filter( current_filter(), __FUNCTION__ );
// Append custom SQL
return $where . " AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';
}
```
Though it would be handy to be able to use this kind of *date queries*:
```
$args = [
'date_query' => [
[ 'before' => 'post_modified' ]
],
];
```
and
```
$args = [
'date_query' => [
[
'column' => 'post_modified_gmt',
'after' => 'post_date_gmt',
'inclusive' => false
]
],
];
```
That's maybe an idea for a core ticket! ;-)
|
208,350 |
<p>I want to make a logo manager in the Customizer, but how do I set different image sizes with the <code>WP_Customize_Cropped_Image_Control</code> class? </p>
<p>Example from <a href="https://make.wordpress.org/core/2015/07/16/new-customizer-media-controls-in-4-3-and-4-2/" rel="nofollow">Make WordPress Core:</a></p>
<pre><code>$wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'cropped_image', array(
'section' => 'background_image',
'label' => __( 'Croppable Image' ),
'flex_width' => true, // Allow any width, making the specified value recommended. False by default.
'flex_height' => false, // Require the resulting image to be exactly as tall as the height attribute (default).
'width' => 1920,
'height' => 1080,
) ) );
</code></pre>
|
[
{
"answer_id": 208314,
"author": "Bharat",
"author_id": 83408,
"author_profile": "https://wordpress.stackexchange.com/users/83408",
"pm_score": 0,
"selected": false,
"text": "<pre><code>$lastupdated_args = array(\n 'paged' => $paged,\n 'post_status' => 'publish',\n 'post_type' = 'post',\n 'orderby' => 'modified',\n 'ignore_sticky_posts' => '1'\n);\n</code></pre>\n\n<p>I think this will help you.</p>\n"
},
{
"answer_id": 208338,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>You can use the <code>posts_where</code> filter:</p>\n\n<pre><code>// Add custom filter\nadd_filter( 'posts_where', 'wpse_modified' );\n\n// Fetch posts\n$query = new WP_Query( $lastupdated_args );\n</code></pre>\n\n<p>where you can define the filter callback as:</p>\n\n<pre><code>function wpse_modified( $where )\n{\n global $wpdb;\n // Run only once:\n remove_filter( current_filter(), __FUNCTION__ );\n // Append custom SQL\n return $where . \" AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';\n}\n</code></pre>\n\n<p>Though it would be handy to be able to use this kind of <em>date queries</em>:</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ 'before' => 'post_modified' ]\n ],\n];\n</code></pre>\n\n<p>and</p>\n\n<pre><code>$args = [\n 'date_query' => [\n [ \n 'column' => 'post_modified_gmt', \n 'after' => 'post_date_gmt', \n 'inclusive' => false \n ]\n ],\n];\n</code></pre>\n\n<p>That's maybe an idea for a core ticket! ;-)</p>\n"
},
{
"answer_id": 348600,
"author": "Amin",
"author_id": 113633,
"author_profile": "https://wordpress.stackexchange.com/users/113633",
"pm_score": 0,
"selected": false,
"text": "<p>Maybe something like this will help, i had a situation where i needed to get posts that were modified at least 1 day after they were created: </p>\n\n<pre><code>function dw_get_modified_posts($author, $post_type = 'post') {\n global $wpdb;\n\n $result = $wpdb->get_results(\n $wpdb->prepare(\"\n SELECT ID\n FROM `$wpdb->posts`\n WHERE UNIX_TIMESTAMP(post_modified_gmt) - UNIX_TIMESTAMP(post_date_gmt) > 86400\n AND post_type = %s\n AND post_author = %d\n \", $post_type, $author)\n );\n\n return array_map(function ($post) {\n return $post->ID;\n\n }, (array) $result);\n}\n</code></pre>\n\n<p><code>86400</code> is the 1 day margin which you can edit it, now you can make a wp_query out of it:</p>\n\n<pre><code>$posts_list = new WP_Query([\n 'post__in' => dw_get_modified_posts() ?: [0]\n]);\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208350",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83187/"
] |
I want to make a logo manager in the Customizer, but how do I set different image sizes with the `WP_Customize_Cropped_Image_Control` class?
Example from [Make WordPress Core:](https://make.wordpress.org/core/2015/07/16/new-customizer-media-controls-in-4-3-and-4-2/)
```
$wp_customize->add_control( new WP_Customize_Cropped_Image_Control( $wp_customize, 'cropped_image', array(
'section' => 'background_image',
'label' => __( 'Croppable Image' ),
'flex_width' => true, // Allow any width, making the specified value recommended. False by default.
'flex_height' => false, // Require the resulting image to be exactly as tall as the height attribute (default).
'width' => 1920,
'height' => 1080,
) ) );
```
|
You can use the `posts_where` filter:
```
// Add custom filter
add_filter( 'posts_where', 'wpse_modified' );
// Fetch posts
$query = new WP_Query( $lastupdated_args );
```
where you can define the filter callback as:
```
function wpse_modified( $where )
{
global $wpdb;
// Run only once:
remove_filter( current_filter(), __FUNCTION__ );
// Append custom SQL
return $where . " AND {$wpdb->posts}.post_modified} != {$wpdb->posts}.post_modified} ';
}
```
Though it would be handy to be able to use this kind of *date queries*:
```
$args = [
'date_query' => [
[ 'before' => 'post_modified' ]
],
];
```
and
```
$args = [
'date_query' => [
[
'column' => 'post_modified_gmt',
'after' => 'post_date_gmt',
'inclusive' => false
]
],
];
```
That's maybe an idea for a core ticket! ;-)
|
208,354 |
<p>I need to add multiple taxonomy filters to the functions.php file to remove (3) irrelevant taxonomies from the Yoast SEO sitemap index. I have been able to successfully add one filter, but when I add the other two filters, I keep getting a 500 server error. I should note that I am a novice when it comes to PHP so I imagine there is something fairly simple that I am missing here.</p>
<p>The filter that works by itself:</p>
<pre><code>function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'scope' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
</code></pre>
<p>but the following code did not work for adding the two remaining filters:</p>
<pre><code>function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'scope' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'layout_type' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'module_width' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
</code></pre>
<p>Many thanks in advance for the help!</p>
<p>-Mark</p>
|
[
{
"answer_id": 208357,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 2,
"selected": false,
"text": "<p>Try PHP's <a href=\"http://php.net/manual/en/function.in-array.php\" rel=\"nofollow\"><code>in_array</code></a>. </p>\n\n<pre><code>function sitemap_exclude_taxonomy( $value, $taxonomy ) {\n $excludes = ['scope', 'layout_type', 'foo', 'bar'];\n if ( in_array( $taxonomy, $excludes ) return true;\n}\n\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 208358,
"author": "DACrosby",
"author_id": 31367,
"author_profile": "https://wordpress.stackexchange.com/users/31367",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot have the same function name more than once. Instead, rename them:</p>\n\n<pre><code>function sitemap_exclude_taxonomy_1( $value, $taxonomy ) {\n if ( 'scope' == $taxonomy ) return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy_1', 10, 2 );\n\nfunction sitemap_exclude_taxonomy_2( $value, $taxonomy ) {\n if ( 'layout_type' == $taxonomy ) return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy_2', 10, 2 );\n\nfunction sitemap_exclude_taxonomy_3( $value, $taxonomy ) {\n if ( 'module_width' == $taxonomy ) return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy_3', 10, 2 );\n</code></pre>\n\n<p>Or better yet, combine them in one tidy function:</p>\n\n<pre><code>function sitemap_exclude_taxonomy( $value, $taxonomy ) {\n if ( 'scope' == $taxonomy\n || 'layout_type' == $taxonomy\n || 'module_width' == $taxonomy )\n return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );\n</code></pre>\n"
}
] |
2015/11/11
|
[
"https://wordpress.stackexchange.com/questions/208354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83428/"
] |
I need to add multiple taxonomy filters to the functions.php file to remove (3) irrelevant taxonomies from the Yoast SEO sitemap index. I have been able to successfully add one filter, but when I add the other two filters, I keep getting a 500 server error. I should note that I am a novice when it comes to PHP so I imagine there is something fairly simple that I am missing here.
The filter that works by itself:
```
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'scope' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
```
but the following code did not work for adding the two remaining filters:
```
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'scope' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'layout_type' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
if ( 'module_width' == $taxonomy ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
```
Many thanks in advance for the help!
-Mark
|
Try PHP's [`in_array`](http://php.net/manual/en/function.in-array.php).
```
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
$excludes = ['scope', 'layout_type', 'foo', 'bar'];
if ( in_array( $taxonomy, $excludes ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
```
|
208,367 |
<p>I have recently been invited to the letsencrypt SSL beta, and have now spotted a potential problem.</p>
<p>My main site tomjn.com is a multisite, and I have the opportunity to add certificates for tomjn.com and www.tomjn.com, but I also have other subdomains, subdomains i do not have SSL certificates for.</p>
<p>Is it possible to have tomjn.com served over SSL via WordPress, but only tomjn.com? Or must I force all the blogs/sites in my install to use SSL? If so, how is this best done?</p>
|
[
{
"answer_id": 208357,
"author": "Will",
"author_id": 44795,
"author_profile": "https://wordpress.stackexchange.com/users/44795",
"pm_score": 2,
"selected": false,
"text": "<p>Try PHP's <a href=\"http://php.net/manual/en/function.in-array.php\" rel=\"nofollow\"><code>in_array</code></a>. </p>\n\n<pre><code>function sitemap_exclude_taxonomy( $value, $taxonomy ) {\n $excludes = ['scope', 'layout_type', 'foo', 'bar'];\n if ( in_array( $taxonomy, $excludes ) return true;\n}\n\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );\n</code></pre>\n"
},
{
"answer_id": 208358,
"author": "DACrosby",
"author_id": 31367,
"author_profile": "https://wordpress.stackexchange.com/users/31367",
"pm_score": 1,
"selected": false,
"text": "<p>You cannot have the same function name more than once. Instead, rename them:</p>\n\n<pre><code>function sitemap_exclude_taxonomy_1( $value, $taxonomy ) {\n if ( 'scope' == $taxonomy ) return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy_1', 10, 2 );\n\nfunction sitemap_exclude_taxonomy_2( $value, $taxonomy ) {\n if ( 'layout_type' == $taxonomy ) return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy_2', 10, 2 );\n\nfunction sitemap_exclude_taxonomy_3( $value, $taxonomy ) {\n if ( 'module_width' == $taxonomy ) return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy_3', 10, 2 );\n</code></pre>\n\n<p>Or better yet, combine them in one tidy function:</p>\n\n<pre><code>function sitemap_exclude_taxonomy( $value, $taxonomy ) {\n if ( 'scope' == $taxonomy\n || 'layout_type' == $taxonomy\n || 'module_width' == $taxonomy )\n return true;\n}\nadd_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );\n</code></pre>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208367",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/736/"
] |
I have recently been invited to the letsencrypt SSL beta, and have now spotted a potential problem.
My main site tomjn.com is a multisite, and I have the opportunity to add certificates for tomjn.com and www.tomjn.com, but I also have other subdomains, subdomains i do not have SSL certificates for.
Is it possible to have tomjn.com served over SSL via WordPress, but only tomjn.com? Or must I force all the blogs/sites in my install to use SSL? If so, how is this best done?
|
Try PHP's [`in_array`](http://php.net/manual/en/function.in-array.php).
```
function sitemap_exclude_taxonomy( $value, $taxonomy ) {
$excludes = ['scope', 'layout_type', 'foo', 'bar'];
if ( in_array( $taxonomy, $excludes ) return true;
}
add_filter( 'wpseo_sitemap_exclude_taxonomy', 'sitemap_exclude_taxonomy', 10, 2 );
```
|
208,384 |
<p>I am using storefront theme, where there is options for the Full Width in the pages but not in the Product Page and Product Category Page in the Store Front Theme</p>
<p>As i played with css and i go this line in the template</p>
<pre><code><div id="primary" class="content-area">
</code></pre>
<p>As i removed the content-area class i can able to remove the space of the sidebar, but that is not what i was expected, because it is removing sidebar in whole website</p>
<p>I need to remove it only in product page but not in product-category page, how this can be achieved in the storefront theme</p>
|
[
{
"answer_id": 217419,
"author": "Iggy",
"author_id": 32150,
"author_profile": "https://wordpress.stackexchange.com/users/32150",
"pm_score": 2,
"selected": false,
"text": "<p>for product page, you can put in functions.php</p>\n\n<pre><code>function remove_storefront_sidebar() {\n if ( is_product() ) {\n remove_action( 'storefront_sidebar', 'storefront_get_sidebar', 10 );\n }\n}\nadd_action( 'get_header', 'remove_storefront_sidebar' );\n</code></pre>\n\n<p>It works with latest woocommerce 2.5.2\nAlso CSS is needed:</p>\n\n<pre><code>.single-product.right-sidebar .content-area {\n float: none;\n margin-right: 0;\n width: 100%;\n}\n</code></pre>\n"
},
{
"answer_id": 244368,
"author": "adam",
"author_id": 105903,
"author_profile": "https://wordpress.stackexchange.com/users/105903",
"pm_score": -1,
"selected": false,
"text": "<p>just go to theme options, select woocommerce, and change the product, shop, and categories layout to 1 column (instead of 2 column with sidebar)</p>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71459/"
] |
I am using storefront theme, where there is options for the Full Width in the pages but not in the Product Page and Product Category Page in the Store Front Theme
As i played with css and i go this line in the template
```
<div id="primary" class="content-area">
```
As i removed the content-area class i can able to remove the space of the sidebar, but that is not what i was expected, because it is removing sidebar in whole website
I need to remove it only in product page but not in product-category page, how this can be achieved in the storefront theme
|
for product page, you can put in functions.php
```
function remove_storefront_sidebar() {
if ( is_product() ) {
remove_action( 'storefront_sidebar', 'storefront_get_sidebar', 10 );
}
}
add_action( 'get_header', 'remove_storefront_sidebar' );
```
It works with latest woocommerce 2.5.2
Also CSS is needed:
```
.single-product.right-sidebar .content-area {
float: none;
margin-right: 0;
width: 100%;
}
```
|
208,423 |
<p>I have AJAX form submission working fine locally. But when pushed to my staging server the process page is 404'ing. I cannot access it directly neither as it 404's but checking on the server and its 100% there with correct permissions too.</p>
<p>The code for the AJAX:</p>
<pre><code>$('body').on('submit', '.product-form', function(e){
e.preventDefault();
$.ajax({
url : '/wp-content/themes/hinge_client_theme/page-templates/template-parts/template-logic/send-form.php',
type : 'POST',
data : thisForm.serialize(),
before : $(".error-message").remove(),
success : function(data) {
// removed for question
},
});
});
</code></pre>
<p>That send-form.php is 404ing on the network tab, any ideas whats going on? Working fine locally.</p>
|
[
{
"answer_id": 208431,
"author": "Mateusz Paulski",
"author_id": 83472,
"author_profile": "https://wordpress.stackexchange.com/users/83472",
"pm_score": -1,
"selected": false,
"text": "<p>maybe try this:</p>\n\n<pre><code>$('body').on('submit', '.product-form', function(e){\n e.preventDefault();\n $.ajax({\n url : get_template_directory() . '/page-templates/template-parts/template-logic/send-form.php',\n type : 'POST',\n data : thisForm.serialize(),\n before : $(\".error-message\").remove(),\n success : function(data) { \n // removed for question\n },\n });\n});\n</code></pre>\n"
},
{
"answer_id": 210331,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 1,
"selected": false,
"text": "<p>Take a look at <a href=\"https://codex.wordpress.org/Function_Reference/wp_localize_script\" rel=\"nofollow\">wp localize script</a>. It'll allow you to encode your url into a separate javascript object before your script is loaded. <a href=\"https://codex.wordpress.org/Function_Reference/get_template_directory\" rel=\"nofollow\">get_template_directory</a> retrieves the absolute path to the directory of the current theme. Use it in case your WP install directory is different than your local development. The theme directory can also change if the folder is renamed or <a href=\"https://codex.wordpress.org/Determining_Plugin_and_Content_Directories\" rel=\"nofollow\">WP_CONTENT</a> is in a different location.</p>\n\n<pre><code><?php\n\n// Register the script\nwp_register_script( 'some_handle', 'path/to/myscript.js' );\n\n// Localize the script with new data\n$translation_array = array(\n 'send_form_php' => get_template_directory() . '/page-templates/template-parts/template-logic/send-form.php', \n);\nwp_localize_script( 'some_handle', 'object_name', $translation_array );\n\n// Enqueued script with localized data.\nwp_enqueue_script( 'some_handle' );\n</code></pre>\n\n<p>Then in your js file you can use:</p>\n\n<pre><code><script>\n// alerts 'Path to the send-form.php'\nalert( object_name.send_form_php );\n</script> \n</code></pre>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208423",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82942/"
] |
I have AJAX form submission working fine locally. But when pushed to my staging server the process page is 404'ing. I cannot access it directly neither as it 404's but checking on the server and its 100% there with correct permissions too.
The code for the AJAX:
```
$('body').on('submit', '.product-form', function(e){
e.preventDefault();
$.ajax({
url : '/wp-content/themes/hinge_client_theme/page-templates/template-parts/template-logic/send-form.php',
type : 'POST',
data : thisForm.serialize(),
before : $(".error-message").remove(),
success : function(data) {
// removed for question
},
});
});
```
That send-form.php is 404ing on the network tab, any ideas whats going on? Working fine locally.
|
Take a look at [wp localize script](https://codex.wordpress.org/Function_Reference/wp_localize_script). It'll allow you to encode your url into a separate javascript object before your script is loaded. [get\_template\_directory](https://codex.wordpress.org/Function_Reference/get_template_directory) retrieves the absolute path to the directory of the current theme. Use it in case your WP install directory is different than your local development. The theme directory can also change if the folder is renamed or [WP\_CONTENT](https://codex.wordpress.org/Determining_Plugin_and_Content_Directories) is in a different location.
```
<?php
// Register the script
wp_register_script( 'some_handle', 'path/to/myscript.js' );
// Localize the script with new data
$translation_array = array(
'send_form_php' => get_template_directory() . '/page-templates/template-parts/template-logic/send-form.php',
);
wp_localize_script( 'some_handle', 'object_name', $translation_array );
// Enqueued script with localized data.
wp_enqueue_script( 'some_handle' );
```
Then in your js file you can use:
```
<script>
// alerts 'Path to the send-form.php'
alert( object_name.send_form_php );
</script>
```
|
208,457 |
<p>I am continuing on from a topic I already <a href="https://wordpress.stackexchange.com/questions/208353/different-text-widgets-in-sidebar-on-many-different-pages">posted</a> but with a different angle. Please bare with me as I try to provide as much information as possible.</p>
<p>I am looking to add a simple <strong>text area</strong> called "Quick Facts" to a bunch of animal/cryptid <strong>pages</strong> in one part of my site. This will provide a list of facts and figures for each animal.</p>
<p>Here are the steps I have taken in order to set this up:</p>
<ul>
<li>Created left and right sidebars in functions.php, called cryptid-sidebar-widgets-left (for the left sidebar) and cryptid-sidebar-widgets (for the right sidebar). The left sidebar is where the "Quick Facts" area is going to go. </li>
<li>Created a new page template called cryptofact-page.php. It grabs a custom header as well as the two new sidebars.</li>
<li>Created pages in wordpress with each individual animal.</li>
<li>Pop a text widget into the left sidebar and start writing down quick facts.</li>
</ul>
<p>It ends up looking like this: </p>
<p><a href="https://i.stack.imgur.com/FE5w4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FE5w4.png" alt="enter image description here"></a></p>
<p><strong>The problem is that, of course, this sidebar repeats the same text data for all the pages. I need it to display unique data for each animal's page instead.</strong></p>
<p>I am wondering how to best tackle this issue because I am going to have <strong>over 100+</strong> of these animal fact pages. Here are the options I've gathered and what problems each one presents. I am new web developer so I want to know how a professional site would tackle this issue. </p>
<ol>
<li><p><strong>Register sidebars and create sidebar-___.php for each new page:</strong> I can go back into functions.php and continue to register 100+ different sidebars for each creature. From there I can make individual php pages called sidebar-creaturename.php and call them from the same template using custom fields. </p>
<ul>
<li>In one tutorial I read, I can place the following into my cryptofact-page.php template. Then go to the custom field place in my pages and add <em>Key</em>:sidebar and <em>Value</em>: (The name of the sidebar-___.php) that I created for this animal. This allows me to keep the same template for all the pages but calls in a different sidebar for each one. </li>
</ul>
<p><code><?php $sidebar = get_post_meta($post->ID, "sidebar", true);
get_sidebar($sidebar);
?></code></p></li>
</ol>
<p>User Will, from my last topic, told me about putting this code into my page template or a sidebar I would make. And introduced me to the idea of Custom Fields.</p>
<pre><code> <?php
var $meta = get_post_meta($post->id, "your-key", true);
if(!empty($meta)):
?>
<aside>
<?php echo $meta; ?>
</aside>
<?php endif; ?>
</code></pre>
<p>The problem was...I added this and it kinda tore up my page. So I wasn't sure if I added it in the wrong place or if I was missing something. If anyone can expand on this, it would be appreciated. I will add code to the end of this post that shows my cryptofact-page.php template and the potential sidebar I will use.</p>
<ol start="2">
<li><p><strong>Using Widget Logic Plugin (or similar plugin):</strong> I am not too fond of using a plugin when I can supposedly do this through coding my own files. This was a suggestion I found when researching my problem. In short, this plugin adds an extra field to each other widget that can specify which page to show that particular widget. </p>
<ul>
<li>I add the Text Widget to the one sidebar (cryptid-sidebar-widgets-left) that I have added to the cryptofacts-page.php template. Under the Text Widget area is where I can use Widget Logic to add <strong>is_page('pageid')</strong> and write down the page id for that animal's page. </li>
<li>I repeat this process over and over so now that when I open the Widgets area under the Customizer, there are now 100+ Text Widgets that I have to wade through for that one sidebar. While this is easy to execute, it also seems a bit like a cluster-f. I want the Text Widget title to only say "Quick Facts" but this would mean I would have many many Text Widgets named Quick Facts with no good way to tell the difference between them at a glance (like let's say I have to go back and add or change facts, I'll need to manually open all of them and figure out which is the creature I want).</li>
</ul></li>
<li><p><strong>Getting rid of the left sidebar completely.</strong> I thought about it and I suppose I could get rid of the left sidebar completely and while I'm writing each animal's <strong>page</strong> in wordpress, I can add a <strong>quickfact div</strong> that floats to the left of the animal's <strong>main content div</strong>. This was my initial idea when I first thought about these Animal Factoid Pages, but when I went to research different tutorials on adding columns and such, many of them suggested to just add a left sidebar instead. It would mean I don't have to deal with widgets or sidebars and all the "quick facts" go into the same input area as the rest of the content. It just means dealing with a lot more divs (which is not a problem since I'm dealing with many in the sidebar as it is). </p></li>
</ol>
<p>Once again, I am wondering what would be the most efficient way to go about doing this for 100+ individual animal pages? What is the most common practice to tackle this for a large website?</p>
<p>Wordpress is fairly new to me and the idea of Custom Fields was just presented to me yesterday so Example #1 is all I really know about Custom Fields. </p>
<p>I am looking for any other ways to do this and I'm willing to take the time to learn to do this right. I don't expect this to be easy. It is going to be tedious because there are so many pages but I just don't want to seem like an idiot taking a super extraneous way to go about this. </p>
<p><strong>My cryptofact-page.php template:</strong>
<pre><code>get_header(); ?>
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php if ( is_active_sidebar( 'cryptid-sidebar-widgets-left' ) ) :
dynamic_sidebar( 'cryptid-sidebar-widgets-left' ); endif; ?>
</ul>
</div>
<?php if ( have_posts() ) : ?>
<!--if there are posts, start the loop-->
<div class="cryptid-container">
<?php while ( have_posts() ) : the_post(); ?>
<!--get the content template for the current post format.-->
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
</div> <!-- .cryptid-container-->
<?php else : ?>
<!--If no content, get content template for 'no posts found'-->
<div class="cryptid-container">
<?php get_template_part( 'content', 'none' ); ?>
</div>
<?php endif; ?>
<div class="cryptid-sidebar-right">
<ul class="cryptid-sidebar-widgets">
<?php if ( is_active_sidebar( 'cryptid-sidebar-widgets' ) ) :
dynamic_sidebar( 'cryptid-sidebar-widgets' );
endif; ?>
</ul>
</div>
<?php get_footer();
?>
</code></pre>
<p><strong>My Sidebar:</strong> Currently I don't need to have a separate sidebar-____.php file. It seems to work with just registering into the functions.php and calling it in the template. But if I had one (or needed one for this) it would probably look like this:</p>
<pre><code><?php
/**
* Displays sidebar widgets for front page
*
* @since ctheme 1.0
*/
?>
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php if ( is_active_sidebar( 'cryptid-sidebar-widgets-left' ) ) :
dynamic_sidebar( 'cryptid-sidebar-widgets-left' );
endif; ?>
</ul>
</div>
</code></pre>
<p>Thanks so much for all your help and for taking the time to read this. I hope I have provided enough information so I can be aided in accomplishing this.</p>
<p><strong>EDIT- Potential Answer:</strong></p>
<p>So I began to read up on Custom Fields again and also began to code Meta Box into my functions.php. I took a break and then realized that there was a simple solution stemming from <strong>Example #2</strong> above: <strong>Text Widget and Widget Logic Plugin</strong>. I still want to tackle this problem in a more sophisticated manner but I'll post here what I did to make what I want happen.</p>
<p>The only real problem with #2 was that when I went to look into the Customizer- Widget area, under the Cryptid Left Sidebar all I saw was this:</p>
<p>Text Widget: Quick Facts</p>
<p>Text Widget: Quick Facts</p>
<p>Text Widget: Quick Facts (and on)</p>
<p>As stated above, if I had to go back to change the text data for one of these creatures, I wouldn't know which one to go into just by a glance. So, I simply went in search for another widget. After trying a few other Text Widgets out, I settled on <strong>Enhanced Text Widget</strong>. This widget gave me the option to title the widget but not show the title in the output. </p>
<p>I titled the widget by the name of the creature. Then in the text field, I simply gave the widget the title "Quick Facts" above all the other data I had coded for the quick facts. I then gave that title the same div that the rest of the widget titles already had, in my case it was called "widgettitle"</p>
<pre><code><div class="widgettitle"><h2>Quick Facts</h2></div>
</code></pre>
<p>It kinda messed up the size of the font but the rest of the styling is there. I can fix that easily in my style.css file.</p>
<p>Then, I used Widget Logic, which adds an extra field to the bottom of each widget. So in this area, I can type in the following so it only shows up for that page:</p>
<pre><code>is_page('pageid')
</code></pre>
<p>In the end we have a widget customize area that now looks like this:</p>
<p>Enhanced Text: Loch Ness</p>
<p>Enhanced Text: Ogopogo</p>
<p>Enhanced Text: Bigfoot (and on)</p>
<p>Each with their own quick facts inside and now I can quickly see which creature's widget it is versus before.</p>
<p>It feels kinda noobie to do it this way, like I should be taking a more sophisticated path but it works out and it seems quite clean. I am not sure how well the site will handle this x100, but it doesn't seem like it should be that difficult or heavy to process. </p>
<p>Also I just realized...I have to do something similar if I wanted a little map for each animal location above the Quick Facts area (as seen in the image). I'll have to tackle that as well...but I may just stick the map in the page's content's instead. This is going to be one stuffed sidebar as it is. </p>
<p>Further help is greatly appreciated! </p>
<p><strong>FINAL EDIT AND SOLUTION:</strong> Thanks to Milo!</p>
<p>Taking the accepted answer below by Milo, I decided to fully implement Custom Fields.
I went through the trouble of creating my own meta box, which came out fairly decently. I ended up reverting to <em>Advanced Custom Fields plugin</em> cause their meta boxes were nicer. I don't even need the plugin, but I kept it around in case I wanted to use it for something more complicated in the future. Using <em>Advanced Custom Fields plugin</em> (or the Custom Fields box without the plugin) I created the custom field key <strong>cryptid_post_class</strong>.</p>
<p>I then altered my page template (cryptofacts-page.php) to remove the sidebar and in it's place GET the data from the custom field. It is imperative to use proper wrappers as it would appear with the sidebar from before (Miloisawesome). </p>
<pre><code>get_header(); ?>
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php
$meta = get_post_meta(get_the_ID(), "cryptid_post_class", true);
if( !empty($meta) ):
?>
<li>
<?php echo $meta; ?>
</li>
<?php
endif;
?>
</ul>
</div>
<?php if ( have_posts() ) : ?>
<!--if there are posts, start the loop-->
<div class="cryptid-container">
<?php while ( have_posts() ) : the_post(); ?>
<!--get the content template for the current post format.-->
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
</code></pre>
<p>Here are some pictures to illustrate the process.</p>
<ol>
<li><strong>Setup the template with proper wrappers</strong></li>
</ol>
<p><a href="https://i.stack.imgur.com/DNUCi.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/DNUCi.png" alt="enter image description here"></a>
2. <strong>Setting up the Custom Fields area</strong></p>
<p><a href="https://i.stack.imgur.com/LxlPh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LxlPh.png" alt="enter image description here"></a>
3. <strong>End result minus some css tweaks since I used a backup template while playing with this</strong></p>
<p><a href="https://i.stack.imgur.com/TfcCu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TfcCu.png" alt="enter image description here"></a></p>
<p>Hopefully this will help any other newbie WordPress developers make things clearer and approach the rather awesome custom fields part of WP!</p>
|
[
{
"answer_id": 208463,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": true,
"text": "<p>You <em>could</em> dynamically register sidebars. When you register sidebars, you could query for all of your animal pages, loop over all pages, and register a unique sidebar for each page. Adding a page would automatically create a sidebar for it.</p>\n\n<p><em>However</em> - that's a lot of sidebars. For something tightly coupled with the page content, I would rather handle it with custom fields via a <a href=\"https://codex.wordpress.org/Function_Reference/add_meta_box\">custom meta box</a> that contained your pre-defined field(s).</p>\n\n<p>As for why your use of post meta disturbed the layout of your site, it's probably just an issue of markup / styling. The simplest course may be to get the layout looking right with a sidebar and text widget, then copy the markup that's generated when you view the page, and use that as the wrapper markup for you custom fields. Looking at your template above, widgets will appear as <code><li></code>s within a <code><ul></code>, so try that when adding your post meta:</p>\n\n<pre><code><div class=\"cryptid-sidebar-left\">\n <ul class=\"cryptid-sidebar-widgets-left\">\n <?php\n $meta = get_post_meta(get_the_ID(), \"your-key\", true);\n if( !empty($meta) ): \n ?>\n <li>\n <?php echo $meta; ?>\n </li>\n <?php\n endif;\n ?>\n </ul>\n</div>\n</code></pre>\n"
},
{
"answer_id": 208489,
"author": "oompahlumpa",
"author_id": 83511,
"author_profile": "https://wordpress.stackexchange.com/users/83511",
"pm_score": 0,
"selected": false,
"text": "<p>I had a site with an issue that sounds alot like the one you are mentioned. I used a plugin \"custom sidebars\" I believe it was called in which it would aloud me to build a sidebar on a specific page and default if not set. Is this what you are looking for?</p>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208457",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83426/"
] |
I am continuing on from a topic I already [posted](https://wordpress.stackexchange.com/questions/208353/different-text-widgets-in-sidebar-on-many-different-pages) but with a different angle. Please bare with me as I try to provide as much information as possible.
I am looking to add a simple **text area** called "Quick Facts" to a bunch of animal/cryptid **pages** in one part of my site. This will provide a list of facts and figures for each animal.
Here are the steps I have taken in order to set this up:
* Created left and right sidebars in functions.php, called cryptid-sidebar-widgets-left (for the left sidebar) and cryptid-sidebar-widgets (for the right sidebar). The left sidebar is where the "Quick Facts" area is going to go.
* Created a new page template called cryptofact-page.php. It grabs a custom header as well as the two new sidebars.
* Created pages in wordpress with each individual animal.
* Pop a text widget into the left sidebar and start writing down quick facts.
It ends up looking like this:
[](https://i.stack.imgur.com/FE5w4.png)
**The problem is that, of course, this sidebar repeats the same text data for all the pages. I need it to display unique data for each animal's page instead.**
I am wondering how to best tackle this issue because I am going to have **over 100+** of these animal fact pages. Here are the options I've gathered and what problems each one presents. I am new web developer so I want to know how a professional site would tackle this issue.
1. **Register sidebars and create sidebar-\_\_\_.php for each new page:** I can go back into functions.php and continue to register 100+ different sidebars for each creature. From there I can make individual php pages called sidebar-creaturename.php and call them from the same template using custom fields.
* In one tutorial I read, I can place the following into my cryptofact-page.php template. Then go to the custom field place in my pages and add *Key*:sidebar and *Value*: (The name of the sidebar-\_\_\_.php) that I created for this animal. This allows me to keep the same template for all the pages but calls in a different sidebar for each one.`<?php $sidebar = get_post_meta($post->ID, "sidebar", true);
get_sidebar($sidebar);
?>`
User Will, from my last topic, told me about putting this code into my page template or a sidebar I would make. And introduced me to the idea of Custom Fields.
```
<?php
var $meta = get_post_meta($post->id, "your-key", true);
if(!empty($meta)):
?>
<aside>
<?php echo $meta; ?>
</aside>
<?php endif; ?>
```
The problem was...I added this and it kinda tore up my page. So I wasn't sure if I added it in the wrong place or if I was missing something. If anyone can expand on this, it would be appreciated. I will add code to the end of this post that shows my cryptofact-page.php template and the potential sidebar I will use.
2. **Using Widget Logic Plugin (or similar plugin):** I am not too fond of using a plugin when I can supposedly do this through coding my own files. This was a suggestion I found when researching my problem. In short, this plugin adds an extra field to each other widget that can specify which page to show that particular widget.
* I add the Text Widget to the one sidebar (cryptid-sidebar-widgets-left) that I have added to the cryptofacts-page.php template. Under the Text Widget area is where I can use Widget Logic to add **is\_page('pageid')** and write down the page id for that animal's page.
* I repeat this process over and over so now that when I open the Widgets area under the Customizer, there are now 100+ Text Widgets that I have to wade through for that one sidebar. While this is easy to execute, it also seems a bit like a cluster-f. I want the Text Widget title to only say "Quick Facts" but this would mean I would have many many Text Widgets named Quick Facts with no good way to tell the difference between them at a glance (like let's say I have to go back and add or change facts, I'll need to manually open all of them and figure out which is the creature I want).
3. **Getting rid of the left sidebar completely.** I thought about it and I suppose I could get rid of the left sidebar completely and while I'm writing each animal's **page** in wordpress, I can add a **quickfact div** that floats to the left of the animal's **main content div**. This was my initial idea when I first thought about these Animal Factoid Pages, but when I went to research different tutorials on adding columns and such, many of them suggested to just add a left sidebar instead. It would mean I don't have to deal with widgets or sidebars and all the "quick facts" go into the same input area as the rest of the content. It just means dealing with a lot more divs (which is not a problem since I'm dealing with many in the sidebar as it is).
Once again, I am wondering what would be the most efficient way to go about doing this for 100+ individual animal pages? What is the most common practice to tackle this for a large website?
Wordpress is fairly new to me and the idea of Custom Fields was just presented to me yesterday so Example #1 is all I really know about Custom Fields.
I am looking for any other ways to do this and I'm willing to take the time to learn to do this right. I don't expect this to be easy. It is going to be tedious because there are so many pages but I just don't want to seem like an idiot taking a super extraneous way to go about this.
**My cryptofact-page.php template:**
```
get_header(); ?>
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php if ( is_active_sidebar( 'cryptid-sidebar-widgets-left' ) ) :
dynamic_sidebar( 'cryptid-sidebar-widgets-left' ); endif; ?>
</ul>
</div>
<?php if ( have_posts() ) : ?>
<!--if there are posts, start the loop-->
<div class="cryptid-container">
<?php while ( have_posts() ) : the_post(); ?>
<!--get the content template for the current post format.-->
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
</div> <!-- .cryptid-container-->
<?php else : ?>
<!--If no content, get content template for 'no posts found'-->
<div class="cryptid-container">
<?php get_template_part( 'content', 'none' ); ?>
</div>
<?php endif; ?>
<div class="cryptid-sidebar-right">
<ul class="cryptid-sidebar-widgets">
<?php if ( is_active_sidebar( 'cryptid-sidebar-widgets' ) ) :
dynamic_sidebar( 'cryptid-sidebar-widgets' );
endif; ?>
</ul>
</div>
<?php get_footer();
?>
```
**My Sidebar:** Currently I don't need to have a separate sidebar-\_\_\_\_.php file. It seems to work with just registering into the functions.php and calling it in the template. But if I had one (or needed one for this) it would probably look like this:
```
<?php
/**
* Displays sidebar widgets for front page
*
* @since ctheme 1.0
*/
?>
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php if ( is_active_sidebar( 'cryptid-sidebar-widgets-left' ) ) :
dynamic_sidebar( 'cryptid-sidebar-widgets-left' );
endif; ?>
</ul>
</div>
```
Thanks so much for all your help and for taking the time to read this. I hope I have provided enough information so I can be aided in accomplishing this.
**EDIT- Potential Answer:**
So I began to read up on Custom Fields again and also began to code Meta Box into my functions.php. I took a break and then realized that there was a simple solution stemming from **Example #2** above: **Text Widget and Widget Logic Plugin**. I still want to tackle this problem in a more sophisticated manner but I'll post here what I did to make what I want happen.
The only real problem with #2 was that when I went to look into the Customizer- Widget area, under the Cryptid Left Sidebar all I saw was this:
Text Widget: Quick Facts
Text Widget: Quick Facts
Text Widget: Quick Facts (and on)
As stated above, if I had to go back to change the text data for one of these creatures, I wouldn't know which one to go into just by a glance. So, I simply went in search for another widget. After trying a few other Text Widgets out, I settled on **Enhanced Text Widget**. This widget gave me the option to title the widget but not show the title in the output.
I titled the widget by the name of the creature. Then in the text field, I simply gave the widget the title "Quick Facts" above all the other data I had coded for the quick facts. I then gave that title the same div that the rest of the widget titles already had, in my case it was called "widgettitle"
```
<div class="widgettitle"><h2>Quick Facts</h2></div>
```
It kinda messed up the size of the font but the rest of the styling is there. I can fix that easily in my style.css file.
Then, I used Widget Logic, which adds an extra field to the bottom of each widget. So in this area, I can type in the following so it only shows up for that page:
```
is_page('pageid')
```
In the end we have a widget customize area that now looks like this:
Enhanced Text: Loch Ness
Enhanced Text: Ogopogo
Enhanced Text: Bigfoot (and on)
Each with their own quick facts inside and now I can quickly see which creature's widget it is versus before.
It feels kinda noobie to do it this way, like I should be taking a more sophisticated path but it works out and it seems quite clean. I am not sure how well the site will handle this x100, but it doesn't seem like it should be that difficult or heavy to process.
Also I just realized...I have to do something similar if I wanted a little map for each animal location above the Quick Facts area (as seen in the image). I'll have to tackle that as well...but I may just stick the map in the page's content's instead. This is going to be one stuffed sidebar as it is.
Further help is greatly appreciated!
**FINAL EDIT AND SOLUTION:** Thanks to Milo!
Taking the accepted answer below by Milo, I decided to fully implement Custom Fields.
I went through the trouble of creating my own meta box, which came out fairly decently. I ended up reverting to *Advanced Custom Fields plugin* cause their meta boxes were nicer. I don't even need the plugin, but I kept it around in case I wanted to use it for something more complicated in the future. Using *Advanced Custom Fields plugin* (or the Custom Fields box without the plugin) I created the custom field key **cryptid\_post\_class**.
I then altered my page template (cryptofacts-page.php) to remove the sidebar and in it's place GET the data from the custom field. It is imperative to use proper wrappers as it would appear with the sidebar from before (Miloisawesome).
```
get_header(); ?>
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php
$meta = get_post_meta(get_the_ID(), "cryptid_post_class", true);
if( !empty($meta) ):
?>
<li>
<?php echo $meta; ?>
</li>
<?php
endif;
?>
</ul>
</div>
<?php if ( have_posts() ) : ?>
<!--if there are posts, start the loop-->
<div class="cryptid-container">
<?php while ( have_posts() ) : the_post(); ?>
<!--get the content template for the current post format.-->
<?php get_template_part( 'content', get_post_format() ); ?>
<?php endwhile; ?>
```
Here are some pictures to illustrate the process.
1. **Setup the template with proper wrappers**
[](https://i.stack.imgur.com/DNUCi.png)
2. **Setting up the Custom Fields area**
[](https://i.stack.imgur.com/LxlPh.png)
3. **End result minus some css tweaks since I used a backup template while playing with this**
[](https://i.stack.imgur.com/TfcCu.png)
Hopefully this will help any other newbie WordPress developers make things clearer and approach the rather awesome custom fields part of WP!
|
You *could* dynamically register sidebars. When you register sidebars, you could query for all of your animal pages, loop over all pages, and register a unique sidebar for each page. Adding a page would automatically create a sidebar for it.
*However* - that's a lot of sidebars. For something tightly coupled with the page content, I would rather handle it with custom fields via a [custom meta box](https://codex.wordpress.org/Function_Reference/add_meta_box) that contained your pre-defined field(s).
As for why your use of post meta disturbed the layout of your site, it's probably just an issue of markup / styling. The simplest course may be to get the layout looking right with a sidebar and text widget, then copy the markup that's generated when you view the page, and use that as the wrapper markup for you custom fields. Looking at your template above, widgets will appear as `<li>`s within a `<ul>`, so try that when adding your post meta:
```
<div class="cryptid-sidebar-left">
<ul class="cryptid-sidebar-widgets-left">
<?php
$meta = get_post_meta(get_the_ID(), "your-key", true);
if( !empty($meta) ):
?>
<li>
<?php echo $meta; ?>
</li>
<?php
endif;
?>
</ul>
</div>
```
|
208,471 |
<p>I have been given a job to amend a Wordpress site. I have only been given access to Cpanel. My questions are can i log in to the back end of Wordpress via Cpanel? If you can't login via Cpanel can i change the details like username and password so i can log in?</p>
<p>I have tried going into mySQL database to the phpmyadmin and making it have no password but that made things worse. I tried going into all the things in my eXtend cpanel but i cant find anything that works.</p>
|
[
{
"answer_id": 208473,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 1,
"selected": false,
"text": "<p>There are 5 options</p>\n\n<h2>1) Ask The Client</h2>\n\n<p>You haven't been given what you need to do your work, so you should request it rather than hacking in to the clients site. This would be the Professional and ethical thing to do</p>\n\n<h2>2) Reset Password link</h2>\n\n<p>Using the standard password reset link should do the job</p>\n\n<h2>3) WP CLI</h2>\n\n<p>You can use WP CLI to set the password, or add a new administrator user.</p>\n\n<p>e.g. to update the user with ID 22:</p>\n\n<pre><code>wp user update 22 --password=\"newpass\"\n</code></pre>\n\n<h2>4) Via The Database</h2>\n\n<p>Passwords are salted, but you can replace them with an MD5 hash. The caveat being that as soon as that hash is checked, if it matches the password, then it gets replaced with a salted version at:</p>\n\n<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/pluggable.php#L2236\" rel=\"nofollow noreferrer\">https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/pluggable.php#L2236</a></p>\n\n<h2>5) <code>emergency.php</code></h2>\n\n<p>If all other options fail, <a href=\"https://codex.wordpress.org/User:MichaelH/Orphaned_Plugins_needing_Adoption/Emergency\" rel=\"nofollow noreferrer\">there is <code>emergency.php</code></a>. The file is dangerous, and should be removed once used, but it will allow you to reset the password of an admin user</p>\n\n<blockquote>\n <ol>\n <li>Save the script below as a file called emergency.php to the root of your WordPress installation (the same directory that contains\n wp-config.php).</li>\n <li>In your browser, open <a href=\"http://example.com/emergency.php\" rel=\"nofollow noreferrer\">http://example.com/emergency.php</a>.</li>\n <li>As instructed, enter the administrator username (usually admin) and the new password, then click Update Options. A message is displayed\n noting the changed password. An email is sent to the blog\n administrator with the changed password information.</li>\n <li><strong>Delete emergency.php from your server</strong> when you are done. Do not leave it on your server as someone else could use it to change your\n password.</li>\n </ol>\n</blockquote>\n\n<hr>\n\n<p>But the best avenue would be to ask the client or your employer for access, it's not an unreasonable request, and it's unreasonable to ask you to break into the site in order to do work.</p>\n"
},
{
"answer_id": 317400,
"author": "djboris",
"author_id": 152412,
"author_profile": "https://wordpress.stackexchange.com/users/152412",
"pm_score": 0,
"selected": false,
"text": "<p>Unless this website is using some hashing-altering plugin like Bcrypt or similar, you can easily change the password for users using phpMyAdmin. </p>\n\n<ol>\n<li>Login to cpanel and open phpMyAdmin.</li>\n<li>Find table <code>wp_users</code> (prefix could differ)</li>\n<li>On the row with the user you want to change the password, click on Edit</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/5bEfj.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5bEfj.png\" alt=\"\"></a></p>\n\n<ol start=\"4\">\n<li>On new screen, find column <code>user_pass</code>, select the Function MD5, and type your new password like on screen, and click Go</li>\n</ol>\n\n<p><a href=\"https://i.stack.imgur.com/5r4lU.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/5r4lU.png\" alt=\"\"></a></p>\n\n<ol start=\"5\">\n<li>Now login to <code>/wp-admin</code> using new password, and change it to a more secure one through the Dashboard. <strong>This last step is very important, because changing password through the Dashboard applies a more secure hashing algorithm to the stored password. Please don't skip it.</strong></li>\n</ol>\n\n<p>More on official WordPress Documentation: <a href=\"https://codex.wordpress.org/Resetting_Your_Password#Through_phpMyAdmin\" rel=\"nofollow noreferrer\">Link</a></p>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208471",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83501/"
] |
I have been given a job to amend a Wordpress site. I have only been given access to Cpanel. My questions are can i log in to the back end of Wordpress via Cpanel? If you can't login via Cpanel can i change the details like username and password so i can log in?
I have tried going into mySQL database to the phpmyadmin and making it have no password but that made things worse. I tried going into all the things in my eXtend cpanel but i cant find anything that works.
|
There are 5 options
1) Ask The Client
-----------------
You haven't been given what you need to do your work, so you should request it rather than hacking in to the clients site. This would be the Professional and ethical thing to do
2) Reset Password link
----------------------
Using the standard password reset link should do the job
3) WP CLI
---------
You can use WP CLI to set the password, or add a new administrator user.
e.g. to update the user with ID 22:
```
wp user update 22 --password="newpass"
```
4) Via The Database
-------------------
Passwords are salted, but you can replace them with an MD5 hash. The caveat being that as soon as that hash is checked, if it matches the password, then it gets replaced with a salted version at:
<https://core.trac.wordpress.org/browser/tags/4.9.8/src/wp-includes/pluggable.php#L2236>
5) `emergency.php`
------------------
If all other options fail, [there is `emergency.php`](https://codex.wordpress.org/User:MichaelH/Orphaned_Plugins_needing_Adoption/Emergency). The file is dangerous, and should be removed once used, but it will allow you to reset the password of an admin user
>
> 1. Save the script below as a file called emergency.php to the root of your WordPress installation (the same directory that contains
> wp-config.php).
> 2. In your browser, open <http://example.com/emergency.php>.
> 3. As instructed, enter the administrator username (usually admin) and the new password, then click Update Options. A message is displayed
> noting the changed password. An email is sent to the blog
> administrator with the changed password information.
> 4. **Delete emergency.php from your server** when you are done. Do not leave it on your server as someone else could use it to change your
> password.
>
>
>
---
But the best avenue would be to ask the client or your employer for access, it's not an unreasonable request, and it's unreasonable to ask you to break into the site in order to do work.
|
208,477 |
<p>I have some PHP experience, but hardly any WP theme writing experience...I'm just starting the journey.</p>
<p>All of the themes I have looked at so far in the .org repository have code that looks like this:</p>
<pre><code><?php if (condition) { ?>
..some html
<?php } else { ?>
..some other html
<?php } ?>
</code></pre>
<p>instead of:</p>
<pre><code><?php
if (condition) {
echo ..some html
}
else {
echo ..some other html
}
?>
</code></pre>
<p>I can see that when using an editor like notepad++ we'd rather have the html "naked" and not in an echo statement, to give the editor the ability to color-code and match up HTML tags with their ending tags, etc.</p>
<p>But I see a lot of templates that have a TON of PHP code and very little HTML -- and they still wrap PHP tags around <em>every</em> line of code. To me, that makes it hard to read.</p>
<p>Is there a technical reason for that, or just a preference on the part of the developer?</p>
|
[
{
"answer_id": 208482,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 4,
"selected": true,
"text": "<p>As always, people copy paste whatever they learned from and IIRC the first style is the coding style of wordpress core.</p>\n\n<p>As you said yourself, when there is a big block of generated HTML it is easier to look at (and balance tags) under the first style, but pragmatic people will use the second whenever that is not the case.</p>\n\n<p>It is really just coding style preference nothing technical behind it.</p>\n"
},
{
"answer_id": 208502,
"author": "Lightness Races in Orbit",
"author_id": 83518,
"author_profile": "https://wordpress.stackexchange.com/users/83518",
"pm_score": 1,
"selected": false,
"text": "<p>Although you may argue that the code is harder to read when you go into and out of PHP mode more often, it is also good and widely-recommended practice in PHP <em>not</em> to mix output styles.</p>\n\n<p>That is, either you output HTML from HTML mode, or you output HTML from <code>echo</code> statements … but you don't mix styles. That would create a maintenance nightmare.</p>\n\n<p>The authors of the templates you're reading are following that best practice.</p>\n\n<p>However, ultimately, yes, this is a style/management issue only: nothing in the language inherently requires it.</p>\n\n<p>A sensible templating system would not allow inline PHP <em>at all</em>, instead allowing only declarative extensions to the HTML markup, but that's another story…</p>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208477",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82933/"
] |
I have some PHP experience, but hardly any WP theme writing experience...I'm just starting the journey.
All of the themes I have looked at so far in the .org repository have code that looks like this:
```
<?php if (condition) { ?>
..some html
<?php } else { ?>
..some other html
<?php } ?>
```
instead of:
```
<?php
if (condition) {
echo ..some html
}
else {
echo ..some other html
}
?>
```
I can see that when using an editor like notepad++ we'd rather have the html "naked" and not in an echo statement, to give the editor the ability to color-code and match up HTML tags with their ending tags, etc.
But I see a lot of templates that have a TON of PHP code and very little HTML -- and they still wrap PHP tags around *every* line of code. To me, that makes it hard to read.
Is there a technical reason for that, or just a preference on the part of the developer?
|
As always, people copy paste whatever they learned from and IIRC the first style is the coding style of wordpress core.
As you said yourself, when there is a big block of generated HTML it is easier to look at (and balance tags) under the first style, but pragmatic people will use the second whenever that is not the case.
It is really just coding style preference nothing technical behind it.
|
208,480 |
<p>There is a horizontal box of one-line height at the bottom with the character "p" in it that I want to get rid of for end users. I don't really care if it is there in the Dashboard Editor for site admins/editors. This line seems to indicate the formatting of the line where the cursor is. End users are providing feedback "so, what's the p?". Can we remove that box?</p>
|
[
{
"answer_id": 208491,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 1,
"selected": false,
"text": "<p>This is how the tinymce statusbar displays on my intsall:</p>\n\n<pre><code><div id=\"mceu_34\" class=\"mce-statusbar mce-container mce-panel mce-stack-layout-item mce-last\" hidefocus=\"1\" tabindex=\"-1\" role=\"group\">\n <div id=\"mceu_34-body\" class=\"mce-container-body mce-flow-layout\">\n <div id=\"mceu_35\" class=\"mce-path mce-flow-layout-item mce-first mce-last\">\n <div role=\"button\" class=\"mce-path-item\" data-index=\"0\" tabindex=\"-1\" id=\"mceu_35-0\" aria-level=\"0\">p</div>\n <div class=\"mce-divider\" aria-hidden=\"true\"> » </div>\n <div role=\"button\" class=\"mce-path-item mce-last\" data-index=\"1\" tabindex=\"-1\" id=\"mceu_35-1\" aria-level=\"1\">strong</div> \n </div>\n </div>\n</div>\n</code></pre>\n\n<p>so this suggests hiding it with CSS.</p>\n\n<p>You probably want to keep the statusbar visible but hide the <code>div.mce-path</code>.</p>\n\n<p>The <code>tiny_mce_before_init</code> hook might come useful to target the tinymce editor:</p>\n\n<pre><code>add_filter( 'tiny_mce_before_init', function( $settings )\n{\n ?><style>.mce-path{display:none;}</style><?php\n return $settings;\n} );\n</code></pre>\n\n<p>But there must be a native way, so I simply searched for the <em>mce-path</em> keyword and this question on StackOverflow popped up first:</p>\n\n<p><a href=\"https://stackoverflow.com/questions/17193624/remove-path-in-status-bar-in-tinymce4\">Remove path in status bar in TinyMCE4</a> </p>\n\n<p>There it's suggested by @BeckJohnson to use:</p>\n\n<pre><code>tinymce.init({ elementpath: false });\n</code></pre>\n\n<p>so we can try that with:</p>\n\n<pre><code>add_filter( 'tiny_mce_before_init', function( $settings )\n{\n $settings['elementpath'] = false;\n return $settings; \n});\n</code></pre>\n\n<p>and that seems to do the trick.</p>\n"
},
{
"answer_id": 208494,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 0,
"selected": false,
"text": "<p>It's called the Element Path located in the editor's status bar.</p>\n\n<p>You remove it by setting its <em>tinymce.init</em> setting of <em>elementpath</em> to false.</p>\n\n<pre><code>{'elementpath': false}\n</code></pre>\n\n<p>In Wordpress, that setting can be altered in the <code>tiny_mce_before_init</code> filter.</p>\n\n<pre><code>add_filter('tiny_mce_before_init', function ($init) {\n$init['elementpath'] = false;\nreturn $init; });\n</code></pre>\n\n<p>Make sure you add the filter before you invoke the editor function or it will not take effect.</p>\n"
},
{
"answer_id": 208496,
"author": "SimonT",
"author_id": 83376,
"author_profile": "https://wordpress.stackexchange.com/users/83376",
"pm_score": 0,
"selected": false,
"text": "<p>It shows what HTML tags are open.</p>\n\n<p>Just tell them what it is and add \"if you don't know what that means, just ignore it. It is nothing you need to worry about.\"</p>\n\n<p>Why go making code changes when they are not needed?</p>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208480",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83503/"
] |
There is a horizontal box of one-line height at the bottom with the character "p" in it that I want to get rid of for end users. I don't really care if it is there in the Dashboard Editor for site admins/editors. This line seems to indicate the formatting of the line where the cursor is. End users are providing feedback "so, what's the p?". Can we remove that box?
|
This is how the tinymce statusbar displays on my intsall:
```
<div id="mceu_34" class="mce-statusbar mce-container mce-panel mce-stack-layout-item mce-last" hidefocus="1" tabindex="-1" role="group">
<div id="mceu_34-body" class="mce-container-body mce-flow-layout">
<div id="mceu_35" class="mce-path mce-flow-layout-item mce-first mce-last">
<div role="button" class="mce-path-item" data-index="0" tabindex="-1" id="mceu_35-0" aria-level="0">p</div>
<div class="mce-divider" aria-hidden="true"> » </div>
<div role="button" class="mce-path-item mce-last" data-index="1" tabindex="-1" id="mceu_35-1" aria-level="1">strong</div>
</div>
</div>
</div>
```
so this suggests hiding it with CSS.
You probably want to keep the statusbar visible but hide the `div.mce-path`.
The `tiny_mce_before_init` hook might come useful to target the tinymce editor:
```
add_filter( 'tiny_mce_before_init', function( $settings )
{
?><style>.mce-path{display:none;}</style><?php
return $settings;
} );
```
But there must be a native way, so I simply searched for the *mce-path* keyword and this question on StackOverflow popped up first:
[Remove path in status bar in TinyMCE4](https://stackoverflow.com/questions/17193624/remove-path-in-status-bar-in-tinymce4)
There it's suggested by @BeckJohnson to use:
```
tinymce.init({ elementpath: false });
```
so we can try that with:
```
add_filter( 'tiny_mce_before_init', function( $settings )
{
$settings['elementpath'] = false;
return $settings;
});
```
and that seems to do the trick.
|
208,487 |
<p>I've been tasked with converting about 100 sites in my multisite instance to HTTPS.</p>
<p>I can easily write a script to hit the DB and change the <code>siteurl</code> and <code>home</code> values to HTTPS, which inturn should force the site to enqueue scripts and future embeded images to HTTPS right?</p>
<p>Well I'll also need to go through all post_content for any internal links, as well as images using HTTP and convert those to HTTPS.</p>
<p>I could probably whip something together to do that, but Im wondering what else I need to change. GUIDs right? If I used the $wpdb commands would I need to reserialize the DB afterwards?</p>
<p>I should have ask first, is there a reliable plugin that will take care of this for me? What else do I need to know about this process?</p>
<p>Notes
- We already have all the SSL certs so thats something I dont have to worry about.
- Server is running linux(redhat) and apache
- The multisite is using sub directories
- I dont know much else tho, the server is outside my jurisdiction</p>
|
[
{
"answer_id": 208490,
"author": "John Lucey",
"author_id": 83434,
"author_profile": "https://wordpress.stackexchange.com/users/83434",
"pm_score": 0,
"selected": false,
"text": "<p>This process actually involves purchasing a security Certificate and applying it to your server for your websites. This will in turn force everyone visiting into a secure connection via the certificate presented by your server. These certificates are called SSL Certs: <a href=\"http://www.DigiCert.com/SSL-Certificates\" rel=\"nofollow\">http://www.DigiCert.com/SSL-Certificates</a></p>\n"
},
{
"answer_id": 235021,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 0,
"selected": false,
"text": "<p>One possible way to do this data modification is to use <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> on the terminal. </p>\n\n<p>First of all, you should make sure you have a backup and a solid restore strategy in case anything goes wrong. You should also test this procedure on a local or testing system with a copy of the live database.</p>\n\n<p>The basic steps are, to iterate over each site of your network and replace the URLs of each site using WP-CLI's <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\"><code>search-replace</code> command</a>. </p>\n\n<p>Here's a bash one-liner:</p>\n\n<pre><code>for SITE in $(wp site list --field=url); do wp search-replace \"{$SITE}\" \"${SITE/http:/https:}\" --dry-run --precise --network --verbose; done\n</code></pre>\n\n<p>Let's examine that: </p>\n\n<pre><code>for SITE in $(wp site list --field=url);\n</code></pre>\n\n<p>That one starts a loop for each line of the output of the command inside <code>$()</code> and writes each line in the variable <code>$SITE</code>.</p>\n\n<pre><code>$(wp site list --field=url)\n</code></pre>\n\n<p>That's the WP-CLI <a href=\"http://wp-cli.org/commands/site/list/\" rel=\"nofollow\"><code>site list</code> command</a> which gives you a list of all site URLs in your network. Run this command solely, you will probably see something like:</p>\n\n<pre><code>http://your-site.tld/\nhttp://your-site.tld/site2/\nhttp://another-of.your-site.tld/\n...\n</code></pre>\n\n<p>Now</p>\n\n<pre><code>...); do\n</code></pre>\n\n<p>will just start the inner loop part.</p>\n\n<p>The inner loop command does all the magic (I split it to two lines using <code>\\</code> for readability):</p>\n\n<pre><code>wp search-replace \"$SITE\" \"${SITE/http:/https:}\" \\\n--dry-run --precise --network --verbose\n</code></pre>\n\n<p>We tell WP-CLI to <em>search</em> for <code>$SITE</code> (e.g. <code>https://your-site.tld/</code>) and <em>replace</em> it with a slightly modified version: <code>${SITE/http:/https:}</code>. This is a bash string replaces operation that replaces <code>http:</code> with <code>https:</code>. (So resolving the variables, the command would look like <code>wp search-replace \"http://your-site.tdl/\" \"https://your-site.tld/\"</code>).</p>\n\n<p><code>search-replace</code> has many possible options that are described in the <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">documentation</a>. In the example I used these:</p>\n\n<pre><code>--dry-run --precise --network --verbose\n</code></pre>\n\n<p><code>--dry-run</code> and <code>--verbose</code> are clearly helpful for testing the command. </p>\n\n<p><code>--network</code> applies the search and replace operation also to the network tabels.</p>\n\n<p><code>--precise</code> tells WP-CLI to use PHP instead of SQL to search and replace the values. That ensures serialized values to not get corrupted. </p>\n\n<p>Finally the loop is closed with</p>\n\n<pre><code>; done\n</code></pre>\n\n<p>Let me emphasize it again: test this deeply before you start using this on production. You should understand how it work and what WP-CLI does. I used WP-CLI before to perform such searach and replace operations to migrate multisites to other domain names, but not to switch from <code>http</code> to <code>https</code>.</p>\n\n<p>There might be some edge cases: WP-CLI still reads the <code>wp-config.php</code> and try to find a matching «network» in the database by using the constants in <code>wp-config.php</code>. If you're manipulating one site (the database) but not the other one (the constants in <code>wp-config.php</code>) you <em>might</em> get into trouble. But for your case, I think that won't be a problem as WP typically relies on <code>DOMAIN_CURRENT_SITE</code> and <code>PATH_CURRENT_SITE</code> and they won't change anyway. But again, test this thorough. </p>\n\n<p>With a bit more bash magic, you could also split this loop into chunks of 5 or 10 sites and go through it step by step.</p>\n"
},
{
"answer_id": 235887,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>To ensure all of your websites use HTTPS in your <code>post_content</code>, you can perform one of two options:</p>\n\n<h3>1. Backend: execute a SQL query</h3>\n\n<p>To make sure that all of your HTTP links are set as HTTPS, use the following SQL query:</p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>This will cover the <code>siteurl</code>, <code>home</code>, and all of your content on your website to the new HTTPS.</p>\n\n<h3>2. Frontend: use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">Search & Replace</a> plugin</h3>\n\n<p>A more user-friendly approach is to use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">Search & Replace</a> plugin to easily replace all tables that contain your old HTTP and change them to a HTTPS. The process is easy to use and you can preview what tables and rows will be affected before applying those changes.</p>\n\n<h3>Forewarning</h3>\n\n<p>Before applying any changes, I think it goes without saying to always make a backup of your database in the event something goes wrong.</p>\n"
},
{
"answer_id": 237455,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 1,
"selected": false,
"text": "<p>You could run a script to UPDATE all urls and guids to https, if you want a clean setup. </p>\n\n<p>But also consider alternatives such as:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]\n</IfModule>\n</code></pre>\n\n<p>In wp-config.php for the backend:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>In wp-config.php for the frontend (or run a db UPDATE script):</p>\n\n<pre><code>define('WP_HOME','https://example.com');\ndefine('WP_SITEURL','https://example.com');\n</code></pre>\n\n<p>Then you could simply run a script to UPDATE all wp_posts content url.</p>\n"
},
{
"answer_id": 238711,
"author": "Harshita",
"author_id": 102498,
"author_profile": "https://wordpress.stackexchange.com/users/102498",
"pm_score": 0,
"selected": false,
"text": "<p>HTTP is a default protocol, which is used by most websites to handle the information over the web. Your website is running on HTTPS without any error message, it means your certificate has been installed correctly. You should migrate your entire website from HTTP to HTTPS. </p>\n\n<p><a href=\"https://make.wordpress.org/support/user-manual/web-publishing/https-for-wordpress/\" rel=\"nofollow\">Learn how to move HTTP to HTTPS for WordPress</a></p>\n"
}
] |
2015/11/12
|
[
"https://wordpress.stackexchange.com/questions/208487",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/19536/"
] |
I've been tasked with converting about 100 sites in my multisite instance to HTTPS.
I can easily write a script to hit the DB and change the `siteurl` and `home` values to HTTPS, which inturn should force the site to enqueue scripts and future embeded images to HTTPS right?
Well I'll also need to go through all post\_content for any internal links, as well as images using HTTP and convert those to HTTPS.
I could probably whip something together to do that, but Im wondering what else I need to change. GUIDs right? If I used the $wpdb commands would I need to reserialize the DB afterwards?
I should have ask first, is there a reliable plugin that will take care of this for me? What else do I need to know about this process?
Notes
- We already have all the SSL certs so thats something I dont have to worry about.
- Server is running linux(redhat) and apache
- The multisite is using sub directories
- I dont know much else tho, the server is outside my jurisdiction
|
You could run a script to UPDATE all urls and guids to https, if you want a clean setup.
But also consider alternatives such as:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>
```
In wp-config.php for the backend:
```
define('FORCE_SSL_ADMIN', true);
```
In wp-config.php for the frontend (or run a db UPDATE script):
```
define('WP_HOME','https://example.com');
define('WP_SITEURL','https://example.com');
```
Then you could simply run a script to UPDATE all wp\_posts content url.
|
208,532 |
<p>I am trying to login a user from custom user registration form.
My Code for Custom user Register is </p>
<pre><code>function register_user($data) {
$userdata = array(
'user_login' => $data['email'],
'user_email' => $data['email'],
'user_pass' => $data['pssword'],
'user_nicename' => $data['fname'],
'display_name' => $data['fname'],
);
$usermetedata = array(
'son_name' => $data['son_name'],
'shape' => $data['shape'],
'siret' => $data['siret'],
'company_email' => $data['company_email'],
'company_activity' => $data['activity'],
'staff' => $data['staff'],
'position_held' => $data['position_held'],
'company_phone' => $data['company_phone'],
'company_mobile' => $data['company_mobile'],
'company_address' => $data['company_address'],
'company_postal' => $data['company_postal'],
'company_ville' => $data['company_ville'],
'url' => $data['url'],
'personal_region' => $data['personal_region'],
'personal_address' => $data['personal_address'],
'personal_ville' => $data['personal_ville'],
'personal_postal' => $data['personal_postal'],
'personal_phone' => $data['personal_phone'],
'personal_mobile' => $data['personal_mobile'],
'dob' => $data['dob'],
'invite_email' => $data['invite_email']
);
$userid = wp_insert_user($userdata);
foreach ($usermetedata as $key => $val):
add_user_meta($userid, $key, $val);
endforeach;
gdlr_new_user_registered($userid);
// echo 'Registration complete. Goto <a href="' . get_site_url() . '/wp-admin">login page</a>.';
if ($userid) {
user_activation($userid, $data);
}
}
</code></pre>
<p>And My code for Login currently register user is </p>
<pre><code>function gdlr_new_user_registered( $user_id ) {
$user = get_user_by( 'id', $user_id );
wp_set_auth_cookie( $user_id, false, is_ssl() );
$redirect_to = site_url().'le-reseau-social/teepy-tableau-de-bord/';
do_action( 'wp_login', $user->user_login );
return $redirect_to;
}
add_filter('login_redirect', 'gdlr_new_user_registered', 10, 3);
</code></pre>
<p>But I am not able to login please suggest me or let me know if i am doing some mistake.</p>
<p>Thanks</p>
|
[
{
"answer_id": 208490,
"author": "John Lucey",
"author_id": 83434,
"author_profile": "https://wordpress.stackexchange.com/users/83434",
"pm_score": 0,
"selected": false,
"text": "<p>This process actually involves purchasing a security Certificate and applying it to your server for your websites. This will in turn force everyone visiting into a secure connection via the certificate presented by your server. These certificates are called SSL Certs: <a href=\"http://www.DigiCert.com/SSL-Certificates\" rel=\"nofollow\">http://www.DigiCert.com/SSL-Certificates</a></p>\n"
},
{
"answer_id": 235021,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 0,
"selected": false,
"text": "<p>One possible way to do this data modification is to use <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> on the terminal. </p>\n\n<p>First of all, you should make sure you have a backup and a solid restore strategy in case anything goes wrong. You should also test this procedure on a local or testing system with a copy of the live database.</p>\n\n<p>The basic steps are, to iterate over each site of your network and replace the URLs of each site using WP-CLI's <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\"><code>search-replace</code> command</a>. </p>\n\n<p>Here's a bash one-liner:</p>\n\n<pre><code>for SITE in $(wp site list --field=url); do wp search-replace \"{$SITE}\" \"${SITE/http:/https:}\" --dry-run --precise --network --verbose; done\n</code></pre>\n\n<p>Let's examine that: </p>\n\n<pre><code>for SITE in $(wp site list --field=url);\n</code></pre>\n\n<p>That one starts a loop for each line of the output of the command inside <code>$()</code> and writes each line in the variable <code>$SITE</code>.</p>\n\n<pre><code>$(wp site list --field=url)\n</code></pre>\n\n<p>That's the WP-CLI <a href=\"http://wp-cli.org/commands/site/list/\" rel=\"nofollow\"><code>site list</code> command</a> which gives you a list of all site URLs in your network. Run this command solely, you will probably see something like:</p>\n\n<pre><code>http://your-site.tld/\nhttp://your-site.tld/site2/\nhttp://another-of.your-site.tld/\n...\n</code></pre>\n\n<p>Now</p>\n\n<pre><code>...); do\n</code></pre>\n\n<p>will just start the inner loop part.</p>\n\n<p>The inner loop command does all the magic (I split it to two lines using <code>\\</code> for readability):</p>\n\n<pre><code>wp search-replace \"$SITE\" \"${SITE/http:/https:}\" \\\n--dry-run --precise --network --verbose\n</code></pre>\n\n<p>We tell WP-CLI to <em>search</em> for <code>$SITE</code> (e.g. <code>https://your-site.tld/</code>) and <em>replace</em> it with a slightly modified version: <code>${SITE/http:/https:}</code>. This is a bash string replaces operation that replaces <code>http:</code> with <code>https:</code>. (So resolving the variables, the command would look like <code>wp search-replace \"http://your-site.tdl/\" \"https://your-site.tld/\"</code>).</p>\n\n<p><code>search-replace</code> has many possible options that are described in the <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">documentation</a>. In the example I used these:</p>\n\n<pre><code>--dry-run --precise --network --verbose\n</code></pre>\n\n<p><code>--dry-run</code> and <code>--verbose</code> are clearly helpful for testing the command. </p>\n\n<p><code>--network</code> applies the search and replace operation also to the network tabels.</p>\n\n<p><code>--precise</code> tells WP-CLI to use PHP instead of SQL to search and replace the values. That ensures serialized values to not get corrupted. </p>\n\n<p>Finally the loop is closed with</p>\n\n<pre><code>; done\n</code></pre>\n\n<p>Let me emphasize it again: test this deeply before you start using this on production. You should understand how it work and what WP-CLI does. I used WP-CLI before to perform such searach and replace operations to migrate multisites to other domain names, but not to switch from <code>http</code> to <code>https</code>.</p>\n\n<p>There might be some edge cases: WP-CLI still reads the <code>wp-config.php</code> and try to find a matching «network» in the database by using the constants in <code>wp-config.php</code>. If you're manipulating one site (the database) but not the other one (the constants in <code>wp-config.php</code>) you <em>might</em> get into trouble. But for your case, I think that won't be a problem as WP typically relies on <code>DOMAIN_CURRENT_SITE</code> and <code>PATH_CURRENT_SITE</code> and they won't change anyway. But again, test this thorough. </p>\n\n<p>With a bit more bash magic, you could also split this loop into chunks of 5 or 10 sites and go through it step by step.</p>\n"
},
{
"answer_id": 235887,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>To ensure all of your websites use HTTPS in your <code>post_content</code>, you can perform one of two options:</p>\n\n<h3>1. Backend: execute a SQL query</h3>\n\n<p>To make sure that all of your HTTP links are set as HTTPS, use the following SQL query:</p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>This will cover the <code>siteurl</code>, <code>home</code>, and all of your content on your website to the new HTTPS.</p>\n\n<h3>2. Frontend: use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">Search & Replace</a> plugin</h3>\n\n<p>A more user-friendly approach is to use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">Search & Replace</a> plugin to easily replace all tables that contain your old HTTP and change them to a HTTPS. The process is easy to use and you can preview what tables and rows will be affected before applying those changes.</p>\n\n<h3>Forewarning</h3>\n\n<p>Before applying any changes, I think it goes without saying to always make a backup of your database in the event something goes wrong.</p>\n"
},
{
"answer_id": 237455,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 1,
"selected": false,
"text": "<p>You could run a script to UPDATE all urls and guids to https, if you want a clean setup. </p>\n\n<p>But also consider alternatives such as:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]\n</IfModule>\n</code></pre>\n\n<p>In wp-config.php for the backend:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>In wp-config.php for the frontend (or run a db UPDATE script):</p>\n\n<pre><code>define('WP_HOME','https://example.com');\ndefine('WP_SITEURL','https://example.com');\n</code></pre>\n\n<p>Then you could simply run a script to UPDATE all wp_posts content url.</p>\n"
},
{
"answer_id": 238711,
"author": "Harshita",
"author_id": 102498,
"author_profile": "https://wordpress.stackexchange.com/users/102498",
"pm_score": 0,
"selected": false,
"text": "<p>HTTP is a default protocol, which is used by most websites to handle the information over the web. Your website is running on HTTPS without any error message, it means your certificate has been installed correctly. You should migrate your entire website from HTTP to HTTPS. </p>\n\n<p><a href=\"https://make.wordpress.org/support/user-manual/web-publishing/https-for-wordpress/\" rel=\"nofollow\">Learn how to move HTTP to HTTPS for WordPress</a></p>\n"
}
] |
2015/11/13
|
[
"https://wordpress.stackexchange.com/questions/208532",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77484/"
] |
I am trying to login a user from custom user registration form.
My Code for Custom user Register is
```
function register_user($data) {
$userdata = array(
'user_login' => $data['email'],
'user_email' => $data['email'],
'user_pass' => $data['pssword'],
'user_nicename' => $data['fname'],
'display_name' => $data['fname'],
);
$usermetedata = array(
'son_name' => $data['son_name'],
'shape' => $data['shape'],
'siret' => $data['siret'],
'company_email' => $data['company_email'],
'company_activity' => $data['activity'],
'staff' => $data['staff'],
'position_held' => $data['position_held'],
'company_phone' => $data['company_phone'],
'company_mobile' => $data['company_mobile'],
'company_address' => $data['company_address'],
'company_postal' => $data['company_postal'],
'company_ville' => $data['company_ville'],
'url' => $data['url'],
'personal_region' => $data['personal_region'],
'personal_address' => $data['personal_address'],
'personal_ville' => $data['personal_ville'],
'personal_postal' => $data['personal_postal'],
'personal_phone' => $data['personal_phone'],
'personal_mobile' => $data['personal_mobile'],
'dob' => $data['dob'],
'invite_email' => $data['invite_email']
);
$userid = wp_insert_user($userdata);
foreach ($usermetedata as $key => $val):
add_user_meta($userid, $key, $val);
endforeach;
gdlr_new_user_registered($userid);
// echo 'Registration complete. Goto <a href="' . get_site_url() . '/wp-admin">login page</a>.';
if ($userid) {
user_activation($userid, $data);
}
}
```
And My code for Login currently register user is
```
function gdlr_new_user_registered( $user_id ) {
$user = get_user_by( 'id', $user_id );
wp_set_auth_cookie( $user_id, false, is_ssl() );
$redirect_to = site_url().'le-reseau-social/teepy-tableau-de-bord/';
do_action( 'wp_login', $user->user_login );
return $redirect_to;
}
add_filter('login_redirect', 'gdlr_new_user_registered', 10, 3);
```
But I am not able to login please suggest me or let me know if i am doing some mistake.
Thanks
|
You could run a script to UPDATE all urls and guids to https, if you want a clean setup.
But also consider alternatives such as:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>
```
In wp-config.php for the backend:
```
define('FORCE_SSL_ADMIN', true);
```
In wp-config.php for the frontend (or run a db UPDATE script):
```
define('WP_HOME','https://example.com');
define('WP_SITEURL','https://example.com');
```
Then you could simply run a script to UPDATE all wp\_posts content url.
|
208,545 |
<p>I have a site with numerous custom post types that are created using a class. I was considering whether it was worth creating a custom taxonomy for each custom post type to offer a way of organizing and categorizing within that custom post type <em>-e.g</em> terms and tags that only apply to that post type and not others (so keeping the vernacular separate). Would that be a sensible use of taxonomies as I've seen some quite confusing (mis)use of taxonomies its seems in Wordpress.</p>
|
[
{
"answer_id": 208490,
"author": "John Lucey",
"author_id": 83434,
"author_profile": "https://wordpress.stackexchange.com/users/83434",
"pm_score": 0,
"selected": false,
"text": "<p>This process actually involves purchasing a security Certificate and applying it to your server for your websites. This will in turn force everyone visiting into a secure connection via the certificate presented by your server. These certificates are called SSL Certs: <a href=\"http://www.DigiCert.com/SSL-Certificates\" rel=\"nofollow\">http://www.DigiCert.com/SSL-Certificates</a></p>\n"
},
{
"answer_id": 235021,
"author": "David",
"author_id": 31323,
"author_profile": "https://wordpress.stackexchange.com/users/31323",
"pm_score": 0,
"selected": false,
"text": "<p>One possible way to do this data modification is to use <a href=\"http://wp-cli.org/\" rel=\"nofollow\">WP-CLI</a> on the terminal. </p>\n\n<p>First of all, you should make sure you have a backup and a solid restore strategy in case anything goes wrong. You should also test this procedure on a local or testing system with a copy of the live database.</p>\n\n<p>The basic steps are, to iterate over each site of your network and replace the URLs of each site using WP-CLI's <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\"><code>search-replace</code> command</a>. </p>\n\n<p>Here's a bash one-liner:</p>\n\n<pre><code>for SITE in $(wp site list --field=url); do wp search-replace \"{$SITE}\" \"${SITE/http:/https:}\" --dry-run --precise --network --verbose; done\n</code></pre>\n\n<p>Let's examine that: </p>\n\n<pre><code>for SITE in $(wp site list --field=url);\n</code></pre>\n\n<p>That one starts a loop for each line of the output of the command inside <code>$()</code> and writes each line in the variable <code>$SITE</code>.</p>\n\n<pre><code>$(wp site list --field=url)\n</code></pre>\n\n<p>That's the WP-CLI <a href=\"http://wp-cli.org/commands/site/list/\" rel=\"nofollow\"><code>site list</code> command</a> which gives you a list of all site URLs in your network. Run this command solely, you will probably see something like:</p>\n\n<pre><code>http://your-site.tld/\nhttp://your-site.tld/site2/\nhttp://another-of.your-site.tld/\n...\n</code></pre>\n\n<p>Now</p>\n\n<pre><code>...); do\n</code></pre>\n\n<p>will just start the inner loop part.</p>\n\n<p>The inner loop command does all the magic (I split it to two lines using <code>\\</code> for readability):</p>\n\n<pre><code>wp search-replace \"$SITE\" \"${SITE/http:/https:}\" \\\n--dry-run --precise --network --verbose\n</code></pre>\n\n<p>We tell WP-CLI to <em>search</em> for <code>$SITE</code> (e.g. <code>https://your-site.tld/</code>) and <em>replace</em> it with a slightly modified version: <code>${SITE/http:/https:}</code>. This is a bash string replaces operation that replaces <code>http:</code> with <code>https:</code>. (So resolving the variables, the command would look like <code>wp search-replace \"http://your-site.tdl/\" \"https://your-site.tld/\"</code>).</p>\n\n<p><code>search-replace</code> has many possible options that are described in the <a href=\"http://wp-cli.org/commands/search-replace/\" rel=\"nofollow\">documentation</a>. In the example I used these:</p>\n\n<pre><code>--dry-run --precise --network --verbose\n</code></pre>\n\n<p><code>--dry-run</code> and <code>--verbose</code> are clearly helpful for testing the command. </p>\n\n<p><code>--network</code> applies the search and replace operation also to the network tabels.</p>\n\n<p><code>--precise</code> tells WP-CLI to use PHP instead of SQL to search and replace the values. That ensures serialized values to not get corrupted. </p>\n\n<p>Finally the loop is closed with</p>\n\n<pre><code>; done\n</code></pre>\n\n<p>Let me emphasize it again: test this deeply before you start using this on production. You should understand how it work and what WP-CLI does. I used WP-CLI before to perform such searach and replace operations to migrate multisites to other domain names, but not to switch from <code>http</code> to <code>https</code>.</p>\n\n<p>There might be some edge cases: WP-CLI still reads the <code>wp-config.php</code> and try to find a matching «network» in the database by using the constants in <code>wp-config.php</code>. If you're manipulating one site (the database) but not the other one (the constants in <code>wp-config.php</code>) you <em>might</em> get into trouble. But for your case, I think that won't be a problem as WP typically relies on <code>DOMAIN_CURRENT_SITE</code> and <code>PATH_CURRENT_SITE</code> and they won't change anyway. But again, test this thorough. </p>\n\n<p>With a bit more bash magic, you could also split this loop into chunks of 5 or 10 sites and go through it step by step.</p>\n"
},
{
"answer_id": 235887,
"author": "Ethan O'Sullivan",
"author_id": 98212,
"author_profile": "https://wordpress.stackexchange.com/users/98212",
"pm_score": 0,
"selected": false,
"text": "<p>To ensure all of your websites use HTTPS in your <code>post_content</code>, you can perform one of two options:</p>\n\n<h3>1. Backend: execute a SQL query</h3>\n\n<p>To make sure that all of your HTTP links are set as HTTPS, use the following SQL query:</p>\n\n<pre><code>UPDATE wp_options SET option_value = replace(option_value, 'OLD_URL', 'NEW_URL') WHERE option_name = 'home' OR option_name = 'siteurl';\nUPDATE wp_posts SET guid = replace(guid, 'OLD_URL','NEW_URL');\nUPDATE wp_posts SET post_content = replace(post_content, 'OLD_URL', 'NEW_URL');\nUPDATE wp_postmeta SET meta_value = replace(meta_value,'OLD_URL','NEW_URL');\n</code></pre>\n\n<ul>\n<li><code>OLD_URL</code> will be replaced with <code>http://example.com</code> (non-HTTP)</li>\n<li><code>NEW_URL</code> will be replaced with <code>https://example.com</code> (HTTPS)</li>\n</ul>\n\n<p>This will cover the <code>siteurl</code>, <code>home</code>, and all of your content on your website to the new HTTPS.</p>\n\n<h3>2. Frontend: use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">Search & Replace</a> plugin</h3>\n\n<p>A more user-friendly approach is to use the <a href=\"https://wordpress.org/plugins/search-and-replace/\" rel=\"nofollow\">Search & Replace</a> plugin to easily replace all tables that contain your old HTTP and change them to a HTTPS. The process is easy to use and you can preview what tables and rows will be affected before applying those changes.</p>\n\n<h3>Forewarning</h3>\n\n<p>Before applying any changes, I think it goes without saying to always make a backup of your database in the event something goes wrong.</p>\n"
},
{
"answer_id": 237455,
"author": "The J",
"author_id": 98010,
"author_profile": "https://wordpress.stackexchange.com/users/98010",
"pm_score": 1,
"selected": false,
"text": "<p>You could run a script to UPDATE all urls and guids to https, if you want a clean setup. </p>\n\n<p>But also consider alternatives such as:</p>\n\n<pre><code><IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteCond %{SERVER_PORT} 80 \nRewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]\n</IfModule>\n</code></pre>\n\n<p>In wp-config.php for the backend:</p>\n\n<pre><code>define('FORCE_SSL_ADMIN', true);\n</code></pre>\n\n<p>In wp-config.php for the frontend (or run a db UPDATE script):</p>\n\n<pre><code>define('WP_HOME','https://example.com');\ndefine('WP_SITEURL','https://example.com');\n</code></pre>\n\n<p>Then you could simply run a script to UPDATE all wp_posts content url.</p>\n"
},
{
"answer_id": 238711,
"author": "Harshita",
"author_id": 102498,
"author_profile": "https://wordpress.stackexchange.com/users/102498",
"pm_score": 0,
"selected": false,
"text": "<p>HTTP is a default protocol, which is used by most websites to handle the information over the web. Your website is running on HTTPS without any error message, it means your certificate has been installed correctly. You should migrate your entire website from HTTP to HTTPS. </p>\n\n<p><a href=\"https://make.wordpress.org/support/user-manual/web-publishing/https-for-wordpress/\" rel=\"nofollow\">Learn how to move HTTP to HTTPS for WordPress</a></p>\n"
}
] |
2015/11/13
|
[
"https://wordpress.stackexchange.com/questions/208545",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17862/"
] |
I have a site with numerous custom post types that are created using a class. I was considering whether it was worth creating a custom taxonomy for each custom post type to offer a way of organizing and categorizing within that custom post type *-e.g* terms and tags that only apply to that post type and not others (so keeping the vernacular separate). Would that be a sensible use of taxonomies as I've seen some quite confusing (mis)use of taxonomies its seems in Wordpress.
|
You could run a script to UPDATE all urls and guids to https, if you want a clean setup.
But also consider alternatives such as:
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://www.yoursite.com/$1 [R,L]
</IfModule>
```
In wp-config.php for the backend:
```
define('FORCE_SSL_ADMIN', true);
```
In wp-config.php for the frontend (or run a db UPDATE script):
```
define('WP_HOME','https://example.com');
define('WP_SITEURL','https://example.com');
```
Then you could simply run a script to UPDATE all wp\_posts content url.
|
208,565 |
<p>I looked at some code for an article and saw that there was a shortcode contained in a <code><p></code> tag:</p>
<pre><code><p>Blabla</p>
<p>[shortcode]</p>
<p>Wofwof</p>
</code></pre>
<p>The shortcode doesn't seem to work. Could it have anything to do with that it's contained in the paragraph tag?</p>
|
[
{
"answer_id": 208550,
"author": "shadylane",
"author_id": 82498,
"author_profile": "https://wordpress.stackexchange.com/users/82498",
"pm_score": 0,
"selected": false,
"text": "<p>I'm not sure if it's the cause, but wouldn't you be better off using mod_php? The performance should be much better than php-cgi - I've never used that in production, but I'm a creature of habit.\nPHP shouldn't be writing a lot to the disk. AFAIK, the main cases where it would write to the disk are.</p>\n\n<ol>\n<li>Server is using swap space (unlikely due to the large amount of RAM you have - worth checking though)</li>\n<li>PHP is generating hundreds of notices and warnings and writing to the error logs (solution: change error reporting level or actually fix the code problems)</li>\n<li>W3 Total Cache config problem - try altering the expiration time of the cache to see if it makes a difference.</li>\n</ol>\n\n<p>3.9MB is also a crazy page size, you could probably do a lot to optimise that, use a CDN for static assets etc.</p>\n"
},
{
"answer_id": 208563,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>writes probably have nothing to do with that (unless there are more details), your problem is file reads</p>\n\n<p>An obvious cause is using cgi instead of mod_php or fastcgi <a href=\"https://stackoverflow.com/questions/14489346/is-it-possible-to-run-apc-with-php-cgi\">https://stackoverflow.com/questions/14489346/is-it-possible-to-run-apc-with-php-cgi</a>. The use of CGI makes the PHP interpreter to read all the files for each request, and if APC could have worked, the PHP would have read only about once every two seconds (configurable), and this is before considering other APC optimizations.</p>\n\n<p>It doesn't help that you have so many requests per page. Fuck whatever google speed tells you about your site, it sends you to optimize browser caching but in practice the effectiveness of browser caching depends on how frequently the people come to your site. IIRC a test done by yahoo several years ago showed that 50% of visitors did not had the yahoo files cached when they accessed the site. The point is that high score in browser caching do not translate to your server not being hit with 250 request for every page request.</p>\n\n<p>Depending on the rate of page requests and hard drive technology you might just be putting the disk controller at busy state all the time (this will also depend on how much the hard drive driver caches files in memory.\nIf you have to have so many requests, maybe you should put the relevant files on memory disk.</p>\n\n<p>You have a beast of an app server and 1000 user at the \"same time\" is not that much (I saw 2x8GB handling 7x your load without sweating at all). Of cource it depends on what your code actually does.... My suggestion is that you should investigate the cost of using CDN. It might be that once your hardware do not need to serve all those files you might be able to reduce the server requirements which might offset the cost of the CDN.</p>\n"
},
{
"answer_id": 211140,
"author": "Xavier Fox",
"author_id": 60023,
"author_profile": "https://wordpress.stackexchange.com/users/60023",
"pm_score": 2,
"selected": true,
"text": "<p>so i managed to figure out what the problem was, your inputs were all help full in pointing me in the right direction. so what was causing my high disk i/o was the php_cgi_maxrequest value which was set at 99999, so i increased the value to 200,000 in the disk i/o shot down drastically, and i'm experiencing a more stable server environment since the change.</p>\n"
}
] |
2015/11/13
|
[
"https://wordpress.stackexchange.com/questions/208565",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83551/"
] |
I looked at some code for an article and saw that there was a shortcode contained in a `<p>` tag:
```
<p>Blabla</p>
<p>[shortcode]</p>
<p>Wofwof</p>
```
The shortcode doesn't seem to work. Could it have anything to do with that it's contained in the paragraph tag?
|
so i managed to figure out what the problem was, your inputs were all help full in pointing me in the right direction. so what was causing my high disk i/o was the php\_cgi\_maxrequest value which was set at 99999, so i increased the value to 200,000 in the disk i/o shot down drastically, and i'm experiencing a more stable server environment since the change.
|
208,608 |
<p>I'm looking for a safe and fast way to delete all of one custom post type's posts. Using <code>get_posts()</code> and <code>wp_delete_post()</code> for each returned post does not work; it's not fast enough due to the sheer amount of database queries involved (timeout error).</p>
<p>Preferably, I'm looking for a single database query to run that deletes all posts that are of a custom post type. Any thoughts?</p>
|
[
{
"answer_id": 275584,
"author": "pathusutariya",
"author_id": 125122,
"author_profile": "https://wordpress.stackexchange.com/users/125122",
"pm_score": 5,
"selected": false,
"text": "<p>You can delete all post via <code>$wpdb</code></p>\n\n<pre><code>DELETE FROM wp_posts WHERE post_type='post_type';\nDELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT id FROM wp_posts);\nDELETE FROM wp_term_relationships WHERE object_id NOT IN (SELECT id FROM wp_posts)\n</code></pre>\n\n<p>or use this query replace it with {{your CPT}} with your Custom Post Type</p>\n\n<pre><code>DELETE a,b,c\n FROM wp_posts a\n LEFT JOIN wp_term_relationships b\n ON (a.ID = b.object_id)\n LEFT JOIN wp_postmeta c\n ON (a.ID = c.post_id)\n WHERE a.post_type = '{{your CPT}}';\n</code></pre>\n"
},
{
"answer_id": 315738,
"author": "Saruque Ahamed Mollick",
"author_id": 151665,
"author_profile": "https://wordpress.stackexchange.com/users/151665",
"pm_score": 4,
"selected": false,
"text": "<p>You can delete all posts of a custom post type in various methods but here I am gonna show you how to do this without using SQL query.\nHere, for example, our post type is <strong>product</strong></p>\n\n<pre><code>$allposts= get_posts( array('post_type'=>'product','numberposts'=>-1) );\nforeach ($allposts as $eachpost) {\nwp_delete_post( $eachpost->ID, true );\n}\n</code></pre>\n\n<p><a href=\"https://www.codespeedy.com/delete-all-posts-from-custom-post-type-in-wordpress/\" rel=\"noreferrer\">See full tutorial Reference Here</a></p>\n"
},
{
"answer_id": 368268,
"author": "jwinn",
"author_id": 82970,
"author_profile": "https://wordpress.stackexchange.com/users/82970",
"pm_score": 4,
"selected": false,
"text": "<p>This can now be done with the <a href=\"https://wp-cli.org\" rel=\"noreferrer\">WordPress CLI</a> using <strong><a href=\"https://developer.wordpress.org/cli/commands/post/delete/\" rel=\"noreferrer\">wp post delete</a></strong>. Once the CLI is installed, the following terminal command (while in your site's root directory) will delete all posts of type <code>mycustomtype</code>:</p>\n\n<p><code>wp post delete $(wp post list --post_type='mycustomtype' --format=ids)</code></p>\n\n<p>No raw SQL (*<em>shudder</em>*), no worrying about timeouts, and it's fast. For example, I just deleted ~2500 posts in less than two minutes.</p>\n"
},
{
"answer_id": 414333,
"author": "Orkan",
"author_id": 186907,
"author_profile": "https://wordpress.stackexchange.com/users/186907",
"pm_score": 0,
"selected": false,
"text": "<p>If you have prefixed your CPT post type and your CPT taxonomies with eg. 'abc_my_custom_post_type' and 'abc_my_taxonomy' then it's trivial to remove everything from db with two queries:</p>\n<pre><code>DELETE a,b\nFROM $wpdb->posts a\nLEFT JOIN $wpdb->postmeta b ON a.ID = b.post_id\nWHERE a.post_type LIKE 'abc_%';\n \nDELETE a,b,c\nFROM $wpdb->term_taxonomy a\nLEFT JOIN $wpdb->term_relationships b ON a.term_taxonomy_id = b.term_taxonomy_id\nLEFT JOIN $wpdb->terms c ON a.term_id = c.term_id\nWHERE a.taxonomy LIKE 'abc_%'\n</code></pre>\n"
}
] |
2015/11/13
|
[
"https://wordpress.stackexchange.com/questions/208608",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/32848/"
] |
I'm looking for a safe and fast way to delete all of one custom post type's posts. Using `get_posts()` and `wp_delete_post()` for each returned post does not work; it's not fast enough due to the sheer amount of database queries involved (timeout error).
Preferably, I'm looking for a single database query to run that deletes all posts that are of a custom post type. Any thoughts?
|
You can delete all post via `$wpdb`
```
DELETE FROM wp_posts WHERE post_type='post_type';
DELETE FROM wp_postmeta WHERE post_id NOT IN (SELECT id FROM wp_posts);
DELETE FROM wp_term_relationships WHERE object_id NOT IN (SELECT id FROM wp_posts)
```
or use this query replace it with {{your CPT}} with your Custom Post Type
```
DELETE a,b,c
FROM wp_posts a
LEFT JOIN wp_term_relationships b
ON (a.ID = b.object_id)
LEFT JOIN wp_postmeta c
ON (a.ID = c.post_id)
WHERE a.post_type = '{{your CPT}}';
```
|
208,615 |
<p>I have a WordPress theme that includes jQuery, but for some reason the "$" doesn't let me call jQuery. I know I can wrap <a href="https://stackoverflow.com/questions/10371539/why-define-anonymous-function-and-pass-jquery-as-the-argument/10372429#10372429">jQuery calls in an anonymous function</a>, but I have other plugins that rely on the $ working, and I don't want to modify their code.</p>
<p>So I need a way to make "$" work for jQuery, globally, across all JS in my site. </p>
<p>My theme adds jQuery with this (in functions.php):</p>
<pre><code>function ss_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_style( 'ss-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'ss_scripts' );
</code></pre>
<p>So two questions:</p>
<ol>
<li>Why doesn't jQuery default to the "$" when the script is added this
way?</li>
<li>How can I make the $ use jQuery, globally, across my entire
site?</li>
</ol>
|
[
{
"answer_id": 208617,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of $ use 'jQuery'. I am not sure about your WordPress version. For the updates with jQuery. 1. 9. It's better to use jQuery instead of $. </p>\n"
},
{
"answer_id": 208623,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>Why doesn't jQuery default to the \"$\" when the script is added this\n way?</p>\n</blockquote>\n\n<p>The <code>$</code> alias has been chosen by several different libraries an alias. This causes conflict if you try to use more than one library. It is a bit ridiculous, actually-- like several major corporations all deciding to use the same phone number.</p>\n\n<blockquote>\n <p>How can I make the $ use jQuery, globally, across my entire site?</p>\n</blockquote>\n\n<p>WordPress load jQuery in <a href=\"https://api.jquery.com/jquery.noconflict/\" rel=\"nofollow\">noConflict mode</a> to avoid the problems caused by the above foolish aliasing. You should not reintroduce those issues. </p>\n"
},
{
"answer_id": 208636,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>To use <code>$</code> as the object reference, you need to do this after jQuery is included and before any other script that uses <code>$</code>:</p>\n\n<pre><code>var $ = jQuery.noConflict();\n</code></pre>\n\n<p>Use at your own risk, may conflict with other code.</p>\n\n<p>Technically, any jQuery plugin that relies on <code>$</code> is written incorrectly.</p>\n"
}
] |
2015/11/14
|
[
"https://wordpress.stackexchange.com/questions/208615",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/13981/"
] |
I have a WordPress theme that includes jQuery, but for some reason the "$" doesn't let me call jQuery. I know I can wrap [jQuery calls in an anonymous function](https://stackoverflow.com/questions/10371539/why-define-anonymous-function-and-pass-jquery-as-the-argument/10372429#10372429), but I have other plugins that rely on the $ working, and I don't want to modify their code.
So I need a way to make "$" work for jQuery, globally, across all JS in my site.
My theme adds jQuery with this (in functions.php):
```
function ss_scripts() {
wp_enqueue_script('jquery');
wp_enqueue_script('jquery-ui-core');
wp_enqueue_style( 'ss-style', get_stylesheet_uri() );
}
add_action( 'wp_enqueue_scripts', 'ss_scripts' );
```
So two questions:
1. Why doesn't jQuery default to the "$" when the script is added this
way?
2. How can I make the $ use jQuery, globally, across my entire
site?
|
>
> Why doesn't jQuery default to the "$" when the script is added this
> way?
>
>
>
The `$` alias has been chosen by several different libraries an alias. This causes conflict if you try to use more than one library. It is a bit ridiculous, actually-- like several major corporations all deciding to use the same phone number.
>
> How can I make the $ use jQuery, globally, across my entire site?
>
>
>
WordPress load jQuery in [noConflict mode](https://api.jquery.com/jquery.noconflict/) to avoid the problems caused by the above foolish aliasing. You should not reintroduce those issues.
|
208,616 |
<p>I have tried many answers here on stackoverflow but couldnt find a solution to my problem. I have created a custom post type called <code>ph_products</code> and custom taxonomies with the name <code>ph_category</code>.</p>
<p>Then I created some categories for that custom post type like this:</p>
<pre><code>blue-products
blue-sub-products
green-products
red-products
</code></pre>
<p>I need to have body classes as following:</p>
<p>When on the <code>ph_products-archive</code> page there should be a class with that slug in the body</p>
<p>When on one of the parent categories the respective slug should be in the body class</p>
<p>And when I am on one of the sub category archive pages I need to also have the parent category class</p>
<p>For example I am at the <code>blue-sub-products</code> archive page I want to have <code>blue-products, ph_products-archive, blue-sub-products</code> in the body class</p>
<p>Of course I need all of these classes in the respective single views of the products as well.</p>
<p>I use this piece of code to add the desired classes:</p>
<p>(thanks to <a href="https://alexanderdejong.com/wordpress/add-custom-taxonomies-body-class" rel="nofollow">https://alexanderdejong.com/wordpress/add-custom-taxonomies-body-class</a>)</p>
<pre><code>function atp_custom_taxonomy_body_class($classes, $class, $ID) {
$taxonomies_args = array(
'public' => true,
'_builtin' => false,
);
$taxonomies = get_taxonomies( $taxonomies_args, 'names', 'and' );
foreach ($taxonomies as $taxonomy) {
$terms = get_the_terms( (int) $ID, $taxonomy );
if ( ! empty( $terms ) ) {
foreach ( (array) $terms as $order => $term ) {
if ( ! in_array( $term->slug, $classes ) ) {
$classes[] = $term->slug;
}
}
}
}
return $classes;
}
add_filter( 'body_class', 'atp_custom_taxonomy_body_class', 10, 3 );
</code></pre>
<p>But this kinda adds the classes pretty weird for example when I am on the <code>ph_products-archive</code> page I also get the category slugs of the last item posted there so if the last item is in the categories <code>blue-products, blue-sub-products</code> I get these two slugs as classes as well although I am not at these category pages</p>
<p>Or when I am at the <code>blue-products-archive</code> page I also get the <code>blue-sub-products</code> category slug in the body class.</p>
<p>How can I only get the classes desired as described above?</p>
|
[
{
"answer_id": 208617,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 0,
"selected": false,
"text": "<p>Instead of $ use 'jQuery'. I am not sure about your WordPress version. For the updates with jQuery. 1. 9. It's better to use jQuery instead of $. </p>\n"
},
{
"answer_id": 208623,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": true,
"text": "<blockquote>\n <p>Why doesn't jQuery default to the \"$\" when the script is added this\n way?</p>\n</blockquote>\n\n<p>The <code>$</code> alias has been chosen by several different libraries an alias. This causes conflict if you try to use more than one library. It is a bit ridiculous, actually-- like several major corporations all deciding to use the same phone number.</p>\n\n<blockquote>\n <p>How can I make the $ use jQuery, globally, across my entire site?</p>\n</blockquote>\n\n<p>WordPress load jQuery in <a href=\"https://api.jquery.com/jquery.noconflict/\" rel=\"nofollow\">noConflict mode</a> to avoid the problems caused by the above foolish aliasing. You should not reintroduce those issues. </p>\n"
},
{
"answer_id": 208636,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 1,
"selected": false,
"text": "<p>To use <code>$</code> as the object reference, you need to do this after jQuery is included and before any other script that uses <code>$</code>:</p>\n\n<pre><code>var $ = jQuery.noConflict();\n</code></pre>\n\n<p>Use at your own risk, may conflict with other code.</p>\n\n<p>Technically, any jQuery plugin that relies on <code>$</code> is written incorrectly.</p>\n"
}
] |
2015/11/14
|
[
"https://wordpress.stackexchange.com/questions/208616",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/64793/"
] |
I have tried many answers here on stackoverflow but couldnt find a solution to my problem. I have created a custom post type called `ph_products` and custom taxonomies with the name `ph_category`.
Then I created some categories for that custom post type like this:
```
blue-products
blue-sub-products
green-products
red-products
```
I need to have body classes as following:
When on the `ph_products-archive` page there should be a class with that slug in the body
When on one of the parent categories the respective slug should be in the body class
And when I am on one of the sub category archive pages I need to also have the parent category class
For example I am at the `blue-sub-products` archive page I want to have `blue-products, ph_products-archive, blue-sub-products` in the body class
Of course I need all of these classes in the respective single views of the products as well.
I use this piece of code to add the desired classes:
(thanks to <https://alexanderdejong.com/wordpress/add-custom-taxonomies-body-class>)
```
function atp_custom_taxonomy_body_class($classes, $class, $ID) {
$taxonomies_args = array(
'public' => true,
'_builtin' => false,
);
$taxonomies = get_taxonomies( $taxonomies_args, 'names', 'and' );
foreach ($taxonomies as $taxonomy) {
$terms = get_the_terms( (int) $ID, $taxonomy );
if ( ! empty( $terms ) ) {
foreach ( (array) $terms as $order => $term ) {
if ( ! in_array( $term->slug, $classes ) ) {
$classes[] = $term->slug;
}
}
}
}
return $classes;
}
add_filter( 'body_class', 'atp_custom_taxonomy_body_class', 10, 3 );
```
But this kinda adds the classes pretty weird for example when I am on the `ph_products-archive` page I also get the category slugs of the last item posted there so if the last item is in the categories `blue-products, blue-sub-products` I get these two slugs as classes as well although I am not at these category pages
Or when I am at the `blue-products-archive` page I also get the `blue-sub-products` category slug in the body class.
How can I only get the classes desired as described above?
|
>
> Why doesn't jQuery default to the "$" when the script is added this
> way?
>
>
>
The `$` alias has been chosen by several different libraries an alias. This causes conflict if you try to use more than one library. It is a bit ridiculous, actually-- like several major corporations all deciding to use the same phone number.
>
> How can I make the $ use jQuery, globally, across my entire site?
>
>
>
WordPress load jQuery in [noConflict mode](https://api.jquery.com/jquery.noconflict/) to avoid the problems caused by the above foolish aliasing. You should not reintroduce those issues.
|
208,677 |
<p>During a large brute force attack, I'd like to shut off the ability to log into WordPress entirely. The only account on the site is mine, so there's no reason for visitors to login and it wouldn't hurt their experience on the site. </p>
<p>When I need to login, I can remove the code. Alternatively, I can limit logins to just my IP address.</p>
<p>I'm trying to achieve this by catching a login attempt as early as possible with the following code</p>
<pre><code>if (isset($_POST['pwd']) || isset($_GET['pwd'])) {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
echo 'logins to the site are disabled';
die();
}
</code></pre>
<p>This is crude but it should work. However, there are still some login attempts getting through and I don't know where they could be coming from.</p>
<p>How else does WordPress accept logins, if it's not with the 'pwd' field?</p>
<p>Is there an existing convention for shutting down logins?</p>
<p>Edit: in addition to stopping wp-login.php, I deleted xmlrpc.php which was being used as another entry into brute forcing logins. My current setup doesn't need it but yours might. Be sure you don't need it before you disable it.</p>
|
[
{
"answer_id": 208678,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>Failing to authenticate should do the trick for all the kinds of possible authentication - login form, xmlrpc, ajax, whatever</p>\n\n<p><strong>Edit</strong>: actually realized there is a way to save sending the user related query to the DB</p>\n\n<pre><code>function wpse208677_authenticate($user,$username,$pass) {\n remove_filter('authenticate','wp_authenticate_username_password',20,3);\n return null;\n // if you want to whitelist your ip check for it and return $user\n}\n\nadd_filter('authenticate','wpse208677_authenticate', 10,3)\n</code></pre>\n"
},
{
"answer_id": 208680,
"author": "Ashvinee Rai",
"author_id": 83593,
"author_profile": "https://wordpress.stackexchange.com/users/83593",
"pm_score": -1,
"selected": false,
"text": "<p>you can fix this issues using </p>\n\n<p>change \"wp-admin\" directory and protect this directory using .htaccess password</p>\n"
},
{
"answer_id": 298220,
"author": "Branndon",
"author_id": 81952,
"author_profile": "https://wordpress.stackexchange.com/users/81952",
"pm_score": 1,
"selected": false,
"text": "<p>The top answer here is horribly bad PHP code, completely broken. Here is a good version. My reputation points are too low to comment on the original answer. </p>\n\n<p>This code can be placed at the very bottom of <code>wp-config.php</code> in a pinch.</p>\n\n<pre><code>function wpse208677_authenticate($user,$username,$pass) {\n remove_filter('authenticate','wp_authenticate_username_password',20,3);\n return null;\n // if you want to whitelist your ip check for it and return $user\n}\nadd_filter('authenticate','wpse208677_authenticate', 1,3)\n</code></pre>\n\n<p>Another option is to prevent access to the login/register pages. This even works behind a hidden login url for WordPress. This code can be placed at the very top of <code>wp-config.php</code> (after the opening <code><?php</code>.</p>\n\n<pre><code>if ( in_array( $_SERVER['PHP_SELF'], array( '/wp-login.php', '/wp-register.php' ) ) ){\n die('Site in maintenance mode.');\n}\n</code></pre>\n"
}
] |
2015/11/14
|
[
"https://wordpress.stackexchange.com/questions/208677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27742/"
] |
During a large brute force attack, I'd like to shut off the ability to log into WordPress entirely. The only account on the site is mine, so there's no reason for visitors to login and it wouldn't hurt their experience on the site.
When I need to login, I can remove the code. Alternatively, I can limit logins to just my IP address.
I'm trying to achieve this by catching a login attempt as early as possible with the following code
```
if (isset($_POST['pwd']) || isset($_GET['pwd'])) {
header($_SERVER["SERVER_PROTOCOL"]." 404 Not Found");
echo 'logins to the site are disabled';
die();
}
```
This is crude but it should work. However, there are still some login attempts getting through and I don't know where they could be coming from.
How else does WordPress accept logins, if it's not with the 'pwd' field?
Is there an existing convention for shutting down logins?
Edit: in addition to stopping wp-login.php, I deleted xmlrpc.php which was being used as another entry into brute forcing logins. My current setup doesn't need it but yours might. Be sure you don't need it before you disable it.
|
Failing to authenticate should do the trick for all the kinds of possible authentication - login form, xmlrpc, ajax, whatever
**Edit**: actually realized there is a way to save sending the user related query to the DB
```
function wpse208677_authenticate($user,$username,$pass) {
remove_filter('authenticate','wp_authenticate_username_password',20,3);
return null;
// if you want to whitelist your ip check for it and return $user
}
add_filter('authenticate','wpse208677_authenticate', 10,3)
```
|
208,710 |
<p>this is my link. <a href="http://redesign.conei-sa.com/apps_cat" rel="nofollow">http://redesign.conei-sa.com/apps_cat</a> . not found .</p>
<p>My code in function.php. </p>
<pre><code>function prefix_register_post_type()
{
register_post_type(
'application',
array(
'labels' => array(
'name' => __('Application', 'text_domain'),
'singular_name' => __('Application', 'text_domain'),
'menu_name' => __('Application', 'text_domain'),
'name_admin_bar' => __('Application Item', 'text_domain'),
'all_items' => __('All Items', 'text_domain'),
'add_new' => _x('Add New', 'prefix_portfolio', 'text_domain'),
'add_new_item' => __('Add New Item', 'text_domain'),
'edit_item' => __('Edit Item', 'text_domain'),
'new_item' => __('New Item', 'text_domain'),
'view_item' => __('View Item', 'text_domain'),
'search_items' => __('Search Items', 'text_domain'),
'not_found' => __('No items found.', 'text_domain'),
'not_found_in_trash' => __('No items found in Trash.', 'text_domain'),
'parent_item_colon' => __('Parent Items:', 'text_domain'),
),
'public' => true,
'menu_position' => 5,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'custom-fields',
),
'taxonomies' => array(
'apps_cat',
),
'has_archive' => true,
'rewrite' => array(
'slug' => 'application',
),
)
);
}
add_action('init', 'prefix_register_post_type');
function prefix_register_taxonomy()
{
register_taxonomy(
'apps_cat',
array(
'application',
),
array(
'labels' => array(
'name' => _x('Categories', 'prefix_portfolio', 'text_domain'),
'singular_name' => _x('Category', 'prefix_portfolio', 'text_domain'),
'menu_name' => __('Categories', 'text_domain'),
'all_items' => __('All Categories', 'text_domain'),
'edit_item' => __('Edit Category', 'text_domain'),
'view_item' => __('View Category', 'text_domain'),
'update_item' => __('Update Category', 'text_domain'),
'add_new_item' => __('Add New Category', 'text_domain'),
'new_item_name' => __('New Category Name', 'text_domain'),
'parent_item' => __('Parent Category', 'text_domain'),
'parent_item_colon' => __('Parent Category:', 'text_domain'),
'search_items' => __('Search Categories', 'text_domain'),
),
'public' => true,
'show_admin_column' => true,
'hierarchical' => true,
'query_var' => true,
"rewrite" => true,
'rewrite' => array(
'slug' => 'apps_cat',
),
)
);
}
add_action('init', 'prefix_register_taxonomy', 0);
</code></pre>
<p>The link is found redesign.conei-sa.com/apps_cat/indexes but redesign.conei-sa.com/apps_cat this is not..</p>
<p>Sorry for my poor english. </p>
|
[
{
"answer_id": 208714,
"author": "Tung Du",
"author_id": 83304,
"author_profile": "https://wordpress.stackexchange.com/users/83304",
"pm_score": 1,
"selected": false,
"text": "<p>It's not how taxonomy work. The apps_cat is just the taxonomy, not the term. Like category, you will receive not found with <a href=\"http://redesign.conei-sa.com/category\" rel=\"nofollow\">http://redesign.conei-sa.com/category</a>. You must point to a specific term of apps_cat. apps_cat can't have any post, only the term of it has.</p>\n\n<p>Anyway, if you got not found with term page, try update permalink structure. Another tip for testing you can try is switching to default permalink while coding to make sure it work, then switch back to pretty permalink.</p>\n"
},
{
"answer_id": 259038,
"author": "Alex",
"author_id": 94487,
"author_profile": "https://wordpress.stackexchange.com/users/94487",
"pm_score": 0,
"selected": false,
"text": "<p>What worked for me for this same problem is to simply change my permalinks to just regular post name structure and update it, which is how my custom post type permalinks looked anyway. I also heard that simply updating the permalinks should work.</p>\n"
}
] |
2015/11/15
|
[
"https://wordpress.stackexchange.com/questions/208710",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83123/"
] |
this is my link. <http://redesign.conei-sa.com/apps_cat> . not found .
My code in function.php.
```
function prefix_register_post_type()
{
register_post_type(
'application',
array(
'labels' => array(
'name' => __('Application', 'text_domain'),
'singular_name' => __('Application', 'text_domain'),
'menu_name' => __('Application', 'text_domain'),
'name_admin_bar' => __('Application Item', 'text_domain'),
'all_items' => __('All Items', 'text_domain'),
'add_new' => _x('Add New', 'prefix_portfolio', 'text_domain'),
'add_new_item' => __('Add New Item', 'text_domain'),
'edit_item' => __('Edit Item', 'text_domain'),
'new_item' => __('New Item', 'text_domain'),
'view_item' => __('View Item', 'text_domain'),
'search_items' => __('Search Items', 'text_domain'),
'not_found' => __('No items found.', 'text_domain'),
'not_found_in_trash' => __('No items found in Trash.', 'text_domain'),
'parent_item_colon' => __('Parent Items:', 'text_domain'),
),
'public' => true,
'menu_position' => 5,
'supports' => array(
'title',
'editor',
'thumbnail',
'excerpt',
'custom-fields',
),
'taxonomies' => array(
'apps_cat',
),
'has_archive' => true,
'rewrite' => array(
'slug' => 'application',
),
)
);
}
add_action('init', 'prefix_register_post_type');
function prefix_register_taxonomy()
{
register_taxonomy(
'apps_cat',
array(
'application',
),
array(
'labels' => array(
'name' => _x('Categories', 'prefix_portfolio', 'text_domain'),
'singular_name' => _x('Category', 'prefix_portfolio', 'text_domain'),
'menu_name' => __('Categories', 'text_domain'),
'all_items' => __('All Categories', 'text_domain'),
'edit_item' => __('Edit Category', 'text_domain'),
'view_item' => __('View Category', 'text_domain'),
'update_item' => __('Update Category', 'text_domain'),
'add_new_item' => __('Add New Category', 'text_domain'),
'new_item_name' => __('New Category Name', 'text_domain'),
'parent_item' => __('Parent Category', 'text_domain'),
'parent_item_colon' => __('Parent Category:', 'text_domain'),
'search_items' => __('Search Categories', 'text_domain'),
),
'public' => true,
'show_admin_column' => true,
'hierarchical' => true,
'query_var' => true,
"rewrite" => true,
'rewrite' => array(
'slug' => 'apps_cat',
),
)
);
}
add_action('init', 'prefix_register_taxonomy', 0);
```
The link is found redesign.conei-sa.com/apps\_cat/indexes but redesign.conei-sa.com/apps\_cat this is not..
Sorry for my poor english.
|
It's not how taxonomy work. The apps\_cat is just the taxonomy, not the term. Like category, you will receive not found with <http://redesign.conei-sa.com/category>. You must point to a specific term of apps\_cat. apps\_cat can't have any post, only the term of it has.
Anyway, if you got not found with term page, try update permalink structure. Another tip for testing you can try is switching to default permalink while coding to make sure it work, then switch back to pretty permalink.
|
208,733 |
<p>I've been handed a vulnerability report(1) that seems to be implying that there may be a security issue in the way Wordpress handles URLs with following tildes. It seems the scanner thinks the website may be serving up some directory listings and the such.</p>
<p>I was surprised that my website was still serving content on those different URLs, so I did a test by installing a totally blank WP instance, switched to "Post name" permalinks, and confirmed that yep, any URL with added tilde still gets interpreted as the URL without the tilde.</p>
<p>Indeed, a url like this:</p>
<pre><code>https://mywordpresssite.com/my-permalink
</code></pre>
<p>Is also accessible with the following URLS:</p>
<pre><code>https://mywordpresssite.com/my-permalink~
https://mywordpresssite.com/my-permalink~/
https://mywordpresssite.com/my-permalink~~~~~~
</code></pre>
<p>I poked around a little bit to see where WP parses the permalinks, and I tracked it down to <code>class-wp.php</code> in the <code>parse_request</code> method, but couldn't get much further than that.</p>
<p>My question is if this is intended behaviour for WP, and if so, is there any way I can switch this off so tildes are not matched? Why would WP interpret URLs with tildes as a URL without them?</p>
<p>(1) <em>Yep, now we've all seen a couple of major hacks and data leaks in the UK, it's that time again where the "security" guys all pretend they're doing their bit by handing us developers 200-page scan reports full of false-positives and generic issues they don't know anything about in the expectation if we read and act on said report, nothing bad will ever happen.</em></p>
|
[
{
"answer_id": 222004,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<p>Yes it seems strange that we should have the same match for: </p>\n\n<pre><code>example.tld/2016/03/29/test/\n</code></pre>\n\n<p>and e.g.</p>\n\n<pre><code>example.tld/2016/03/29/..!!$$~~test~~!!$$../\n</code></pre>\n\n<p>Why this is possible, seems to be <a href=\"https://github.com/WordPress/WordPress/blob/0e53ff669279c585e01d8ac8fbb49e80526b513e/wp-includes/query.php#L2701-L2703\" rel=\"nofollow\">this part</a> of the <code>WP_Query::get_posts()</code> method:</p>\n\n<pre><code>if ( '' != $q['name'] ) {\n $q['name'] = sanitize_title_for_query( $q['name'] );\n</code></pre>\n\n<p>where <code>sanitize_title_for_query()</code> is defined as:</p>\n\n<pre><code>function sanitize_title_for_query( $title ) {\n return sanitize_title( $title, '', 'query' );\n}\n</code></pre>\n\n<p>It should be possible to make this stricter with the <code>sanitize_title</code> filter, but it might not be a good idea to override the default output, based on <code>sanitize_title_with_dashes</code>, that is responsible for the sanitation here. You should consider creating a ticket instead of changing it, if there are no current once already about this behavior. </p>\n\n<h2>Update</h2>\n\n<p>I wonder if we could clean up the noise from the current the path with <code>sanitize_title_for_query()</code> and redirect to the cleaned url if necessary?</p>\n\n<p>Here's a demo that you could play with on your test site and adjust to your needs:</p>\n\n<pre><code>/**\n * DEMO: Remove noise from url and redirect to the cleaned version if needed \n */\nadd_action( 'init', function( )\n{\n // Only for the front-end\n if( is_admin() )\n return;\n\n // Get current url\n $url = home_url( add_query_arg( [] ) );\n\n // Let's clean the current path with sanitize_title_for_query()\n $parse = parse_url( $url );\n $parts = explode( '/', $parse['path'] );\n $parts = array_map( 'sanitize_title_for_query', $parts ); \n $path_clean = join( '/', $parts );\n $url_clean = home_url( $path_clean );\n if( ! empty( $parse['query'] ) )\n $url_clean .= '?' . $parse['query'];\n\n // Only redirect if the current url is noisy\n if( $url === $url_clean )\n return;\n wp_safe_redirect( esc_url_raw( $url_clean ) );\n exit;\n} );\n</code></pre>\n\n<p>It might even be better to use <code>sanitize_title_with_dashes()</code> directly to avoid the filters and replace:</p>\n\n<pre><code>$parts = array_map( 'sanitize_title_for_query', $parts );\n</code></pre>\n\n<p>with:</p>\n\n<pre><code>foreach( $parts as &$part )\n{\n $part = sanitize_title_with_dashes( $part, '', 'query' );\n}\n</code></pre>\n\n<p>ps: I think I learned this trick, to get the current path with an empty <code>add_query_arg( [] )</code>, from @gmazzap ;-) This is also <a href=\"https://developer.wordpress.org/reference/functions/add_query_arg/\" rel=\"nofollow\">noted</a> in the Codex. Thanks again to @gmazzap for the reminder of using <code>esc_url()</code> when displaying the output of <code>add_query_arg( [] )</code> or <code>esc_url_raw()</code> when e.g. redirecting it. Check the previous Codex reference for that too.</p>\n"
},
{
"answer_id": 222006,
"author": "engelen",
"author_id": 40403,
"author_profile": "https://wordpress.stackexchange.com/users/40403",
"pm_score": 2,
"selected": false,
"text": "<p>Let me explain WordPress' processing of a request, and a method to change WordPress' behaviour to accomplish your goals accordingly.</p>\n\n<h3>Parsing the request</h3>\n\n<p>When WordPress receives a request, it starts a process of dissecting the request and transforming it into a page. The core of this process begins when WordPress main query method <code>WP::main()</code> is called. This function parses the query, as you correctly identified, in <code>parse_request()</code> (in <code>includes/class-wp.php</code>). There, WordPress tries to match the URL against one of the <a href=\"https://codex.wordpress.org/Rewrite_API\" rel=\"nofollow noreferrer\">rewrite rules</a>. When the URL is matched, it creates a query string of the URL parts and encodes these parts (everything between two slashes) using <a href=\"http://php.net/manual/en/function.urlencode.php\" rel=\"nofollow noreferrer\"><code>urlencode()</code></a>, to prevent special characters such as <code>&</code> from messing up the query string. These encoded characters might have caused you to think that the problem resided there, but they're actually turned into their corresponding \"real\" characters when parsing the query string.</p>\n\n<h3>Running the query associated with the request</h3>\n\n<p>After WordPress has parsed the URL, it sets up the main query class, <code>WP_Query</code>, which is done in the same <code>main()</code> method of the <code>WP</code> class. The beef of <code>WP_Query</code> can be found in its <code>get_posts()</code> method where all query arguments are parsed and sanitized and the actual SQL query is constructed (and, eventually, run).</p>\n\n<p>In this method, on line 2730, the following code is executed:</p>\n\n<pre><code>$q['name'] = sanitize_title_for_query( $q['name'] );\n</code></pre>\n\n<p>This sanitizes the post for fetching it from the posts table. Outputting debug info inside the loop shows that this is where the problem resides: your post name, <code>my-permalink~</code>, is transformed to <code>my-permalink</code>, which is then used to fetch the post from the database.</p>\n\n<h3>The post title sanitization function</h3>\n\n<p>The function <code>sanitize_title_for_query</code> calls <code>sanitize_title</code> with the proper parameters, which proceeds to sanitize the title. Now the core of this function is applying the <code>sanitize_title</code> filter:</p>\n\n<pre><code>$title = apply_filters( 'sanitize_title', $title, $raw_title, $context );\n</code></pre>\n\n<p>This filter has, in native WordPress, a single function attached to it: <code>sanitize_title_with_dashes</code>. I've written an extensive overview of what this function does, <a href=\"https://wordpress.stackexchange.com/questions/149191/slug-formatting-acceptable-characters/149192#149192\">which can be found here</a>. <strong>In this function, the line that's causing your problem is</strong></p>\n\n<pre><code>$title = preg_replace('/[^%a-z0-9 _-]/', '', $title);\n</code></pre>\n\n<p>This line strips all characters except for alphanumerical characters, spaces, hyphens and underscores.</p>\n\n<h3>Solving your problem</h3>\n\n<p>So, there is basically a single way to solve your problem: removing the <code>sanitize_title_with_dashes</code> function from the filter and replacing it with your own function. This is actually not that difficult to do, <strong>but</strong>:</p>\n\n<ol>\n<li>When WordPress changes the internal process of sanitizing titles, this will have major effects on your website.</li>\n<li>Other plugins hooking into this filter might not correctly handle the new functionality.</li>\n<li><p><strong>Most importantly</strong>: WordPress uses the result of the <code>sanitize_title</code> function <strong>directly</strong> in the SQL query by this line:</p>\n\n<pre><code>$where .= \" AND $wpdb->posts.post_name = '\" . $q['name'] . \"'\";\n</code></pre>\n\n<p>Should you ever consider changing the filter, be sure that you properly escape the title before it is used in the query!</p></li>\n</ol>\n\n<p>Conclusion: solving your problem is not necessary as far as security is concerned, but should you want to do it, replace the <code>sanitize_title_with_dashes</code> with your own functionality and pay attention to SQL escaping.</p>\n\n<p><em>NB all file names and line numbers correspond with WordPress 4.4.2 files.</em></p>\n"
},
{
"answer_id": 222007,
"author": "Huginn",
"author_id": 70043,
"author_profile": "https://wordpress.stackexchange.com/users/70043",
"pm_score": -1,
"selected": false,
"text": "<p>You can always try adding adding the following to your <code>.htaccess</code> file:</p>\n\n<pre><code>RewriteEngine On\nRewriteRule \\.php~$ – [forbidden,last]\n</code></pre>\n\n<p>The second line above should go right under the first line shown. It should prevent <code>index.php~</code> from displaying in URLs. </p>\n"
},
{
"answer_id": 222052,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": false,
"text": "<blockquote>\n <p>is intended behaviour for WP</p>\n</blockquote>\n\n<p>Yes, as already explained, <a href=\"https://developer.wordpress.org/reference/classes/wp_query/get_posts/\" rel=\"noreferrer\"><code>WP_Query::get_posts()</code></a> uses <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title_for_query/\" rel=\"noreferrer\"><code>sanitize_title_for_query()</code></a> (<em>which uses <a href=\"https://developer.wordpress.org/reference/functions/sanitize_title/\" rel=\"noreferrer\"><code>sanitize_title()</code></a></em>) to sanitize the post name of a singular post. </p>\n\n<p>In short, after the post name passed through <code>sanitize_title_for_query()</code>, <code>my-permalink === my-permalink~~~</code> as <code>sanitize_title_for_query()</code> removes the trailing <code>~~~</code>. You can test this by doing the following:</p>\n\n<pre><code>echo sanitize_title_for_query( 'my-permalink~~~' )\n</code></pre>\n\n<blockquote>\n <p>is there any way I can switch this off so tildes are not matched</p>\n</blockquote>\n\n<p>This is not something you can switch off. There is a filter in <code>sanitize_title()</code> called <a href=\"https://developer.wordpress.org/reference/hooks/sanitize_title/\" rel=\"noreferrer\"><code>sanitize_title</code></a> which you can use to alter the behavior of <code>sanitize_title()</code>, but that is almost always not a very good idea. SQL injection is very serious, so letting something slip through the cracks due to bad sanitation can have really bad influence on the integrity of your site. \"Over sanitation\" can sometimes be a pain in the butt.</p>\n\n<p>I'm not sure what you are after, but I suspect that you maybe want to 404 single posts with these trailing tilde, in your words, \"switch it off\". The only way I can think of at this stage is to halt the main query when we have these trailing tildes. For this, we can filter the <code>posts_where</code> clause of the main query. </p>\n\n<h2>THE FILTER</h2>\n\n<p>Note: I only considered normal singular posts, and not static front pages or attachments, you can extend the filter to incorporate this</p>\n\n<pre><code>add_filter( 'posts_where', function ( $where, \\WP_Query $q )\n{\n // Only apply the filter on the main query\n if ( !$q->is_main_query() )\n return $where;\n\n // Only apply the filter on singular posts\n if ( !$q->is_singular() )\n return $where;\n\n // We are on a singular page, lets get the singular post name\n $name = sanitize_title_for_query( $q->query_vars['name'] );\n\n // Suppose $name is empty, like on ugly permalinks, lets bail and let WorPress handle it from here\n if ( !$name )\n return $where;\n\n // Get the single post URL\n $single_post_url = home_url( add_query_arg( [] ) );\n $parsed_url = parse_url( $single_post_url );\n\n // Explode the url and return the page name from the path\n $exploded_pieces = explode( '/', $parsed_url['path'] );\n $exploded_pieces = array_reverse( $exploded_pieces );\n\n // Loop through the pieces and return the part holding the pagename\n $raw_name = '';\n foreach ( $exploded_pieces as $piece ) {\n if ( false !== strpos( $piece, $name ) ) {\n $raw_name = $piece;\n\n break;\n }\n }\n\n // If $raw_name is empty, we have a serious stuff-up, lets bail and let WordPress handle this mess\n if ( !$raw_name )\n return $where;\n\n /**\n * All we need to do now is to match $name against $raw_name. If these two don't match,\n * we most probably have some extra crap in the post name/URL. We need to 404, even if the\n * the sanitized version of $raw_name would match $name. \n */\n if ( $raw_name === $name )\n return $where;\n\n // $raw_name !== $name, lets halt the main query and 404\n $where .= \" AND 0=1 \";\n\n // Remove the redirect_canonical action so we do not get redirected to the correct URL due to the 404\n remove_action( 'template_redirect', 'redirect_canonical' );\n\n return $where;\n}, 10, 2 );\n</code></pre>\n\n<h2>FEW NOTES</h2>\n\n<p>The above filter will return a 404 page when we have a URL like <code>https://mywordpresssite.com/my-permalink~~~~~~</code>. You can however, by removing <code>remove_action( 'template_redirect', 'redirect_canonical' );</code> from the filter, have the query automatically redirect to <code>https://mywordpresssite.com/my-permalink</code> and display the single post due to <code>redirect_canonical()</code> which is hooked to <code>template_redirect</code> which handles redirection of WordPress generated 404's</p>\n"
},
{
"answer_id": 222147,
"author": "gmazzap",
"author_id": 35541,
"author_profile": "https://wordpress.stackexchange.com/users/35541",
"pm_score": 4,
"selected": false,
"text": "<h1>Let's go simple</h1>\n\n<p>If I understand OP well, your problem is that urls containing a tilde are matched at all.</p>\n\n<p>All other answers focus on the fact that sanitization for query strips out some characters before perform the query, however one should be capable to prevent a rewrite rule to don't match under some circumstances.</p>\n\n<p>And it is doable, not very easy, but doable.</p>\n\n<h1>Why it matches, in first place?</h1>\n\n<p>The reason why two urls like <code>example.com/postname</code> and <code>example.com/postname~</code> match the same rewrite rule is because WP rewrite rule for posts use the rewrite tag <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-rewrite.php#L311\" rel=\"nofollow\"><code>%postname%</code></a> that is replaced by the regex <a href=\"https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-rewrite.php#L333\" rel=\"nofollow\"><code>([^/]+)</code></a> when rewrite rules are created.</p>\n\n<p>Problem is that regex <code>([^/]+)</code> also matches the postname <code>postname~</code> and, because of sanitization, the name queried will be <code>postname</code> ending up in a valid result.</p>\n\n<p>It means that if we are able to change the regex from <code>([^/]+)</code> to <code>([^~/]+)</code> tilde will not match anymore so we actively prevent urls containing tilde in post name to be matched. </p>\n\n<p>Since no rule will match, the url will end up to be a 404, which should be the expected behavior, I think.</p>\n\n<h1>Prevent matching</h1>\n\n<p><a href=\"https://codex.wordpress.org/Rewrite_API/add_rewrite_tag\" rel=\"nofollow\"><code>add_rewrite_tag</code></a> is a function that, despite its name, can be used to update an existing rewrite tag like <code>%postname%</code>.</p>\n\n<p>So, if we use the code:</p>\n\n<pre><code>add_action('init', function() {\n add_rewrite_tag( '%postname%', '([^~/]+)', 'name=' );\n});\n</code></pre>\n\n<p>we will reach our target and <code>example.com/postname~</code> will <strong>not</strong> match the rule for <code>example.com/postname</code>.</p>\n\n<p>So, yes, <strong>the 3 lines above is the only code you'll need</strong>.</p>\n\n<p>However, before it works, you'll need to flush rewrite rules by visiting permalink settings page on backend.</p>\n\n<p>Note that regex <code>([^~/]+)</code> prevent a tilde to be anywhere in post name, not only as trailing character, but since post names can't actually contain tilde because of sanitization, that should be not a problem.</p>\n"
},
{
"answer_id": 222447,
"author": "kovshenin",
"author_id": 1316,
"author_profile": "https://wordpress.stackexchange.com/users/1316",
"pm_score": 2,
"selected": false,
"text": "<p>Some folks have already explained the problem, so I'll just post an alternative solution. Should be pretty self-explanatory.</p>\n\n<pre><code>add_action( 'template_redirect', function() {\n global $wp;\n\n if ( ! is_singular() || empty( $wp->query_vars['name'] ) )\n return;\n\n if ( $wp->query_vars['name'] != get_query_var( 'name' ) ) {\n die( wp_redirect( get_permalink(), 301 ) );\n // or 404, or 403, or whatever you want.\n }\n});\n</code></pre>\n\n<p>You will have to do something a bit different for hierarchical post types though, since <code>WP_Query</code> will run <code>pagename</code> through <code>wp_basename</code> and then sanitize it, so <code>query_vars['pagename']</code> and <code>get_query_var('pagename')</code> won't match for children becuase the latter will not contain the parent part.</p>\n\n<p>I wish <code>redirect_canonical</code> just took care of this crap.</p>\n"
},
{
"answer_id": 296210,
"author": "Michael S. Howard",
"author_id": 136490,
"author_profile": "https://wordpress.stackexchange.com/users/136490",
"pm_score": 0,
"selected": false,
"text": "<p>THIS IS THE FIX... FOR WORDPRESS's BUG JUST ADD THE BEGIN security mod block above the Wordpress Generated BLOCK.</p>\n\n<pre><code># BEGIN security mod\n<IfModule mod_rewrite.c>\nRewriteRule ^.*[~]+.*$ - [R=404]\n</IfModule>\n#END security mod\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /wordpress/\nRewriteRule ^index\\.php$ - [L]\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule . /wordpress/index.php [L]\n</IfModule>\n\n# END WordPress\n</code></pre>\n"
}
] |
2015/11/15
|
[
"https://wordpress.stackexchange.com/questions/208733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/22457/"
] |
I've been handed a vulnerability report(1) that seems to be implying that there may be a security issue in the way Wordpress handles URLs with following tildes. It seems the scanner thinks the website may be serving up some directory listings and the such.
I was surprised that my website was still serving content on those different URLs, so I did a test by installing a totally blank WP instance, switched to "Post name" permalinks, and confirmed that yep, any URL with added tilde still gets interpreted as the URL without the tilde.
Indeed, a url like this:
```
https://mywordpresssite.com/my-permalink
```
Is also accessible with the following URLS:
```
https://mywordpresssite.com/my-permalink~
https://mywordpresssite.com/my-permalink~/
https://mywordpresssite.com/my-permalink~~~~~~
```
I poked around a little bit to see where WP parses the permalinks, and I tracked it down to `class-wp.php` in the `parse_request` method, but couldn't get much further than that.
My question is if this is intended behaviour for WP, and if so, is there any way I can switch this off so tildes are not matched? Why would WP interpret URLs with tildes as a URL without them?
(1) *Yep, now we've all seen a couple of major hacks and data leaks in the UK, it's that time again where the "security" guys all pretend they're doing their bit by handing us developers 200-page scan reports full of false-positives and generic issues they don't know anything about in the expectation if we read and act on said report, nothing bad will ever happen.*
|
Let's go simple
===============
If I understand OP well, your problem is that urls containing a tilde are matched at all.
All other answers focus on the fact that sanitization for query strips out some characters before perform the query, however one should be capable to prevent a rewrite rule to don't match under some circumstances.
And it is doable, not very easy, but doable.
Why it matches, in first place?
===============================
The reason why two urls like `example.com/postname` and `example.com/postname~` match the same rewrite rule is because WP rewrite rule for posts use the rewrite tag [`%postname%`](https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-rewrite.php#L311) that is replaced by the regex [`([^/]+)`](https://github.com/WordPress/WordPress/blob/master/wp-includes/class-wp-rewrite.php#L333) when rewrite rules are created.
Problem is that regex `([^/]+)` also matches the postname `postname~` and, because of sanitization, the name queried will be `postname` ending up in a valid result.
It means that if we are able to change the regex from `([^/]+)` to `([^~/]+)` tilde will not match anymore so we actively prevent urls containing tilde in post name to be matched.
Since no rule will match, the url will end up to be a 404, which should be the expected behavior, I think.
Prevent matching
================
[`add_rewrite_tag`](https://codex.wordpress.org/Rewrite_API/add_rewrite_tag) is a function that, despite its name, can be used to update an existing rewrite tag like `%postname%`.
So, if we use the code:
```
add_action('init', function() {
add_rewrite_tag( '%postname%', '([^~/]+)', 'name=' );
});
```
we will reach our target and `example.com/postname~` will **not** match the rule for `example.com/postname`.
So, yes, **the 3 lines above is the only code you'll need**.
However, before it works, you'll need to flush rewrite rules by visiting permalink settings page on backend.
Note that regex `([^~/]+)` prevent a tilde to be anywhere in post name, not only as trailing character, but since post names can't actually contain tilde because of sanitization, that should be not a problem.
|
208,740 |
<p>I am trying to get the json data of my posts. I have tried with both v1.2.4 and v2 of the REST API plugin.</p>
<p>If I enter</p>
<pre><code>http://example.com/wp-json/posts?type=magazine
</code></pre>
<p>or</p>
<pre><code>http://example.com/wp-json/posts?type=magazine&filter[posts_per_page]=-1
</code></pre>
<p>just an empty array is returned.</p>
<p>If I enter</p>
<pre><code>http://example.com/wp-json/posts?type=magazine&filter[posts_per_page]=80
</code></pre>
<p>(or any number between 1 and 80)</p>
<p>all data appear just fine.</p>
<p>Is there a limit? I need to get ALL the posts from any custom post type.</p>
|
[
{
"answer_id": 245792,
"author": "Edukondalu Thaviti",
"author_id": 104441,
"author_profile": "https://wordpress.stackexchange.com/users/104441",
"pm_score": 1,
"selected": false,
"text": "<p>Try this instead for pagination. It returns all the posts on my site.</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/posts/?filter[category_name]=country&filter[posts_per_page]=-1\n</code></pre>\n"
},
{
"answer_id": 411605,
"author": "djack109",
"author_id": 188000,
"author_profile": "https://wordpress.stackexchange.com/users/188000",
"pm_score": 0,
"selected": false,
"text": "<p>This article has the right answer</p>\n<p><a href=\"https://wordpress.stackexchange.com/questions/267361/how-to-pull-all-posts-categories-or-tags-in-wordpress-rest-api?rq=1\">How to Pull ALL Posts, Categories, or Tags in WordPress REST API</a></p>\n<p>Turns our the query parameter is <code>/wp-json/wp/v2/products/?per_page=xx</code></p>\n<p>Where xx is the number of posts you want.</p>\n<p>I only needed to get twenty so not sure if there is any upper limit</p>\n"
}
] |
2015/11/15
|
[
"https://wordpress.stackexchange.com/questions/208740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/74398/"
] |
I am trying to get the json data of my posts. I have tried with both v1.2.4 and v2 of the REST API plugin.
If I enter
```
http://example.com/wp-json/posts?type=magazine
```
or
```
http://example.com/wp-json/posts?type=magazine&filter[posts_per_page]=-1
```
just an empty array is returned.
If I enter
```
http://example.com/wp-json/posts?type=magazine&filter[posts_per_page]=80
```
(or any number between 1 and 80)
all data appear just fine.
Is there a limit? I need to get ALL the posts from any custom post type.
|
Try this instead for pagination. It returns all the posts on my site.
```
http://example.com/wp-json/wp/v2/posts/?filter[category_name]=country&filter[posts_per_page]=-1
```
|
208,756 |
<p>Filter</p>
<pre><code> add_filter( 'the_content', 'sandy_posts_filter' );
function sandy_posts_filter( $content )
{
global $post;
$review_box_pos =get_post_meta( $post->ID, 'repeatable_fields', true );
if (is_array($review_box_pos)) {
foreach ($review_box_pos as $key => $val) {
switch ($val[nameooz]) {
case 'top':
$content = sandy_reviews() . $content;
break;
case 'bottom':
//$content .= "Extra Content" ; Work at footer Perfect//
$content .= sandy_reviews() ; //shown at top only !!!
break;
} //End Switch
}
}
return $content ;
}
</code></pre>
<p>Function</p>
<pre><code> //////////////////// Reviews Box ///////////////////////
function sandy_reviews() {
$get_meta = get_post_custom($current_ID);
$reviews = (get_post_meta(get_the_ID(), 'repeatable_fields', true));
$sumArray = array();
if (is_array($reviews))
foreach($reviews as $k => $val) {
foreach($val as $id => $value) {
$sumArray[$id] += $value;
}
}
$Reviwes_count = count($reviews);
$Total_Reviwes = round(($sumArray[range] / $Reviwes_count), 1);
if (!empty($reviews)) { ?>
<div class = "reviews-box" >
<div class = "reviews-box-title" >
<?php
$get_meta = get_post_custom($current_ID);
if (!empty($reviews))
foreach($reviews as $val) {
echo $val["nameoo"];
} ?>
</div>
<?php
//Get Round Number
if (!empty($reviews))
foreach($reviews as $key => $val) {
if (!empty($val[range]))
$reviews_title = $val[nameoo];
$ranges = $val[range];
$range1 = ($val[range] * 0.01) * (5);
$range2 = floor(($range1 * 2) / 2);
$Reviwes = ($range1 * 20);
?>
<div class = "reviews-box-row" >
<div class = "reviews-box-keywords" > <?php echo $val[name]; ?> </div> <div class = "reviews-box-ranges" >
<span style = "display: block;float:left; width: 65px; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 0;" >
<span style = "display: block;float:left; width: <?php echo $ranges.'%';?>; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 -13px;" > </span> </span> <?php
echo "</div></div>";}
?>
<div class = "reviews-box-percent" > Summary </div>
<!-- <div class="reviews-box-ranges"><?php //echo ($val[range]*0.01)*(5);?></div> -->
<div class = "reviews-box-ranges-percent" >
<div class = "Total_Reviwes" > <?php echo $Total_Reviwes.""; ?> </div>
<span style = "display: inline-block; margin:0 auto;width: 65px; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 0;" >
<span style = "display: block; margin:0 auto;float:left;width: <?php echo $Total_Reviwes.'%';?>; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 -13px;" > </span> </span>
<?php
echo "</div>";
echo "</div>";
}
}
//////////////////// Reviews Box END///////////////////////
</code></pre>
<p>1- Why this function not shown at bottom of content ?</p>
<p>2- Why when we used this filter at top of content it's show review box at </p>
<p>summary of content at category page !!</p>
|
[
{
"answer_id": 245792,
"author": "Edukondalu Thaviti",
"author_id": 104441,
"author_profile": "https://wordpress.stackexchange.com/users/104441",
"pm_score": 1,
"selected": false,
"text": "<p>Try this instead for pagination. It returns all the posts on my site.</p>\n\n<pre><code>http://example.com/wp-json/wp/v2/posts/?filter[category_name]=country&filter[posts_per_page]=-1\n</code></pre>\n"
},
{
"answer_id": 411605,
"author": "djack109",
"author_id": 188000,
"author_profile": "https://wordpress.stackexchange.com/users/188000",
"pm_score": 0,
"selected": false,
"text": "<p>This article has the right answer</p>\n<p><a href=\"https://wordpress.stackexchange.com/questions/267361/how-to-pull-all-posts-categories-or-tags-in-wordpress-rest-api?rq=1\">How to Pull ALL Posts, Categories, or Tags in WordPress REST API</a></p>\n<p>Turns our the query parameter is <code>/wp-json/wp/v2/products/?per_page=xx</code></p>\n<p>Where xx is the number of posts you want.</p>\n<p>I only needed to get twenty so not sure if there is any upper limit</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208756",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/82877/"
] |
Filter
```
add_filter( 'the_content', 'sandy_posts_filter' );
function sandy_posts_filter( $content )
{
global $post;
$review_box_pos =get_post_meta( $post->ID, 'repeatable_fields', true );
if (is_array($review_box_pos)) {
foreach ($review_box_pos as $key => $val) {
switch ($val[nameooz]) {
case 'top':
$content = sandy_reviews() . $content;
break;
case 'bottom':
//$content .= "Extra Content" ; Work at footer Perfect//
$content .= sandy_reviews() ; //shown at top only !!!
break;
} //End Switch
}
}
return $content ;
}
```
Function
```
//////////////////// Reviews Box ///////////////////////
function sandy_reviews() {
$get_meta = get_post_custom($current_ID);
$reviews = (get_post_meta(get_the_ID(), 'repeatable_fields', true));
$sumArray = array();
if (is_array($reviews))
foreach($reviews as $k => $val) {
foreach($val as $id => $value) {
$sumArray[$id] += $value;
}
}
$Reviwes_count = count($reviews);
$Total_Reviwes = round(($sumArray[range] / $Reviwes_count), 1);
if (!empty($reviews)) { ?>
<div class = "reviews-box" >
<div class = "reviews-box-title" >
<?php
$get_meta = get_post_custom($current_ID);
if (!empty($reviews))
foreach($reviews as $val) {
echo $val["nameoo"];
} ?>
</div>
<?php
//Get Round Number
if (!empty($reviews))
foreach($reviews as $key => $val) {
if (!empty($val[range]))
$reviews_title = $val[nameoo];
$ranges = $val[range];
$range1 = ($val[range] * 0.01) * (5);
$range2 = floor(($range1 * 2) / 2);
$Reviwes = ($range1 * 20);
?>
<div class = "reviews-box-row" >
<div class = "reviews-box-keywords" > <?php echo $val[name]; ?> </div> <div class = "reviews-box-ranges" >
<span style = "display: block;float:left; width: 65px; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 0;" >
<span style = "display: block;float:left; width: <?php echo $ranges.'%';?>; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 -13px;" > </span> </span> <?php
echo "</div></div>";}
?>
<div class = "reviews-box-percent" > Summary </div>
<!-- <div class="reviews-box-ranges"><?php //echo ($val[range]*0.01)*(5);?></div> -->
<div class = "reviews-box-ranges-percent" >
<div class = "Total_Reviwes" > <?php echo $Total_Reviwes.""; ?> </div>
<span style = "display: inline-block; margin:0 auto;width: 65px; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 0;" >
<span style = "display: block; margin:0 auto;float:left;width: <?php echo $Total_Reviwes.'%';?>; height: 13px; background: url( <?php echo get_template_directory_uri();?>/images/star-rating-sprite.png) 0 -13px;" > </span> </span>
<?php
echo "</div>";
echo "</div>";
}
}
//////////////////// Reviews Box END///////////////////////
```
1- Why this function not shown at bottom of content ?
2- Why when we used this filter at top of content it's show review box at
summary of content at category page !!
|
Try this instead for pagination. It returns all the posts on my site.
```
http://example.com/wp-json/wp/v2/posts/?filter[category_name]=country&filter[posts_per_page]=-1
```
|
208,760 |
<p>I want to totally disable this functionality from WordPress because I'm implementing my own version of this with Javascript.</p>
<p>When I try to grab all the content in a post via the <code>get_the_content()</code> or <code>the_content()</code> it gives me only the first page, since the content has the page breaks. When I use <code>$post->the_content</code> I get the full post but it's not formatted with HTML tags. I don't want to have to add those myself programatically. </p>
<p>So I either need to get all the content already formatted - the way to do this is unknown to me at the moment
or disable <code>wp_page_links()</code> so it doesn't paginate my posts. </p>
|
[
{
"answer_id": 208762,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 4,
"selected": true,
"text": "<p><strong>EDIT -</strong> Now that 4.4 is out, you should use the <code>content_pagination</code> filter. See birgire's answer below.</p>\n\n<hr>\n\n<p>You can add formatting to raw post content by <a href=\"https://codex.wordpress.org/Function_Reference/apply_filters\" rel=\"nofollow\">applying</a> the <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content\" rel=\"nofollow\">content filters</a> directly to <code>$post->post_content</code>:</p>\n\n<pre><code>echo apply_filters( 'the_content', $post->post_content );\n</code></pre>\n\n<p>This will bypass pagination by not using the <code>get_the_content</code> function, which is what <code>the_content</code> uses internally to retrieve the current page's content for multipage posts.</p>\n\n<p>You can prevent <code>wp_link_pages</code> from outputting anything by applying a filter to its output before the function is called and using the <a href=\"https://codex.wordpress.org/Function_Reference/_return_empty_string\" rel=\"nofollow\"><code>__return_empty_string</code></a> helper function:</p>\n\n<pre><code>add_filter( 'wp_link_pages', '__return_empty_string' );\n</code></pre>\n"
},
{
"answer_id": 208767,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>You can kill the \"link pages\" functionality in one filter by stripping the <code>nextpage</code> markers out of the post content:</p>\n\n<pre><code>function kill_pages($posts,$qry) {\n if ($qry->is_single()) {\n $posts[0]->post_content = preg_replace( '/<!--nextpage(.*?)?-->/', '', $posts[0]->post_content );\n }\n return $posts;\n}\nadd_filter('the_posts','kill_pages',1,2);\n</code></pre>\n"
},
{
"answer_id": 208784,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": false,
"text": "<h2>New content pagination filter in WordPress 4.4</h2>\n\n<p>As of WordPress 4.4 we can use the <code>content_pagination</code> filter ( see ticket <a href=\"https://core.trac.wordpress.org/ticket/9911\" rel=\"noreferrer\">#9911</a> )</p>\n\n<pre><code>/**\n * Filter the \"pages\" derived from splitting the post content.\n *\n * \"Pages\" are determined by splitting the post content based on the presence\n * of `<!-- nextpage -->` tags.\n *\n * @since 4.4.0\n *\n * @param array $pages Array of \"pages\" derived from the post content.\n * of `<!-- nextpage -->` tags..\n * @param WP_Post $post Current post object.\n */\n $pages = apply_filters( 'content_pagination', $pages, $post );\n</code></pre>\n\n<p>This filter lives in the <code>setup_postdata()</code> method of the <code>WP_Query</code> class and will make it easier to modify the pagination pages.</p>\n\n<p>Here are few examples how to remove the content pagination (PHP 5.4+):</p>\n\n<h2>Example #1</h2>\n\n<p>Here's how we can disable the content pagination:</p>\n\n<pre><code>/**\n * Disable content pagination\n *\n * @link http://wordpress.stackexchange.com/a/208784/26350\n */\nadd_filter( 'content_pagination', function( $pages )\n{\n $pages = [ join( '', $pages ) ];\n return $pages;\n} );\n</code></pre>\n\n<h2>Example #2</h2>\n\n<p>If we want to only target the <em>main query loop</em>:</p>\n\n<pre><code>/**\n * Disable content pagination in the main loop\n *\n * @link http://wordpress.stackexchange.com/a/208784/26350\n */\nadd_filter( 'content_pagination', function( $pages )\n{\n if ( in_the_loop() )\n $pages = [ join( '', $pages ) ];\n\n return $pages;\n} );\n</code></pre>\n\n<h2>Example #3</h2>\n\n<p>If we only want to target <code>post</code> post type in the main loop:</p>\n\n<pre><code>/**\n * Disable content pagination for post post type in the main loop\n *\n * @link http://wordpress.stackexchange.com/a/208784/26350\n */\nadd_filter( 'content_pagination', function( $pages, $post )\n{\n if ( in_the_loop() && 'post' === $post->post_type )\n $pages = [ join( '', $pages ) ];\n\n return $pages;\n}, 10, 2 );\n</code></pre>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/35549/"
] |
I want to totally disable this functionality from WordPress because I'm implementing my own version of this with Javascript.
When I try to grab all the content in a post via the `get_the_content()` or `the_content()` it gives me only the first page, since the content has the page breaks. When I use `$post->the_content` I get the full post but it's not formatted with HTML tags. I don't want to have to add those myself programatically.
So I either need to get all the content already formatted - the way to do this is unknown to me at the moment
or disable `wp_page_links()` so it doesn't paginate my posts.
|
**EDIT -** Now that 4.4 is out, you should use the `content_pagination` filter. See birgire's answer below.
---
You can add formatting to raw post content by [applying](https://codex.wordpress.org/Function_Reference/apply_filters) the [content filters](https://codex.wordpress.org/Plugin_API/Filter_Reference/the_content) directly to `$post->post_content`:
```
echo apply_filters( 'the_content', $post->post_content );
```
This will bypass pagination by not using the `get_the_content` function, which is what `the_content` uses internally to retrieve the current page's content for multipage posts.
You can prevent `wp_link_pages` from outputting anything by applying a filter to its output before the function is called and using the [`__return_empty_string`](https://codex.wordpress.org/Function_Reference/_return_empty_string) helper function:
```
add_filter( 'wp_link_pages', '__return_empty_string' );
```
|
208,761 |
<p>I'm moving my WordPress site to a new host, and in the process I want to make a one time change to the Permalinks. I want to rewrite the URLs from <code>/2015/11/sample-post/</code> to <code>/sample-post/</code> but how can I accomplish that?</p>
|
[
{
"answer_id": 208763,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 0,
"selected": false,
"text": "<p>Go-to <code>settings -> permalink</code>. and than add it like this: <code>%post_name%</code>.</p>\n"
},
{
"answer_id": 208766,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>The most efficient way to accomplish this would be to change the structure to <code>/%postname%/</code> and add a 301 redirect to your .htaccess file for the old structure:</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$3\n</code></pre>\n\n<p>Change <code>example.com</code> to your domain and add the redirect above the <code># BEGIN WordPress</code> directive so it won't be removed if WordPress updates the file.</p>\n\n<p>EDIT- redirect /yyyy/mm/dd/postname</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$4\n</code></pre>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208761",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83671/"
] |
I'm moving my WordPress site to a new host, and in the process I want to make a one time change to the Permalinks. I want to rewrite the URLs from `/2015/11/sample-post/` to `/sample-post/` but how can I accomplish that?
|
The most efficient way to accomplish this would be to change the structure to `/%postname%/` and add a 301 redirect to your .htaccess file for the old structure:
```
RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$3
```
Change `example.com` to your domain and add the redirect above the `# BEGIN WordPress` directive so it won't be removed if WordPress updates the file.
EDIT- redirect /yyyy/mm/dd/postname
```
RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$4
```
|
208,776 |
<p>I'm working on an application using WP as my CMS. I was successfully creating new posts and working with them in my app. </p>
<p>But I noticed when visitors went to the website they were being listed in the blog (in the loop). I don't want them to show up there so after doing some research I decided to change my post type from "post" to "page". Now the posts no longer show up on the blog page! </p>
<p>But now, I noticed, my "pages" are showing up as menu items across the top of the page. This is not what I want. </p>
<p>Is it OK to change the type to something else that WP isn't using? For example, can I change the type to "document" and everything be OK?</p>
|
[
{
"answer_id": 208763,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 0,
"selected": false,
"text": "<p>Go-to <code>settings -> permalink</code>. and than add it like this: <code>%post_name%</code>.</p>\n"
},
{
"answer_id": 208766,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 3,
"selected": true,
"text": "<p>The most efficient way to accomplish this would be to change the structure to <code>/%postname%/</code> and add a 301 redirect to your .htaccess file for the old structure:</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$3\n</code></pre>\n\n<p>Change <code>example.com</code> to your domain and add the redirect above the <code># BEGIN WordPress</code> directive so it won't be removed if WordPress updates the file.</p>\n\n<p>EDIT- redirect /yyyy/mm/dd/postname</p>\n\n<pre><code>RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$4\n</code></pre>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208776",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29247/"
] |
I'm working on an application using WP as my CMS. I was successfully creating new posts and working with them in my app.
But I noticed when visitors went to the website they were being listed in the blog (in the loop). I don't want them to show up there so after doing some research I decided to change my post type from "post" to "page". Now the posts no longer show up on the blog page!
But now, I noticed, my "pages" are showing up as menu items across the top of the page. This is not what I want.
Is it OK to change the type to something else that WP isn't using? For example, can I change the type to "document" and everything be OK?
|
The most efficient way to accomplish this would be to change the structure to `/%postname%/` and add a 301 redirect to your .htaccess file for the old structure:
```
RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$3
```
Change `example.com` to your domain and add the redirect above the `# BEGIN WordPress` directive so it won't be removed if WordPress updates the file.
EDIT- redirect /yyyy/mm/dd/postname
```
RedirectMatch 301 ^/([0-9]{4})/([0-9]{2})/([0-9]{2})/(?!page/)(.+)$ http://example.com/$4
```
|
208,792 |
<p>I've changed the default registering option by allowing people to sign up with their e-mail addresses. They also have an option to add their firstname, lastname but it's not required. </p>
<pre><code>// Allow email instead of nickname for login
add_filter('authenticate', function($user, $email, $password){
//Check for empty fields
if(empty($email) || empty ($password)){
//create new error object and add errors to it.
$error = new WP_Error();
if(empty($email)){ //No email
$error->add('empty_username', __('<strong>Viga</strong>: Unustasid sisestada e-posti aadressi'));
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email
$error->add('invalid_username', __('<strong>Viga</strong>: E-posti aadress on vale.'));
}
if(empty($password)){ //No password
$error->add('empty_password', __('<strong>Viga</strong>: Unustasid sisestada parooli'));
}
return $error;
}
//Check if user exists in WordPress database
$user = get_user_by('email', $email);
//bad email
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>Viga</strong>: E-posti aadress või parool ei ole õige.'));
return $error;
}
else{ //check password
if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>Viga</strong>: E-posti aadress või parool ei ole õige.'));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);
</code></pre>
<p>But this raises a problem. On the author page, users e-mail addresses become public: </p>
<pre><code>http://example.com/author/email-address/
</code></pre>
<p>I know how do change the /author/ part of the URL: </p>
<pre><code>add_action('init', 'cng_author_base');
function cng_author_base() {
global $wp_rewrite;
$author_slug = 'autor'; // change slug name
$wp_rewrite->author_base = $author_slug;
}
</code></pre>
<p>but not how do change the username to show the ID of the author.
Can it be done? </p>
|
[
{
"answer_id": 278147,
"author": "Crazycoolcam",
"author_id": 28144,
"author_profile": "https://wordpress.stackexchange.com/users/28144",
"pm_score": 2,
"selected": false,
"text": "<p>Surprised to see this unanswered for this long. This is pretty simple to do with a simple block of code:</p>\n\n<pre><code>function set_my_nice_name() {\n global $wpdb;\n $user_table = $wpdb->prefix . 'users';\n $wpdb->query(\"UPDATE $user_table SET `user_nicename`=`ID`\");\n}\nadd_action('init', 'set_my_nice_name');\n</code></pre>\n\n<p>This works because the visible portion of an author slug (or profile slug in BuddyPress) uses the <code>user_nicename</code> column in the users table and this just copies the user ID to that column for everyone in the DB.</p>\n"
},
{
"answer_id": 385761,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<p>Something to have in mind is that authors queries could become really predictable. Adding <code>+1</code> isn't that hard. Abuse from bots could arise, retrieving data through puppeteer for example.</p>\n<p>We could append to the user ID the <code>user_registered</code> by sanitizing it. We would get a nice random-ish string of numbers which would actively prevent bots and users from jumping through pages.</p>\n<p>We can catch the user ID upon registration then update <code>user_nicename</code> with the required value.</p>\n<pre><code>add_action( 'user_register', 'wpso208792' );\n\nfunction wpso208792( $user_id ) {\n\n $userdata = array (\n 'ID' => $user_id, \n 'user_nicename' => sanitize_title_with_dashes( $user_id . str_replace ( array( '-', ' ', ':', ), '', get_userdata( $user_id )->user_registered ) ),\n );\n\n wp_update_user( $userdata );\n\n};\n</code></pre>\n<p>If you're not interested in randomizing the user <code>user_nicename</code> just remove <code> . str_replace ( array( '-', ' ', ':', ), '', get_userdata( $user_id )->user_registered )</code> from the value.</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208792",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/34301/"
] |
I've changed the default registering option by allowing people to sign up with their e-mail addresses. They also have an option to add their firstname, lastname but it's not required.
```
// Allow email instead of nickname for login
add_filter('authenticate', function($user, $email, $password){
//Check for empty fields
if(empty($email) || empty ($password)){
//create new error object and add errors to it.
$error = new WP_Error();
if(empty($email)){ //No email
$error->add('empty_username', __('<strong>Viga</strong>: Unustasid sisestada e-posti aadressi'));
}
else if(!filter_var($email, FILTER_VALIDATE_EMAIL)){ //Invalid Email
$error->add('invalid_username', __('<strong>Viga</strong>: E-posti aadress on vale.'));
}
if(empty($password)){ //No password
$error->add('empty_password', __('<strong>Viga</strong>: Unustasid sisestada parooli'));
}
return $error;
}
//Check if user exists in WordPress database
$user = get_user_by('email', $email);
//bad email
if(!$user){
$error = new WP_Error();
$error->add('invalid', __('<strong>Viga</strong>: E-posti aadress või parool ei ole õige.'));
return $error;
}
else{ //check password
if(!wp_check_password($password, $user->user_pass, $user->ID)){ //bad password
$error = new WP_Error();
$error->add('invalid', __('<strong>Viga</strong>: E-posti aadress või parool ei ole õige.'));
return $error;
}else{
return $user; //passed
}
}
}, 20, 3);
```
But this raises a problem. On the author page, users e-mail addresses become public:
```
http://example.com/author/email-address/
```
I know how do change the /author/ part of the URL:
```
add_action('init', 'cng_author_base');
function cng_author_base() {
global $wp_rewrite;
$author_slug = 'autor'; // change slug name
$wp_rewrite->author_base = $author_slug;
}
```
but not how do change the username to show the ID of the author.
Can it be done?
|
Surprised to see this unanswered for this long. This is pretty simple to do with a simple block of code:
```
function set_my_nice_name() {
global $wpdb;
$user_table = $wpdb->prefix . 'users';
$wpdb->query("UPDATE $user_table SET `user_nicename`=`ID`");
}
add_action('init', 'set_my_nice_name');
```
This works because the visible portion of an author slug (or profile slug in BuddyPress) uses the `user_nicename` column in the users table and this just copies the user ID to that column for everyone in the DB.
|
208,799 |
<p>I'm developing an eCommerce site using Woo-Commerce, i'm hoping to introduce some JavaScript to my sale pages only, in the name of a finance slider. What is the best way to go about including a specific piece of JavaScript on my Woo-Commerce sale page only.</p>
<p>I'm new to WP so apologies if this is obvious, google didn't help though. Thanks</p>
|
[
{
"answer_id": 278147,
"author": "Crazycoolcam",
"author_id": 28144,
"author_profile": "https://wordpress.stackexchange.com/users/28144",
"pm_score": 2,
"selected": false,
"text": "<p>Surprised to see this unanswered for this long. This is pretty simple to do with a simple block of code:</p>\n\n<pre><code>function set_my_nice_name() {\n global $wpdb;\n $user_table = $wpdb->prefix . 'users';\n $wpdb->query(\"UPDATE $user_table SET `user_nicename`=`ID`\");\n}\nadd_action('init', 'set_my_nice_name');\n</code></pre>\n\n<p>This works because the visible portion of an author slug (or profile slug in BuddyPress) uses the <code>user_nicename</code> column in the users table and this just copies the user ID to that column for everyone in the DB.</p>\n"
},
{
"answer_id": 385761,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<p>Something to have in mind is that authors queries could become really predictable. Adding <code>+1</code> isn't that hard. Abuse from bots could arise, retrieving data through puppeteer for example.</p>\n<p>We could append to the user ID the <code>user_registered</code> by sanitizing it. We would get a nice random-ish string of numbers which would actively prevent bots and users from jumping through pages.</p>\n<p>We can catch the user ID upon registration then update <code>user_nicename</code> with the required value.</p>\n<pre><code>add_action( 'user_register', 'wpso208792' );\n\nfunction wpso208792( $user_id ) {\n\n $userdata = array (\n 'ID' => $user_id, \n 'user_nicename' => sanitize_title_with_dashes( $user_id . str_replace ( array( '-', ' ', ':', ), '', get_userdata( $user_id )->user_registered ) ),\n );\n\n wp_update_user( $userdata );\n\n};\n</code></pre>\n<p>If you're not interested in randomizing the user <code>user_nicename</code> just remove <code> . str_replace ( array( '-', ' ', ':', ), '', get_userdata( $user_id )->user_registered )</code> from the value.</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208799",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83395/"
] |
I'm developing an eCommerce site using Woo-Commerce, i'm hoping to introduce some JavaScript to my sale pages only, in the name of a finance slider. What is the best way to go about including a specific piece of JavaScript on my Woo-Commerce sale page only.
I'm new to WP so apologies if this is obvious, google didn't help though. Thanks
|
Surprised to see this unanswered for this long. This is pretty simple to do with a simple block of code:
```
function set_my_nice_name() {
global $wpdb;
$user_table = $wpdb->prefix . 'users';
$wpdb->query("UPDATE $user_table SET `user_nicename`=`ID`");
}
add_action('init', 'set_my_nice_name');
```
This works because the visible portion of an author slug (or profile slug in BuddyPress) uses the `user_nicename` column in the users table and this just copies the user ID to that column for everyone in the DB.
|
208,823 |
<p>I want to setup an Android and iOS App that calls my WP site via WebView. Somehow, i wasn't able to find the best way to do this via Google. First I was thinking about putting some Code in my functions.php that detects if I am a WebView App Visitor and then deliver another Theme. Then I thought about using the Multisite Function for this, but i believe this is not a good Idea since I am not really using two "different" Websites, for which this Function is, I just need different themes delivered.</p>
<p>So, what would the best Practice for this? Detect if the user is surfing with WebView and then change the Theme (which WP Function can do that?).</p>
<p>Note: I am trying to not use any Theme-Switcher Plugins for this since I want to keep the Plugin Bloat as small as possible.</p>
<p>Thanks!</p>
<p>UPDATE:
Since I think my Question was not well written...
The Website already is responsive for mobile users that visit the site with their regular mobile phone browser. My Goal is to to deliver a completely different theme for People that use a App that I am going to develop, since the App is going to work different than the regular website but still needs to grab the WP Posts - WebView App detection will be made via User Agent or similar.</p>
|
[
{
"answer_id": 278147,
"author": "Crazycoolcam",
"author_id": 28144,
"author_profile": "https://wordpress.stackexchange.com/users/28144",
"pm_score": 2,
"selected": false,
"text": "<p>Surprised to see this unanswered for this long. This is pretty simple to do with a simple block of code:</p>\n\n<pre><code>function set_my_nice_name() {\n global $wpdb;\n $user_table = $wpdb->prefix . 'users';\n $wpdb->query(\"UPDATE $user_table SET `user_nicename`=`ID`\");\n}\nadd_action('init', 'set_my_nice_name');\n</code></pre>\n\n<p>This works because the visible portion of an author slug (or profile slug in BuddyPress) uses the <code>user_nicename</code> column in the users table and this just copies the user ID to that column for everyone in the DB.</p>\n"
},
{
"answer_id": 385761,
"author": "amarinediary",
"author_id": 190376,
"author_profile": "https://wordpress.stackexchange.com/users/190376",
"pm_score": 0,
"selected": false,
"text": "<p>Something to have in mind is that authors queries could become really predictable. Adding <code>+1</code> isn't that hard. Abuse from bots could arise, retrieving data through puppeteer for example.</p>\n<p>We could append to the user ID the <code>user_registered</code> by sanitizing it. We would get a nice random-ish string of numbers which would actively prevent bots and users from jumping through pages.</p>\n<p>We can catch the user ID upon registration then update <code>user_nicename</code> with the required value.</p>\n<pre><code>add_action( 'user_register', 'wpso208792' );\n\nfunction wpso208792( $user_id ) {\n\n $userdata = array (\n 'ID' => $user_id, \n 'user_nicename' => sanitize_title_with_dashes( $user_id . str_replace ( array( '-', ' ', ':', ), '', get_userdata( $user_id )->user_registered ) ),\n );\n\n wp_update_user( $userdata );\n\n};\n</code></pre>\n<p>If you're not interested in randomizing the user <code>user_nicename</code> just remove <code> . str_replace ( array( '-', ' ', ':', ), '', get_userdata( $user_id )->user_registered )</code> from the value.</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208823",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/71313/"
] |
I want to setup an Android and iOS App that calls my WP site via WebView. Somehow, i wasn't able to find the best way to do this via Google. First I was thinking about putting some Code in my functions.php that detects if I am a WebView App Visitor and then deliver another Theme. Then I thought about using the Multisite Function for this, but i believe this is not a good Idea since I am not really using two "different" Websites, for which this Function is, I just need different themes delivered.
So, what would the best Practice for this? Detect if the user is surfing with WebView and then change the Theme (which WP Function can do that?).
Note: I am trying to not use any Theme-Switcher Plugins for this since I want to keep the Plugin Bloat as small as possible.
Thanks!
UPDATE:
Since I think my Question was not well written...
The Website already is responsive for mobile users that visit the site with their regular mobile phone browser. My Goal is to to deliver a completely different theme for People that use a App that I am going to develop, since the App is going to work different than the regular website but still needs to grab the WP Posts - WebView App detection will be made via User Agent or similar.
|
Surprised to see this unanswered for this long. This is pretty simple to do with a simple block of code:
```
function set_my_nice_name() {
global $wpdb;
$user_table = $wpdb->prefix . 'users';
$wpdb->query("UPDATE $user_table SET `user_nicename`=`ID`");
}
add_action('init', 'set_my_nice_name');
```
This works because the visible portion of an author slug (or profile slug in BuddyPress) uses the `user_nicename` column in the users table and this just copies the user ID to that column for everyone in the DB.
|
208,831 |
<p>I have written up a page template that will list posts in the same category as the name of the page. I am wondering how to alter it to get it to return the posts in alphabetical order?</p>
<p>I have been reading over and playing with how to change the template with the <a href="https://codex.wordpress.org/Alphabetizing_Posts" rel="nofollow noreferrer">Alphabetizing Posts Codex Page</a>. I just can't seem to get it to work. It would be greatly appreciated if someone demonstrated this for me once so I can see how it is done in this context.</p>
<p>The following is my code for the page template:</p>
<pre><code><?php /*
Template Name: Category Page
*/
get_header(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="content-container">
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
else: endif; ?>
<?php query_posts('category_name='.get_the_title().'&post_status=publish');?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h1>
<p><?php the_content(); ?>
<?php endwhile; else: endif; ?>
</div>
<?php /*If sidebar is not disabled in Customizer, get_sidebar*/
if ( get_theme_mod( 'ctheme_remove_sidebar' ) != 1 ) :
get_sidebar();
endif;
get_footer(); ?>
</code></pre>
<p>This is one way I'm thinking of doing it. If you have any other ideas how I should approach it, let me know!</p>
<p>The purpose of this page will be to retrieve a list of animal names, (no date for the post, no excerpt for the post, just the name of the animal) so alphabetical order would be the most useful.</p>
<p>Thanks!</p>
|
[
{
"answer_id": 208833,
"author": "pwbred",
"author_id": 6154,
"author_profile": "https://wordpress.stackexchange.com/users/6154",
"pm_score": 1,
"selected": false,
"text": "<p>You need to look closer at query_posts and order your posts by the title, as it says on the <a href=\"https://codex.wordpress.org/Alphabetizing_Posts#Main_Page\" rel=\"nofollow\">page that you linked to</a>.</p>\n\n<p>You need to change this:</p>\n\n<pre><code><?php query_posts('category_name='.get_the_title().'&post_status=publish');?>\n</code></pre>\n\n<p>and add this:</p>\n\n<pre><code><?php query_posts('category_name='.get_the_title().'&post_status=publish&orderby=title');?>\n</code></pre>\n\n<p>As someone else pointed out, you should really be using WP_Query in this situation. Take a look at the reference as many of the options are explained very clearly: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">Class Reference/WP Query</a></p>\n"
},
{
"answer_id": 208842,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>As I have stated, never ever use <code>query_posts</code>. The page you have linked to in the codex is worth nothing and completely wrong. For extra info on why not to use <code>query_posts</code>, check <a href=\"https://wordpress.stackexchange.com/a/191934/31545\">my answer here</a> and the answer by <a href=\"https://wordpress.stackexchange.com/a/1755/31545\">@Rarst</a>.</p>\n\n<p>You have another issue here, <code>category_name</code> does <strong>not</strong> accept the category name as value, but the <strong>slug</strong>. The naming convention of this parameter is wrong. <code>get_the_title()</code> returns the page name/title, not the slug. Your query might work if the page has a one word title without special characters as sanitizing the name in the <code>WP_Tax_Query</code> class might match it up the slug, but it will fail if the page name has special characters or have more than one word.</p>\n\n<p>What you need is to get the page slug, which you will pass as category slug to <code>category_name</code> To do this, you need to get the queried object and then return the <code>$post_name</code> property. Again, the naming convention is completely wrong. <code>$post_name</code> holds the slug of the page, not the name. </p>\n\n<p>In connection with ordering, you would need to set the <code>orderby</code> parameter to <code>title</code> and <code>order</code> to <code>ASC</code> to order from a-z and not the default <code>z-a</code></p>\n\n<p>All in all, your query would look something like this: (<strong><em>NOTE:</strong> Requires minimum PHP 5.4</em>)</p>\n\n<pre><code>$args = [\n 'category_name' => get_queried_object()->post_name,\n 'order' => 'ASC',\n 'orderby' => 'title' // Can use 'name' as well, see https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\n // Add any extra parameters you need\n];\n$q = new WP_Query( $args ); \n\n// Run the loop\nif ( $q->have_posts() ) {\n while ( $q->have_posts() ) {\n $q->the_post();\n\n // Display what you need from the loop like title, content etc\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>You can also try to use something like <a href=\"https://wordpress.stackexchange.com/a/162904/31545\">this</a> where you can have page where you choose which category to display when you publish a page, you can also select ordering and a few other features.</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208831",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83426/"
] |
I have written up a page template that will list posts in the same category as the name of the page. I am wondering how to alter it to get it to return the posts in alphabetical order?
I have been reading over and playing with how to change the template with the [Alphabetizing Posts Codex Page](https://codex.wordpress.org/Alphabetizing_Posts). I just can't seem to get it to work. It would be greatly appreciated if someone demonstrated this for me once so I can see how it is done in this context.
The following is my code for the page template:
```
<?php /*
Template Name: Category Page
*/
get_header(); ?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<div class="content-container">
<h1><?php the_title(); ?></h1>
<?php the_content(); ?>
<?php endwhile;
else: endif; ?>
<?php query_posts('category_name='.get_the_title().'&post_status=publish');?>
<?php if ( have_posts() ) : while ( have_posts() ) : the_post(); ?>
<h1><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a> </h1>
<p><?php the_content(); ?>
<?php endwhile; else: endif; ?>
</div>
<?php /*If sidebar is not disabled in Customizer, get_sidebar*/
if ( get_theme_mod( 'ctheme_remove_sidebar' ) != 1 ) :
get_sidebar();
endif;
get_footer(); ?>
```
This is one way I'm thinking of doing it. If you have any other ideas how I should approach it, let me know!
The purpose of this page will be to retrieve a list of animal names, (no date for the post, no excerpt for the post, just the name of the animal) so alphabetical order would be the most useful.
Thanks!
|
As I have stated, never ever use `query_posts`. The page you have linked to in the codex is worth nothing and completely wrong. For extra info on why not to use `query_posts`, check [my answer here](https://wordpress.stackexchange.com/a/191934/31545) and the answer by [@Rarst](https://wordpress.stackexchange.com/a/1755/31545).
You have another issue here, `category_name` does **not** accept the category name as value, but the **slug**. The naming convention of this parameter is wrong. `get_the_title()` returns the page name/title, not the slug. Your query might work if the page has a one word title without special characters as sanitizing the name in the `WP_Tax_Query` class might match it up the slug, but it will fail if the page name has special characters or have more than one word.
What you need is to get the page slug, which you will pass as category slug to `category_name` To do this, you need to get the queried object and then return the `$post_name` property. Again, the naming convention is completely wrong. `$post_name` holds the slug of the page, not the name.
In connection with ordering, you would need to set the `orderby` parameter to `title` and `order` to `ASC` to order from a-z and not the default `z-a`
All in all, your query would look something like this: (***NOTE:*** Requires minimum PHP 5.4)
```
$args = [
'category_name' => get_queried_object()->post_name,
'order' => 'ASC',
'orderby' => 'title' // Can use 'name' as well, see https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
// Add any extra parameters you need
];
$q = new WP_Query( $args );
// Run the loop
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Display what you need from the loop like title, content etc
}
wp_reset_postdata();
}
```
You can also try to use something like [this](https://wordpress.stackexchange.com/a/162904/31545) where you can have page where you choose which category to display when you publish a page, you can also select ordering and a few other features.
|
208,843 |
<p>Is there any benefit perfomance wise when defining a constant in the wp-config.php like so</p>
<pre><code><php define('PATH_TO_THEME', get_stylesheet_directory_uri() ); ?>
</code></pre>
<p>and then referring to <code>PATH_TO_THEME</code> instead using <code>get_stylesheet_directory_uri()</code> multiple times?</p>
<p>I got this from a wordpress handbook, saying that when you call this function multiple times it consumes more performance in comparison to using a constant like PATH_TO_THEME. Is that true? And why?</p>
<p>Or does it only give a performance boost when using an absolute uri to define the constant like so
<code><php define('PATH_TO_THEME', 'http://example.com/wp-content/themes/themename' ); ?>
</code>This of course would mean you had to change the uri anytime the url of the website or the location of the stylesheet directory changed.</p>
|
[
{
"answer_id": 208833,
"author": "pwbred",
"author_id": 6154,
"author_profile": "https://wordpress.stackexchange.com/users/6154",
"pm_score": 1,
"selected": false,
"text": "<p>You need to look closer at query_posts and order your posts by the title, as it says on the <a href=\"https://codex.wordpress.org/Alphabetizing_Posts#Main_Page\" rel=\"nofollow\">page that you linked to</a>.</p>\n\n<p>You need to change this:</p>\n\n<pre><code><?php query_posts('category_name='.get_the_title().'&post_status=publish');?>\n</code></pre>\n\n<p>and add this:</p>\n\n<pre><code><?php query_posts('category_name='.get_the_title().'&post_status=publish&orderby=title');?>\n</code></pre>\n\n<p>As someone else pointed out, you should really be using WP_Query in this situation. Take a look at the reference as many of the options are explained very clearly: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">Class Reference/WP Query</a></p>\n"
},
{
"answer_id": 208842,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>As I have stated, never ever use <code>query_posts</code>. The page you have linked to in the codex is worth nothing and completely wrong. For extra info on why not to use <code>query_posts</code>, check <a href=\"https://wordpress.stackexchange.com/a/191934/31545\">my answer here</a> and the answer by <a href=\"https://wordpress.stackexchange.com/a/1755/31545\">@Rarst</a>.</p>\n\n<p>You have another issue here, <code>category_name</code> does <strong>not</strong> accept the category name as value, but the <strong>slug</strong>. The naming convention of this parameter is wrong. <code>get_the_title()</code> returns the page name/title, not the slug. Your query might work if the page has a one word title without special characters as sanitizing the name in the <code>WP_Tax_Query</code> class might match it up the slug, but it will fail if the page name has special characters or have more than one word.</p>\n\n<p>What you need is to get the page slug, which you will pass as category slug to <code>category_name</code> To do this, you need to get the queried object and then return the <code>$post_name</code> property. Again, the naming convention is completely wrong. <code>$post_name</code> holds the slug of the page, not the name. </p>\n\n<p>In connection with ordering, you would need to set the <code>orderby</code> parameter to <code>title</code> and <code>order</code> to <code>ASC</code> to order from a-z and not the default <code>z-a</code></p>\n\n<p>All in all, your query would look something like this: (<strong><em>NOTE:</strong> Requires minimum PHP 5.4</em>)</p>\n\n<pre><code>$args = [\n 'category_name' => get_queried_object()->post_name,\n 'order' => 'ASC',\n 'orderby' => 'title' // Can use 'name' as well, see https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\n // Add any extra parameters you need\n];\n$q = new WP_Query( $args ); \n\n// Run the loop\nif ( $q->have_posts() ) {\n while ( $q->have_posts() ) {\n $q->the_post();\n\n // Display what you need from the loop like title, content etc\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>You can also try to use something like <a href=\"https://wordpress.stackexchange.com/a/162904/31545\">this</a> where you can have page where you choose which category to display when you publish a page, you can also select ordering and a few other features.</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208843",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/67074/"
] |
Is there any benefit perfomance wise when defining a constant in the wp-config.php like so
```
<php define('PATH_TO_THEME', get_stylesheet_directory_uri() ); ?>
```
and then referring to `PATH_TO_THEME` instead using `get_stylesheet_directory_uri()` multiple times?
I got this from a wordpress handbook, saying that when you call this function multiple times it consumes more performance in comparison to using a constant like PATH\_TO\_THEME. Is that true? And why?
Or does it only give a performance boost when using an absolute uri to define the constant like so
`<php define('PATH_TO_THEME', 'http://example.com/wp-content/themes/themename' ); ?>`This of course would mean you had to change the uri anytime the url of the website or the location of the stylesheet directory changed.
|
As I have stated, never ever use `query_posts`. The page you have linked to in the codex is worth nothing and completely wrong. For extra info on why not to use `query_posts`, check [my answer here](https://wordpress.stackexchange.com/a/191934/31545) and the answer by [@Rarst](https://wordpress.stackexchange.com/a/1755/31545).
You have another issue here, `category_name` does **not** accept the category name as value, but the **slug**. The naming convention of this parameter is wrong. `get_the_title()` returns the page name/title, not the slug. Your query might work if the page has a one word title without special characters as sanitizing the name in the `WP_Tax_Query` class might match it up the slug, but it will fail if the page name has special characters or have more than one word.
What you need is to get the page slug, which you will pass as category slug to `category_name` To do this, you need to get the queried object and then return the `$post_name` property. Again, the naming convention is completely wrong. `$post_name` holds the slug of the page, not the name.
In connection with ordering, you would need to set the `orderby` parameter to `title` and `order` to `ASC` to order from a-z and not the default `z-a`
All in all, your query would look something like this: (***NOTE:*** Requires minimum PHP 5.4)
```
$args = [
'category_name' => get_queried_object()->post_name,
'order' => 'ASC',
'orderby' => 'title' // Can use 'name' as well, see https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
// Add any extra parameters you need
];
$q = new WP_Query( $args );
// Run the loop
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Display what you need from the loop like title, content etc
}
wp_reset_postdata();
}
```
You can also try to use something like [this](https://wordpress.stackexchange.com/a/162904/31545) where you can have page where you choose which category to display when you publish a page, you can also select ordering and a few other features.
|
208,873 |
<p>I am going to install and use AWS SDK for PHP to facilitate uploads/list objects directly from the front-end of my WordPress instance to S3. What is the best practice to do that ?</p>
<p>P.S: I don't want to use plugins</p>
|
[
{
"answer_id": 208833,
"author": "pwbred",
"author_id": 6154,
"author_profile": "https://wordpress.stackexchange.com/users/6154",
"pm_score": 1,
"selected": false,
"text": "<p>You need to look closer at query_posts and order your posts by the title, as it says on the <a href=\"https://codex.wordpress.org/Alphabetizing_Posts#Main_Page\" rel=\"nofollow\">page that you linked to</a>.</p>\n\n<p>You need to change this:</p>\n\n<pre><code><?php query_posts('category_name='.get_the_title().'&post_status=publish');?>\n</code></pre>\n\n<p>and add this:</p>\n\n<pre><code><?php query_posts('category_name='.get_the_title().'&post_status=publish&orderby=title');?>\n</code></pre>\n\n<p>As someone else pointed out, you should really be using WP_Query in this situation. Take a look at the reference as many of the options are explained very clearly: <a href=\"https://codex.wordpress.org/Class_Reference/WP_Query\" rel=\"nofollow\">Class Reference/WP Query</a></p>\n"
},
{
"answer_id": 208842,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 3,
"selected": true,
"text": "<p>As I have stated, never ever use <code>query_posts</code>. The page you have linked to in the codex is worth nothing and completely wrong. For extra info on why not to use <code>query_posts</code>, check <a href=\"https://wordpress.stackexchange.com/a/191934/31545\">my answer here</a> and the answer by <a href=\"https://wordpress.stackexchange.com/a/1755/31545\">@Rarst</a>.</p>\n\n<p>You have another issue here, <code>category_name</code> does <strong>not</strong> accept the category name as value, but the <strong>slug</strong>. The naming convention of this parameter is wrong. <code>get_the_title()</code> returns the page name/title, not the slug. Your query might work if the page has a one word title without special characters as sanitizing the name in the <code>WP_Tax_Query</code> class might match it up the slug, but it will fail if the page name has special characters or have more than one word.</p>\n\n<p>What you need is to get the page slug, which you will pass as category slug to <code>category_name</code> To do this, you need to get the queried object and then return the <code>$post_name</code> property. Again, the naming convention is completely wrong. <code>$post_name</code> holds the slug of the page, not the name. </p>\n\n<p>In connection with ordering, you would need to set the <code>orderby</code> parameter to <code>title</code> and <code>order</code> to <code>ASC</code> to order from a-z and not the default <code>z-a</code></p>\n\n<p>All in all, your query would look something like this: (<strong><em>NOTE:</strong> Requires minimum PHP 5.4</em>)</p>\n\n<pre><code>$args = [\n 'category_name' => get_queried_object()->post_name,\n 'order' => 'ASC',\n 'orderby' => 'title' // Can use 'name' as well, see https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters\n // Add any extra parameters you need\n];\n$q = new WP_Query( $args ); \n\n// Run the loop\nif ( $q->have_posts() ) {\n while ( $q->have_posts() ) {\n $q->the_post();\n\n // Display what you need from the loop like title, content etc\n\n }\n wp_reset_postdata();\n}\n</code></pre>\n\n<p>You can also try to use something like <a href=\"https://wordpress.stackexchange.com/a/162904/31545\">this</a> where you can have page where you choose which category to display when you publish a page, you can also select ordering and a few other features.</p>\n"
}
] |
2015/11/16
|
[
"https://wordpress.stackexchange.com/questions/208873",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81228/"
] |
I am going to install and use AWS SDK for PHP to facilitate uploads/list objects directly from the front-end of my WordPress instance to S3. What is the best practice to do that ?
P.S: I don't want to use plugins
|
As I have stated, never ever use `query_posts`. The page you have linked to in the codex is worth nothing and completely wrong. For extra info on why not to use `query_posts`, check [my answer here](https://wordpress.stackexchange.com/a/191934/31545) and the answer by [@Rarst](https://wordpress.stackexchange.com/a/1755/31545).
You have another issue here, `category_name` does **not** accept the category name as value, but the **slug**. The naming convention of this parameter is wrong. `get_the_title()` returns the page name/title, not the slug. Your query might work if the page has a one word title without special characters as sanitizing the name in the `WP_Tax_Query` class might match it up the slug, but it will fail if the page name has special characters or have more than one word.
What you need is to get the page slug, which you will pass as category slug to `category_name` To do this, you need to get the queried object and then return the `$post_name` property. Again, the naming convention is completely wrong. `$post_name` holds the slug of the page, not the name.
In connection with ordering, you would need to set the `orderby` parameter to `title` and `order` to `ASC` to order from a-z and not the default `z-a`
All in all, your query would look something like this: (***NOTE:*** Requires minimum PHP 5.4)
```
$args = [
'category_name' => get_queried_object()->post_name,
'order' => 'ASC',
'orderby' => 'title' // Can use 'name' as well, see https://codex.wordpress.org/Class_Reference/WP_Query#Order_.26_Orderby_Parameters
// Add any extra parameters you need
];
$q = new WP_Query( $args );
// Run the loop
if ( $q->have_posts() ) {
while ( $q->have_posts() ) {
$q->the_post();
// Display what you need from the loop like title, content etc
}
wp_reset_postdata();
}
```
You can also try to use something like [this](https://wordpress.stackexchange.com/a/162904/31545) where you can have page where you choose which category to display when you publish a page, you can also select ordering and a few other features.
|
208,884 |
<p>I have a custom Post type called product which has a Methabox with a Custom Field Called <code>Price</code> I entered <code>$</code> for some of the products and I need to remove them from the WP table. Now can you please let me know how I can do that? I mean I need to know which table is storing the data from Metaboxes?</p>
<p><strong>Update</strong></p>
<pre><code>add_action( 'add_meta_boxes', 'product_details_mtbox' );
function product_details_mtbox()
{
foreach( $post_types as $post_type ){
add_meta_box(
"product-detail",
"Product Details ",
"render_mtbox",
$post_type,
"normal",
"high"
);
}
}
</code></pre>
|
[
{
"answer_id": 208885,
"author": "Mateusz Marchel",
"author_id": 83704,
"author_profile": "https://wordpress.stackexchange.com/users/83704",
"pm_score": 3,
"selected": true,
"text": "<p>In case you use native custom fields, you should look for them in wp_postmeta table (your table prefix can be different than 'wp').</p>\n"
},
{
"answer_id": 208886,
"author": "vancoder",
"author_id": 26778,
"author_profile": "https://wordpress.stackexchange.com/users/26778",
"pm_score": 0,
"selected": false,
"text": "<p>If you made the plugin yourself, you really should know where you are storing the data.</p>\n\n<p>Mateusz is correct, in that custom fields are normally stored in the postmeta table.</p>\n"
},
{
"answer_id": 208888,
"author": "Scriptonomy",
"author_id": 82166,
"author_profile": "https://wordpress.stackexchange.com/users/82166",
"pm_score": 1,
"selected": false,
"text": "<p>Custom fields, aka. custom post meta fields, are stored in the wp_postmeta table.</p>\n\n<p>Use this code to update your metas rather then going through the table. Modify the condition to target a certain post or a certain meta value:</p>\n\n<p><code>$args = array('post_type' => 'product');\n$query = new WP_Query( $args );\nforeach($query->posts as $post) {\n $meta = get_post_meta($post->ID, 'price', true);\n if ($post->ID == '85' && $meta == '$') { // Set search condition here\n update_post_meta($post->ID, 'price', '100'); //change meta value here\n }\n}</code></p>\n"
}
] |
2015/11/17
|
[
"https://wordpress.stackexchange.com/questions/208884",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31793/"
] |
I have a custom Post type called product which has a Methabox with a Custom Field Called `Price` I entered `$` for some of the products and I need to remove them from the WP table. Now can you please let me know how I can do that? I mean I need to know which table is storing the data from Metaboxes?
**Update**
```
add_action( 'add_meta_boxes', 'product_details_mtbox' );
function product_details_mtbox()
{
foreach( $post_types as $post_type ){
add_meta_box(
"product-detail",
"Product Details ",
"render_mtbox",
$post_type,
"normal",
"high"
);
}
}
```
|
In case you use native custom fields, you should look for them in wp\_postmeta table (your table prefix can be different than 'wp').
|
208,893 |
<p>I'm trying to change the menu in a primary and a secondary menu depending on the page which is visited.</p>
<p>My primary menu is in the top of the page, and it looks like this:</p>
<hr>
<p>Index | About | Contact</p>
<hr>
<p>And my second menu is a dropdown menu, under the header, and it looks like this:</p>
<hr>
<p>Write New | Help | Profile | </p>
<hr>
<p>So, the thing is that whenever you visit profile for example, I want to change both menus for others I've already created.</p>
<p>So reading I found something but it doesn't work at all: in the file functions.php I added:</p>
<pre><code>add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
function my_wp_nav_menu_args( $args) {
if( is_page('2') ) {
$args['menu'] = 'Original Menu';
} else {
$args['menu'] = 'Menu for Profile';
}
return $args;
}
</code></pre>
<p>It works, but it changes primary and secondary menus with the 'Menu for Profile', and I want it only for the primary. I've tried adding ['theme_location'] = 'primary' but what it does is dissapear both menus.</p>
<p>I hope you can help me, and thanks.</p>
|
[
{
"answer_id": 208901,
"author": "Omar",
"author_id": 83743,
"author_profile": "https://wordpress.stackexchange.com/users/83743",
"pm_score": -1,
"selected": false,
"text": "<p>You have to create two menus and call them with a conditional in <code>header.php</code> file, like this: </p>\n\n<pre><code>if ( is_page( 'about' ) ) { \n wp_nav_menu( array(\n 'menu' => 'primary', \n 'theme_location' => 'primary'\n ) ); \n} else { \n wp_nav_menu( array(\n 'menu' => 'second_menu', \n 'theme_location' => 'primary'\n ) );\n}\n</code></pre>\n"
},
{
"answer_id": 208906,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 1,
"selected": true,
"text": "<p>You most probably used the theme location part wrongly. Here is an example of how it should be done</p>\n\n<p>Follow the comments in code for explanation :-)</p>\n\n<pre><code>add_filter( 'wp_nav_menu_args', function ( $args ) \n{\n if ( is_page( 2 ) //Only target page 2 \n && $args['theme_location'] === 'primary' ) { // Check and only target the primary menu\n ) {\n $args['menu'] = 'Menu for Profile';\n }\n return $args;\n}); \n</code></pre>\n"
}
] |
2015/11/17
|
[
"https://wordpress.stackexchange.com/questions/208893",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83740/"
] |
I'm trying to change the menu in a primary and a secondary menu depending on the page which is visited.
My primary menu is in the top of the page, and it looks like this:
---
Index | About | Contact
---
And my second menu is a dropdown menu, under the header, and it looks like this:
---
Write New | Help | Profile |
---
So, the thing is that whenever you visit profile for example, I want to change both menus for others I've already created.
So reading I found something but it doesn't work at all: in the file functions.php I added:
```
add_filter( 'wp_nav_menu_args', 'my_wp_nav_menu_args' );
function my_wp_nav_menu_args( $args) {
if( is_page('2') ) {
$args['menu'] = 'Original Menu';
} else {
$args['menu'] = 'Menu for Profile';
}
return $args;
}
```
It works, but it changes primary and secondary menus with the 'Menu for Profile', and I want it only for the primary. I've tried adding ['theme\_location'] = 'primary' but what it does is dissapear both menus.
I hope you can help me, and thanks.
|
You most probably used the theme location part wrongly. Here is an example of how it should be done
Follow the comments in code for explanation :-)
```
add_filter( 'wp_nav_menu_args', function ( $args )
{
if ( is_page( 2 ) //Only target page 2
&& $args['theme_location'] === 'primary' ) { // Check and only target the primary menu
) {
$args['menu'] = 'Menu for Profile';
}
return $args;
});
```
|
208,896 |
<p>I have a custom post type to list countries but I am not sure how to create them with this permalink structure:</p>
<ul>
<li>Country archive: <code>/map</code></li>
<li>Country single: <code>/map/country/england</code></li>
</ul>
<p>How can I achieve this? Heres my country post code: </p>
<pre><code>function countries() {
$labels = array(
'name' => _x( 'countries', 'Post Type General Name', 'countries' ),
'singular_name' => _x( 'country', 'Post Type Singular Name', 'countries' ),
'menu_name' => __( 'Countries', 'countries' ),
'name_admin_bar' => __( 'Country', 'countries' ),
'parent_item_colon' => __( 'Parent Country', 'countries' ),
'all_items' => __( 'All Countries', 'countries' ),
'add_new_item' => __( 'Add New Country', 'countries' ),
'add_new' => __( 'Add New Country', 'countries' ),
'new_item' => __( 'New Country', 'countries' ),
'edit_item' => __( 'Edit Country', 'countries' ),
'update_item' => __( 'Update Country', 'countries' ),
'view_item' => __( 'View Country', 'countries' ),
'search_items' => __( 'Search Countries', 'countries' ),
'not_found' => __( 'Country Not found', 'countries' ),
'not_found_in_trash' => __( 'Not found in Trash', 'countries' ),
'items_list' => __( 'Country list', 'countries' ),
'items_list_navigation' => __( 'Countries List Navigation', 'countries' ),
'filter_items_list' => __( 'Filter Country List', 'countries' ),
);
$rewrite = array(
'slug' => 'country',
'with_front' => true,
'pages' => true,
'feeds' => true,
);
$args = array(
'label' => __( 'country', 'countries' ),
'description' => __( 'Country Information', 'countries' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'trackbacks', 'revisions', 'custom-fields', 'page-attributes', ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'rewrite' => $rewrite,
'capability_type' => 'page',
);
register_post_type( 'countries', $args );
}
add_action( 'init', 'countries', 0 );
</code></pre>
<p>I am also trying this with the following taxonomy but it 404s even when I update the permalink settings page:</p>
<pre><code>register_taxonomy(
'region',
'country',
[
'label' => __( 'Region' ),
'rewrite' => array( 'slug' => 'map/region' ),
'hierarchical' => true,
]
);
</code></pre>
|
[
{
"answer_id": 208899,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 2,
"selected": false,
"text": "<p>You just want a hierarchical post type. Change <code>'hierarchical' => false,</code> to <code>'hierarchical' => true,</code> and nest your posts appropriately</p>\n"
},
{
"answer_id": 208900,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>To get your desired archive URL, set <code>has_archive</code> to <code>'map'</code> instead of <code>true</code>.</p>\n\n<p>To get your desired single post URL, set the <code>slug</code> argument in your <code>$rewrite</code> array to <code>'map/country'</code></p>\n"
}
] |
2015/11/17
|
[
"https://wordpress.stackexchange.com/questions/208896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40814/"
] |
I have a custom post type to list countries but I am not sure how to create them with this permalink structure:
* Country archive: `/map`
* Country single: `/map/country/england`
How can I achieve this? Heres my country post code:
```
function countries() {
$labels = array(
'name' => _x( 'countries', 'Post Type General Name', 'countries' ),
'singular_name' => _x( 'country', 'Post Type Singular Name', 'countries' ),
'menu_name' => __( 'Countries', 'countries' ),
'name_admin_bar' => __( 'Country', 'countries' ),
'parent_item_colon' => __( 'Parent Country', 'countries' ),
'all_items' => __( 'All Countries', 'countries' ),
'add_new_item' => __( 'Add New Country', 'countries' ),
'add_new' => __( 'Add New Country', 'countries' ),
'new_item' => __( 'New Country', 'countries' ),
'edit_item' => __( 'Edit Country', 'countries' ),
'update_item' => __( 'Update Country', 'countries' ),
'view_item' => __( 'View Country', 'countries' ),
'search_items' => __( 'Search Countries', 'countries' ),
'not_found' => __( 'Country Not found', 'countries' ),
'not_found_in_trash' => __( 'Not found in Trash', 'countries' ),
'items_list' => __( 'Country list', 'countries' ),
'items_list_navigation' => __( 'Countries List Navigation', 'countries' ),
'filter_items_list' => __( 'Filter Country List', 'countries' ),
);
$rewrite = array(
'slug' => 'country',
'with_front' => true,
'pages' => true,
'feeds' => true,
);
$args = array(
'label' => __( 'country', 'countries' ),
'description' => __( 'Country Information', 'countries' ),
'labels' => $labels,
'supports' => array( 'title', 'editor', 'excerpt', 'thumbnail', 'trackbacks', 'revisions', 'custom-fields', 'page-attributes', ),
'taxonomies' => array( 'category', 'post_tag' ),
'hierarchical' => false,
'public' => true,
'show_ui' => true,
'show_in_menu' => true,
'menu_position' => 5,
'show_in_admin_bar' => true,
'show_in_nav_menus' => true,
'can_export' => true,
'has_archive' => true,
'exclude_from_search' => false,
'publicly_queryable' => true,
'rewrite' => $rewrite,
'capability_type' => 'page',
);
register_post_type( 'countries', $args );
}
add_action( 'init', 'countries', 0 );
```
I am also trying this with the following taxonomy but it 404s even when I update the permalink settings page:
```
register_taxonomy(
'region',
'country',
[
'label' => __( 'Region' ),
'rewrite' => array( 'slug' => 'map/region' ),
'hierarchical' => true,
]
);
```
|
You just want a hierarchical post type. Change `'hierarchical' => false,` to `'hierarchical' => true,` and nest your posts appropriately
|
208,979 |
<p>I am developing a swear filter plugin for my blog. It is supposed to deny submissions containing any words in a text file called <code>swears.txt</code>. Here is the code I am using for the comment form on single post page:</p>
<pre><code><?php
if (isset($_POST['submit'])) {
echo 'Submitted'; // for debugging purposes
$swearsFile = 'swears.txt';
$swearsCntnt = file_get_contents($swearsFile);
$swearList = explode("\n", $swearsCntnt);
$swearWords = "/";
for ($i = 0; $i < count($swearList); ++$i) {
if ($i == 0)
$swearWords .= rtrim($swearList[$i]);
else
$swearWords .= "|" . rtrim($swearList[$i]);
}
$swearWords .= "/i";
if (preg_match($swearWords, $_POST['comment'])) {
wp_die( __( '<strong>ERROR</strong>: You have entered forbidden text. Please consider revising.' ), 200 );
}
}
?>
</code></pre>
<p>The problem is that nothing happens after I press the Post Comment button except that the submitted comment appears as a new one. I am using an echo to verify that the Post Comment button has been pressed whether or not its following statements return true, yet nothing happens. How do I get WordPress to acknowledge <code>if (isset($_POST['submit']))</code>?</p>
|
[
{
"answer_id": 208983,
"author": "Mateusz Hajdziony",
"author_id": 15865,
"author_profile": "https://wordpress.stackexchange.com/users/15865",
"pm_score": 2,
"selected": true,
"text": "<p>This might not directly answer your question (because I haven't even thought about why the <code>$_POST['submit']</code> would be ignored or if it is even correct), but you should use filters/actions whenever possible.</p>\n\n<p>The correct filter for filtering comment text is <a href=\"https://developer.wordpress.org/reference/hooks/pre_comment_content/\" rel=\"nofollow\"><code>pre_comment_content</code></a>, and you should use it like this:</p>\n\n<pre><code>function my_filter_comment_for_swear_words( $comment_content ) {\n // Verify if $comment_content contains swear words here\n // return $comment_content if it doesn't contain forbidden words\n // or wp_die if it does\n}\nadd_filter( 'pre_comment_content', 'my_filter_comment_for_swear_words' );\n</code></pre>\n\n<p>This code would, as usual, go into your <code>functions.php</code> file or into your custom plugin (depending on what your setup is).</p>\n"
},
{
"answer_id": 208984,
"author": "flomei",
"author_id": 65455,
"author_profile": "https://wordpress.stackexchange.com/users/65455",
"pm_score": 0,
"selected": false,
"text": "<p>I don´t want to stop you, but what you are doing here is WordPress standard functionality. Have a look at\n<code>Settings -> Discussion</code> where you will find a textarea where you can enter words which trigger a comment to need moderation.</p>\n\n<p>Besides that you are probably going the wrong way. You should not just \"wait\" for a submit, but create <a href=\"https://codex.wordpress.org/Plugin_API/Hooks\" rel=\"nofollow\">a hook</a> at the relevant places. You could use <a href=\"https://codex.wordpress.org/Plugin_API/Action_Reference/comment_post\" rel=\"nofollow\"><code>comment_post</code></a> to trigger a function when a comment is posted.</p>\n"
},
{
"answer_id": 208990,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>It is not being TRUE because the action url of the comment form points to the wp-comments-post.php file at the root of the site which handle the submission. Once the submitting was successfully processed at that file the user is redirected back to the post in which the submit was done.</p>\n\n<p>As the other answers had said, you are doing it wrong and you should use the available comment handling hooks to trigger the execution of your code (if at all it is needed)</p>\n"
}
] |
2015/11/17
|
[
"https://wordpress.stackexchange.com/questions/208979",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83779/"
] |
I am developing a swear filter plugin for my blog. It is supposed to deny submissions containing any words in a text file called `swears.txt`. Here is the code I am using for the comment form on single post page:
```
<?php
if (isset($_POST['submit'])) {
echo 'Submitted'; // for debugging purposes
$swearsFile = 'swears.txt';
$swearsCntnt = file_get_contents($swearsFile);
$swearList = explode("\n", $swearsCntnt);
$swearWords = "/";
for ($i = 0; $i < count($swearList); ++$i) {
if ($i == 0)
$swearWords .= rtrim($swearList[$i]);
else
$swearWords .= "|" . rtrim($swearList[$i]);
}
$swearWords .= "/i";
if (preg_match($swearWords, $_POST['comment'])) {
wp_die( __( '<strong>ERROR</strong>: You have entered forbidden text. Please consider revising.' ), 200 );
}
}
?>
```
The problem is that nothing happens after I press the Post Comment button except that the submitted comment appears as a new one. I am using an echo to verify that the Post Comment button has been pressed whether or not its following statements return true, yet nothing happens. How do I get WordPress to acknowledge `if (isset($_POST['submit']))`?
|
This might not directly answer your question (because I haven't even thought about why the `$_POST['submit']` would be ignored or if it is even correct), but you should use filters/actions whenever possible.
The correct filter for filtering comment text is [`pre_comment_content`](https://developer.wordpress.org/reference/hooks/pre_comment_content/), and you should use it like this:
```
function my_filter_comment_for_swear_words( $comment_content ) {
// Verify if $comment_content contains swear words here
// return $comment_content if it doesn't contain forbidden words
// or wp_die if it does
}
add_filter( 'pre_comment_content', 'my_filter_comment_for_swear_words' );
```
This code would, as usual, go into your `functions.php` file or into your custom plugin (depending on what your setup is).
|
209,016 |
<p>I am developing a website where I have modified the comment form to have review rating capabilities. I ask them to rate them on food, service and location. For each of those option there is “bad”(1),”okay”(2),”Good”(3). I store each in a custom comment field like the following “review_service”=1 & “review_food”=3.</p>
<p>Right now when a page loads “get_comments” is used to get all the custom comment fields and count them in the following array. The array is used to display results.</p>
<pre><code>Array
(
[food] => Array
(
[1] => 3
[2] => 1
[3] => 1
)
[service] => Array
(
[1] => 1
[2] => 2
[3] => 2
)
[location] => Array
(
[1] => 1
[2] => 3
[3] => 1
)
)
</code></pre>
<p>In future I want to show locations listed in order of counts. I’m sure using ‘get_comments’ through all posts is not efficient.
I thought of two ideas.</p>
<ol>
<li><p>Store the array (serialized) in a post custom field for the location. Each time a review is done the array in the custom field is updated. </p></li>
<li><p>Put the array in a custom table like below. <strong>EDIT</strong>: I forgot to add the option column. </p>
<p><code>|Id | post_id | option_id |option|option_count|</code></p>
<p><code>|1 |1433 |food |bad |5 |</code></p>
<p><code>|2 |1433 |food |good |3 |</code></p>
<p>In terms of speed/efficiency which option should I choose?</p></li>
</ol>
|
[
{
"answer_id": 208985,
"author": "aifrim",
"author_id": 58040,
"author_profile": "https://wordpress.stackexchange.com/users/58040",
"pm_score": 1,
"selected": false,
"text": "<p>Whatever the <code>action/filter</code> you <strong>hooked</strong> your code into they <em>(the callbacks)</em> <strong>DO NOT</strong> run asynchronously.</p>\n\n<p>PHP is not Javascript/Java/C# or any other programming language & compiler/interpreter that permits async functions, user-defined threads and etc.. Why would you think this? PHP is a text processor that allows the creation of dynamic website. Upon a set of <code>parameters</code> is returns a certain <code>HTML</code> result. It has to be <strong>fast</strong> as <strong>the Flash</strong> and it cannot wait for <code>async functions</code> to end before sending its result.</p>\n\n<p>Your site lags because your functions do some heavy duty stuff there.</p>\n"
},
{
"answer_id": 208988,
"author": "Mateusz Hajdziony",
"author_id": 15865,
"author_profile": "https://wordpress.stackexchange.com/users/15865",
"pm_score": 3,
"selected": true,
"text": "<p>Actions and filters are resolved in a linear fashion when processing the request. They do not run asynchronously. If you have some heavy processing that runs during every request (i.e. you use action and filter hooks that run during every page load for every user, like <code>template_redirect</code>, <code>init</code> or whatever usual hooks you might be using), then it will impact the loading time of the page and probably consume lots of your server's CPU time.</p>\n\n<p>If you do some heavy data processing that doesn't need to run for every page load (that is not calculated for every user and doesn't have to be accessible for users during casual browsing) you might consider using WP Cron or setup a cron job on your server.</p>\n\n<p>Otherwise, you might use AJAX to load the needed data asynchronously, that is display the page without the special processed data first, then send an AJAX request to the server which would fetch the data. This way the initial page load is fast and the user sees some kind of loading animation and knows that your website is working on fetching the data.</p>\n"
}
] |
2015/11/17
|
[
"https://wordpress.stackexchange.com/questions/209016",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/28123/"
] |
I am developing a website where I have modified the comment form to have review rating capabilities. I ask them to rate them on food, service and location. For each of those option there is “bad”(1),”okay”(2),”Good”(3). I store each in a custom comment field like the following “review\_service”=1 & “review\_food”=3.
Right now when a page loads “get\_comments” is used to get all the custom comment fields and count them in the following array. The array is used to display results.
```
Array
(
[food] => Array
(
[1] => 3
[2] => 1
[3] => 1
)
[service] => Array
(
[1] => 1
[2] => 2
[3] => 2
)
[location] => Array
(
[1] => 1
[2] => 3
[3] => 1
)
)
```
In future I want to show locations listed in order of counts. I’m sure using ‘get\_comments’ through all posts is not efficient.
I thought of two ideas.
1. Store the array (serialized) in a post custom field for the location. Each time a review is done the array in the custom field is updated.
2. Put the array in a custom table like below. **EDIT**: I forgot to add the option column.
`|Id | post_id | option_id |option|option_count|`
`|1 |1433 |food |bad |5 |`
`|2 |1433 |food |good |3 |`
In terms of speed/efficiency which option should I choose?
|
Actions and filters are resolved in a linear fashion when processing the request. They do not run asynchronously. If you have some heavy processing that runs during every request (i.e. you use action and filter hooks that run during every page load for every user, like `template_redirect`, `init` or whatever usual hooks you might be using), then it will impact the loading time of the page and probably consume lots of your server's CPU time.
If you do some heavy data processing that doesn't need to run for every page load (that is not calculated for every user and doesn't have to be accessible for users during casual browsing) you might consider using WP Cron or setup a cron job on your server.
Otherwise, you might use AJAX to load the needed data asynchronously, that is display the page without the special processed data first, then send an AJAX request to the server which would fetch the data. This way the initial page load is fast and the user sees some kind of loading animation and knows that your website is working on fetching the data.
|
209,046 |
<p>I use the below code to delete custom posts with status 'expired' (thanks to <a href="https://stackoverflow.com/q/27386129/1354580">Jamie Keefer</a>). Posts are set as 'expired' by a 3rd party plugin. Users have only a frontend access to their posts (adverts).</p>
<p>My question is: <strong>how to delete them after a number of days after they expired if post authors don't republish them?</strong> Also, I will appreciate any suggestions about how to improve this code.</p>
<pre><code>// expired_post_delete hook fires when the Cron is executed
add_action( 'expired_post_delete', 'delete_expired_posts' );
// This function will run once the 'expired_post_delete' is called
function delete_expired_posts() {
$todays_date = current_time('mysql');
$args = array(
'post_type' => 'advert',
'post_status' => 'expired',
'posts_per_page' => -1
);
$posts = new WP_Query( $args );
// The Loop
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
wp_delete_post(get_the_ID());
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
}
// Add function to register event to WordPress init
add_action( 'init', 'register_daily_post_delete_event');
// Function which will register the event
function register_daily_post_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'expired_post_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'daily', 'expired_post_delete' );
}
}
</code></pre>
<p><strong>UPDATE</strong></p>
<p>This is how posts are set as 'expired':</p>
<pre><code>add_action( 'adverts_event_expire_ads', 'adverts_event_expire_ads' );
/**
* Expires ads
*
* Function finds Adverts that already expired (value in _expiration_date
* meta field is lower then current timestamp) and changes their status to 'expired'.
*
* @since 0.1
* @return void
*/
function adverts_event_expire_ads() {
// find adverts with status 'publish' which exceeded expiration date
// (_expiration_date is a timestamp)
$posts = new WP_Query( array(
"post_type" => "advert",
"post_status" => "publish",
"meta_query" => array(
array(
"key" => "_expiration_date",
"value" => current_time( 'timestamp' ),
"compare" => "<="
)
)
) );
if( $posts->post_count ) {
foreach($posts->posts as $post) {
// change post status to expired.
$update = wp_update_post( array(
"ID" => $post->ID,
"post_status" => "expired"
) );
} // endforeach
} // endif
}
</code></pre>
|
[
{
"answer_id": 209080,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2>The native trash bin</h2>\n\n<p>It sounds like you're implementing your own version of the WordPress <strong><em>trash</em></strong> system.</p>\n\n<p>If you <em>trash</em> a post, the native way, it will get the <code>trash</code> post status and will be automatically deleted (permanently) after 30 days. You can change that in your <code>wp-config.php</code> file with:</p>\n\n<pre><code>define( 'EMPTY_TRASH_DAYS', 10 );\n</code></pre>\n\n<p>for e.g. 10 days.</p>\n\n<p>You can then trash your post with <a href=\"https://codex.wordpress.org/Function_Reference/wp_trash_post\" rel=\"nofollow\"><code>wp_trash_post( $post_id )</code></a> instead of creating your own custom <code>expire</code> post status.</p>\n\n<p>This way you let the system work <strong>with you</strong> ;-)</p>\n\n<p>For more info check the <a href=\"https://codex.wordpress.org/Trash_status\" rel=\"nofollow\"><em>trash status</em></a> in the Codex.</p>\n"
},
{
"answer_id": 209173,
"author": "Pieter Goosen",
"author_id": 31545,
"author_profile": "https://wordpress.stackexchange.com/users/31545",
"pm_score": 4,
"selected": true,
"text": "<p>WP Cron jobs are not reliable as it needs someone to visit the site at the time the event should fire. If you need precise timing, you should use server cron jobs. </p>\n\n<p>Anyways, lets look at your code and what is wrong and we can fix it</p>\n\n<ul>\n<li><p><code>wp</code> is a better hook to use to hook your scheduled event, this is the earliest that postdata available. <code>init</code> is way to early. I probably think for safety, you can also try the <code>template_redirect</code> hook.</p></li>\n<li><p>Your code are very very expensive to run which unnecessarily wastes server resources. We need to look at the following:</p>\n\n<ul>\n<li><p>We do not need any postdata except the post ID. Any other postdata are useless, and querying it waste a lot of resources. On large sites, this can actually lead to fatal errors due to timing out</p></li>\n<li><p>We only need to query posts which has expired and the expiry date has reached a certain timeframe.</p></li>\n</ul></li>\n</ul>\n\n<p>Lets put everything in code: (<strong><em>NOTE:</strong> This all untested, I have also copied and pasted some of your code, so I might have missed something, and also, the code requires PHP 5.4+</em>)</p>\n\n<pre><code>function get_exired_posts_to_delete()\n{\n /**\n * If you need posts that expired more than a week ago, we would need to\n * get the unix time stamp of the day a week ago. You can adjust the relative \n * date and time formats as needed. \n * @see http://php.net/manual/en/function.strtotime.php\n * @see http://php.net/manual/en/datetime.formats.php\n */\n // As example, we need to get posts that has expired more than 7days ago\n $past = strtotime( \"- 1 week\" );\n\n // Set our query arguments\n $args = [\n 'fields' => 'ids', // Only get post ID's to improve performance\n 'post_type' => 'advert',\n 'post_status' => 'expired',\n 'posts_per_page' => -1,\n 'meta_query' => [\n [\n 'key' => '_expiration_date',\n 'value' => $past,\n 'compare' => '<='\n ]\n ]\n ];\n $q = get_posts( $args );\n\n // Check if we have posts to delete, if not, return false\n if ( !$q )\n return false;\n\n // OK, we have posts to delete, lets delete them\n foreach ( $q as $id )\n wp_delete_post( $id );\n}\n</code></pre>\n\n<p>Now we can create our custom hook to hook our function</p>\n\n<pre><code>// expired_post_delete hook fires when the Cron is executed\nadd_action( 'expired_post_delete', 'get_exired_posts_to_delete' );\n</code></pre>\n\n<p>Lastly, schedule our event</p>\n\n<pre><code>// Add function to register event to wp\nadd_action( 'wp', 'register_daily_post_delete_event');\nfunction register_daily_post_delete_event() {\n // Make sure this event hasn't been scheduled\n if( !wp_next_scheduled( 'expired_post_delete' ) ) {\n // Schedule the event\n wp_schedule_event( time(), 'daily', 'expired_post_delete' );\n }\n}\n</code></pre>\n\n<p>This should about do it, just remember to set the correct time frame inside the function</p>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25187/"
] |
I use the below code to delete custom posts with status 'expired' (thanks to [Jamie Keefer](https://stackoverflow.com/q/27386129/1354580)). Posts are set as 'expired' by a 3rd party plugin. Users have only a frontend access to their posts (adverts).
My question is: **how to delete them after a number of days after they expired if post authors don't republish them?** Also, I will appreciate any suggestions about how to improve this code.
```
// expired_post_delete hook fires when the Cron is executed
add_action( 'expired_post_delete', 'delete_expired_posts' );
// This function will run once the 'expired_post_delete' is called
function delete_expired_posts() {
$todays_date = current_time('mysql');
$args = array(
'post_type' => 'advert',
'post_status' => 'expired',
'posts_per_page' => -1
);
$posts = new WP_Query( $args );
// The Loop
if ( $posts->have_posts() ) {
while ( $posts->have_posts() ) {
$posts->the_post();
wp_delete_post(get_the_ID());
}
} else {
// no posts found
}
/* Restore original Post Data */
wp_reset_postdata();
}
// Add function to register event to WordPress init
add_action( 'init', 'register_daily_post_delete_event');
// Function which will register the event
function register_daily_post_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'expired_post_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'daily', 'expired_post_delete' );
}
}
```
**UPDATE**
This is how posts are set as 'expired':
```
add_action( 'adverts_event_expire_ads', 'adverts_event_expire_ads' );
/**
* Expires ads
*
* Function finds Adverts that already expired (value in _expiration_date
* meta field is lower then current timestamp) and changes their status to 'expired'.
*
* @since 0.1
* @return void
*/
function adverts_event_expire_ads() {
// find adverts with status 'publish' which exceeded expiration date
// (_expiration_date is a timestamp)
$posts = new WP_Query( array(
"post_type" => "advert",
"post_status" => "publish",
"meta_query" => array(
array(
"key" => "_expiration_date",
"value" => current_time( 'timestamp' ),
"compare" => "<="
)
)
) );
if( $posts->post_count ) {
foreach($posts->posts as $post) {
// change post status to expired.
$update = wp_update_post( array(
"ID" => $post->ID,
"post_status" => "expired"
) );
} // endforeach
} // endif
}
```
|
WP Cron jobs are not reliable as it needs someone to visit the site at the time the event should fire. If you need precise timing, you should use server cron jobs.
Anyways, lets look at your code and what is wrong and we can fix it
* `wp` is a better hook to use to hook your scheduled event, this is the earliest that postdata available. `init` is way to early. I probably think for safety, you can also try the `template_redirect` hook.
* Your code are very very expensive to run which unnecessarily wastes server resources. We need to look at the following:
+ We do not need any postdata except the post ID. Any other postdata are useless, and querying it waste a lot of resources. On large sites, this can actually lead to fatal errors due to timing out
+ We only need to query posts which has expired and the expiry date has reached a certain timeframe.
Lets put everything in code: (***NOTE:*** This all untested, I have also copied and pasted some of your code, so I might have missed something, and also, the code requires PHP 5.4+)
```
function get_exired_posts_to_delete()
{
/**
* If you need posts that expired more than a week ago, we would need to
* get the unix time stamp of the day a week ago. You can adjust the relative
* date and time formats as needed.
* @see http://php.net/manual/en/function.strtotime.php
* @see http://php.net/manual/en/datetime.formats.php
*/
// As example, we need to get posts that has expired more than 7days ago
$past = strtotime( "- 1 week" );
// Set our query arguments
$args = [
'fields' => 'ids', // Only get post ID's to improve performance
'post_type' => 'advert',
'post_status' => 'expired',
'posts_per_page' => -1,
'meta_query' => [
[
'key' => '_expiration_date',
'value' => $past,
'compare' => '<='
]
]
];
$q = get_posts( $args );
// Check if we have posts to delete, if not, return false
if ( !$q )
return false;
// OK, we have posts to delete, lets delete them
foreach ( $q as $id )
wp_delete_post( $id );
}
```
Now we can create our custom hook to hook our function
```
// expired_post_delete hook fires when the Cron is executed
add_action( 'expired_post_delete', 'get_exired_posts_to_delete' );
```
Lastly, schedule our event
```
// Add function to register event to wp
add_action( 'wp', 'register_daily_post_delete_event');
function register_daily_post_delete_event() {
// Make sure this event hasn't been scheduled
if( !wp_next_scheduled( 'expired_post_delete' ) ) {
// Schedule the event
wp_schedule_event( time(), 'daily', 'expired_post_delete' );
}
}
```
This should about do it, just remember to set the correct time frame inside the function
|
209,059 |
<p>I'm on ubuntu vps running nginx</p>
<p>Running w3 total cache on wordpress.</p>
<p>Everything works fine except for when i enable "rewrite url structure", and it breaks, 404 probably to the minified files.</p>
<p>How to proceed?</p>
<p>Am i missing some package on my vps? what should I install?</p>
<p>Permalink for wordpress work fine though</p>
<p><strong>Note:</strong>
nginx.conf of site includes custom nginx.file properly which is being written fine by w3tc too, so minify isn't the issue and minify is working fine too, only url rewriting isn't.</p>
<p>Thanks.</p>
|
[
{
"answer_id": 209067,
"author": "riteshsanap",
"author_id": 55324,
"author_profile": "https://wordpress.stackexchange.com/users/55324",
"pm_score": 1,
"selected": false,
"text": "<p>W3 Total cache generates a <code>nginx.conf</code> file in the root of your blog.</p>\n\n<p>you need to include that file in your nginx configuration file, for W3 Total cache to work properly.</p>\n\n<p>For example if your file is in the <code>/etc/nginx/sites-available/MyWordPress</code></p>\n\n<p>then edit that file to include your blogs <code>nginx.conf</code> generated by W3 Total Cache in the Server block.</p>\n\n<pre>\n server {\n listen 80;\n listen [::]:80;\n\n root /var/www/MyWordPress;\n index index.php index.html index.htm;\n\n include /var/www/MyWordPress/nginx.conf;\n }\n</pre>\n\n<p>you just need to include the last line.</p>\n\n<p>Update :</p>\n\n<p><code>nginx.conf</code> generated by W3 Total Cache contains the below rewrite code for Minify :</p>\n\n<pre>\n# BEGIN W3TC Minify core\nrewrite ^/wp-content/cache/minify.*/w3tc_rewrite_test$ /wp-content/plugins/w3-total-cache/pub/minify.php?w3tc_rewrite_test=1 last;\nset $w3tc_enc \"\";\nif ($http_accept_encoding ~ gzip) {\n set $w3tc_enc .gzip;\n}\nif (-f $request_filename$w3tc_enc) {\n rewrite (.*) $1$w3tc_enc break;\n}\nrewrite ^/wp-content/cache/minify/(.+/[X]+\\.css)$ /wp-content/plugins/w3-total-cache/pub/minify.php?test_file=$1 last;\nrewrite ^/wp-content/cache/minify/(.+\\.(css|js))$ /wp-content/plugins/w3-total-cache/pub/minify.php?file=$1 last;\n# END W3TC Minify core\n</pre>\n"
},
{
"answer_id": 209135,
"author": "Nabeel Khan",
"author_id": 57389,
"author_profile": "https://wordpress.stackexchange.com/users/57389",
"pm_score": 0,
"selected": false,
"text": "<p>The issue was that w3 total cache wasn't creating the w3tc folder in wp-content itself! Don't know why? :/ </p>\n\n<p>Anyway, created it, gave it chown to www-data, restarted nginx and voila! </p>\n\n<p>Check the 3rd error on this page for method:</p>\n\n<p><a href=\"http://nabtron.com/w3-total-cache-fixing-errors/\" rel=\"nofollow\">http://nabtron.com/w3-total-cache-fixing-errors/</a></p>\n\n<p>I wonder if the install guide could be more clear!</p>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209059",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57389/"
] |
I'm on ubuntu vps running nginx
Running w3 total cache on wordpress.
Everything works fine except for when i enable "rewrite url structure", and it breaks, 404 probably to the minified files.
How to proceed?
Am i missing some package on my vps? what should I install?
Permalink for wordpress work fine though
**Note:**
nginx.conf of site includes custom nginx.file properly which is being written fine by w3tc too, so minify isn't the issue and minify is working fine too, only url rewriting isn't.
Thanks.
|
W3 Total cache generates a `nginx.conf` file in the root of your blog.
you need to include that file in your nginx configuration file, for W3 Total cache to work properly.
For example if your file is in the `/etc/nginx/sites-available/MyWordPress`
then edit that file to include your blogs `nginx.conf` generated by W3 Total Cache in the Server block.
```
server {
listen 80;
listen [::]:80;
root /var/www/MyWordPress;
index index.php index.html index.htm;
include /var/www/MyWordPress/nginx.conf;
}
```
you just need to include the last line.
Update :
`nginx.conf` generated by W3 Total Cache contains the below rewrite code for Minify :
```
# BEGIN W3TC Minify core
rewrite ^/wp-content/cache/minify.*/w3tc_rewrite_test$ /wp-content/plugins/w3-total-cache/pub/minify.php?w3tc_rewrite_test=1 last;
set $w3tc_enc "";
if ($http_accept_encoding ~ gzip) {
set $w3tc_enc .gzip;
}
if (-f $request_filename$w3tc_enc) {
rewrite (.*) $1$w3tc_enc break;
}
rewrite ^/wp-content/cache/minify/(.+/[X]+\.css)$ /wp-content/plugins/w3-total-cache/pub/minify.php?test_file=$1 last;
rewrite ^/wp-content/cache/minify/(.+\.(css|js))$ /wp-content/plugins/w3-total-cache/pub/minify.php?file=$1 last;
# END W3TC Minify core
```
|
209,060 |
<p>I have this code:</p>
<pre><code>Search: <input type="text" id="fname" onkeyup="myfunction()">
<a id="sear" href="" target="_blank">Search</a>
<script>
function myFunction() {
var x = document.getElementById("fname").value;
var url = "https://www.google.co.in/search?q=all+"+x+"&biw=1366&bih=643&source=lnms&tbm=isch";
document.getElementById("sear").href=url;
}
</script>
</code></pre>
<p>This code is changing into the following code when I add it to wordpress page editor and is not working.</p>
<pre><code>Search: <input id="fname" type="text" />
<a id="sear" target="_blank"></a>Search
<script>// <![CDATA[
function myFunction() {
var x = document.getElementById("fname").value;
var url = "https://www.google.co.in/search?q=all+"+x+"&biw=1366&bih=643&source=lnms&tbm=isch";
document.getElementById("sear").href=url;
}
// ]]></script>
</code></pre>
<p>Is there a solution to make it work?</p>
|
[
{
"answer_id": 209067,
"author": "riteshsanap",
"author_id": 55324,
"author_profile": "https://wordpress.stackexchange.com/users/55324",
"pm_score": 1,
"selected": false,
"text": "<p>W3 Total cache generates a <code>nginx.conf</code> file in the root of your blog.</p>\n\n<p>you need to include that file in your nginx configuration file, for W3 Total cache to work properly.</p>\n\n<p>For example if your file is in the <code>/etc/nginx/sites-available/MyWordPress</code></p>\n\n<p>then edit that file to include your blogs <code>nginx.conf</code> generated by W3 Total Cache in the Server block.</p>\n\n<pre>\n server {\n listen 80;\n listen [::]:80;\n\n root /var/www/MyWordPress;\n index index.php index.html index.htm;\n\n include /var/www/MyWordPress/nginx.conf;\n }\n</pre>\n\n<p>you just need to include the last line.</p>\n\n<p>Update :</p>\n\n<p><code>nginx.conf</code> generated by W3 Total Cache contains the below rewrite code for Minify :</p>\n\n<pre>\n# BEGIN W3TC Minify core\nrewrite ^/wp-content/cache/minify.*/w3tc_rewrite_test$ /wp-content/plugins/w3-total-cache/pub/minify.php?w3tc_rewrite_test=1 last;\nset $w3tc_enc \"\";\nif ($http_accept_encoding ~ gzip) {\n set $w3tc_enc .gzip;\n}\nif (-f $request_filename$w3tc_enc) {\n rewrite (.*) $1$w3tc_enc break;\n}\nrewrite ^/wp-content/cache/minify/(.+/[X]+\\.css)$ /wp-content/plugins/w3-total-cache/pub/minify.php?test_file=$1 last;\nrewrite ^/wp-content/cache/minify/(.+\\.(css|js))$ /wp-content/plugins/w3-total-cache/pub/minify.php?file=$1 last;\n# END W3TC Minify core\n</pre>\n"
},
{
"answer_id": 209135,
"author": "Nabeel Khan",
"author_id": 57389,
"author_profile": "https://wordpress.stackexchange.com/users/57389",
"pm_score": 0,
"selected": false,
"text": "<p>The issue was that w3 total cache wasn't creating the w3tc folder in wp-content itself! Don't know why? :/ </p>\n\n<p>Anyway, created it, gave it chown to www-data, restarted nginx and voila! </p>\n\n<p>Check the 3rd error on this page for method:</p>\n\n<p><a href=\"http://nabtron.com/w3-total-cache-fixing-errors/\" rel=\"nofollow\">http://nabtron.com/w3-total-cache-fixing-errors/</a></p>\n\n<p>I wonder if the install guide could be more clear!</p>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209060",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83782/"
] |
I have this code:
```
Search: <input type="text" id="fname" onkeyup="myfunction()">
<a id="sear" href="" target="_blank">Search</a>
<script>
function myFunction() {
var x = document.getElementById("fname").value;
var url = "https://www.google.co.in/search?q=all+"+x+"&biw=1366&bih=643&source=lnms&tbm=isch";
document.getElementById("sear").href=url;
}
</script>
```
This code is changing into the following code when I add it to wordpress page editor and is not working.
```
Search: <input id="fname" type="text" />
<a id="sear" target="_blank"></a>Search
<script>// <![CDATA[
function myFunction() {
var x = document.getElementById("fname").value;
var url = "https://www.google.co.in/search?q=all+"+x+"&biw=1366&bih=643&source=lnms&tbm=isch";
document.getElementById("sear").href=url;
}
// ]]></script>
```
Is there a solution to make it work?
|
W3 Total cache generates a `nginx.conf` file in the root of your blog.
you need to include that file in your nginx configuration file, for W3 Total cache to work properly.
For example if your file is in the `/etc/nginx/sites-available/MyWordPress`
then edit that file to include your blogs `nginx.conf` generated by W3 Total Cache in the Server block.
```
server {
listen 80;
listen [::]:80;
root /var/www/MyWordPress;
index index.php index.html index.htm;
include /var/www/MyWordPress/nginx.conf;
}
```
you just need to include the last line.
Update :
`nginx.conf` generated by W3 Total Cache contains the below rewrite code for Minify :
```
# BEGIN W3TC Minify core
rewrite ^/wp-content/cache/minify.*/w3tc_rewrite_test$ /wp-content/plugins/w3-total-cache/pub/minify.php?w3tc_rewrite_test=1 last;
set $w3tc_enc "";
if ($http_accept_encoding ~ gzip) {
set $w3tc_enc .gzip;
}
if (-f $request_filename$w3tc_enc) {
rewrite (.*) $1$w3tc_enc break;
}
rewrite ^/wp-content/cache/minify/(.+/[X]+\.css)$ /wp-content/plugins/w3-total-cache/pub/minify.php?test_file=$1 last;
rewrite ^/wp-content/cache/minify/(.+\.(css|js))$ /wp-content/plugins/w3-total-cache/pub/minify.php?file=$1 last;
# END W3TC Minify core
```
|
209,069 |
<p>I have this code:</p>
<pre><code>Search: <input type="text" id="fname" onkeyup="myfunction()">
<a id="sear" href="" target="_blank">Search</a>
<script>
function myFunction() {
var x = document.getElementById("fname").value;
var url = "https://www.google.co.in/search?q=all+"+x+"&biw=1366&bih=643&source=lnms&tbm=isch";
document.getElementById("sear").href=url;
}
</script>
</code></pre>
<p>I have implemented this in WordPress and the link is now pointing to the same page rather than opening the google search page.</p>
|
[
{
"answer_id": 209075,
"author": "daniyalahmad",
"author_id": 69626,
"author_profile": "https://wordpress.stackexchange.com/users/69626",
"pm_score": 0,
"selected": false,
"text": "<p>There is issue in your JS code and the html that you are not calling your JS function. </p>\n\n<p>Try this code : </p>\n\n<p><a href=\"http://codepen.io/anon/pen/pjYRex\" rel=\"nofollow\">http://codepen.io/anon/pen/pjYRex</a></p>\n\n<p>Put script in header.php and user HTML in post editor.</p>\n\n<p>PS: Its good practice to enquee the script properly so it goes in footer.</p>\n"
},
{
"answer_id": 209076,
"author": "Mateusz Marchel",
"author_id": 83704,
"author_profile": "https://wordpress.stackexchange.com/users/83704",
"pm_score": 2,
"selected": true,
"text": "<p>You have a typo in <code>onkeyup=\"myfunction()\"</code>. Your function is named myFunction, not myfunction (function names are case sensitive).</p>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209069",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83782/"
] |
I have this code:
```
Search: <input type="text" id="fname" onkeyup="myfunction()">
<a id="sear" href="" target="_blank">Search</a>
<script>
function myFunction() {
var x = document.getElementById("fname").value;
var url = "https://www.google.co.in/search?q=all+"+x+"&biw=1366&bih=643&source=lnms&tbm=isch";
document.getElementById("sear").href=url;
}
</script>
```
I have implemented this in WordPress and the link is now pointing to the same page rather than opening the google search page.
|
You have a typo in `onkeyup="myfunction()"`. Your function is named myFunction, not myfunction (function names are case sensitive).
|
209,089 |
<p>I want to show 8 recent products from multiple authors on the frontpage.
Need to show 1 recent product per author.</p>
<p>Currently i'm using basic wp query to show recent 8 products. </p>
<pre><code>$args = array (
'post_type' => array( 'product' ),
'posts_per_page' => '8',
'order' => 'DESC',
'orderby' => 'date',
);
// The Query
$query = new WP_Query( $args );
</code></pre>
<p>What's the best way to achieve this?</p>
|
[
{
"answer_id": 209092,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 4,
"selected": true,
"text": "<p>I believe that you can achieve this effect by grouping the query by author ID, which will require a filter(<a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_groupby\" rel=\"noreferrer\">mostly cribbed from the Codex</a>):</p>\n\n<pre><code>function my_posts_groupby($groupby) {\n global $wpdb;\n $groupby = \"{$wpdb->posts}.post_author\";\n return $groupby;\n}\nadd_filter( 'posts_groupby', 'my_posts_groupby' );\n</code></pre>\n\n<p>If you have less than 8 authors, however, this won't work. (You will get a number of results equal to your number of authors.) If that is the case you will need much more complicated logic and a much more complicated code.</p>\n"
},
{
"answer_id": 378681,
"author": "Sean Doherty",
"author_id": 162004,
"author_profile": "https://wordpress.stackexchange.com/users/162004",
"pm_score": 1,
"selected": false,
"text": "<p>Anyone coming to this years after the fact and would like the code in full, rather than having to piece this together from comments and the accepted answer, here you go!</p>\n<p><strong>Declare the function that limits the post results to 1 per author</strong>. For me, this was in functions.php:</p>\n<pre><code>function one_per_author($groupby) {\n global $wpdb;\n $groupby = "{$wpdb->posts}.post_author";\n return $groupby;\n}\n</code></pre>\n<p>Do NOT follow this with <code>apply_filter</code> as per the accepted answer - this would then apply to all loops.</p>\n<p><strong>Next run the loop you would like to filter</strong>, and call the <code>apply</code> and <code>remove</code> filters directly before and after it:</p>\n<pre><code>$args = array (\n'post_type' => array( 'product' ),\n'posts_per_page' => '8',\n'order' => 'DESC',\n'orderby' => 'date',\n);\n\nadd_filter( 'posts_groupby', 'one_per_author' );\n$query = new WP_Query( $args );\nif ( $query->have_posts() ) :\n while ( $query->have_posts() ) : $query->the_post();\n // Do loop stuff\n endwhile;\nendif;\nremove_filter( 'posts_groupby', 'one_per_author' );\n</code></pre>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209089",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/77725/"
] |
I want to show 8 recent products from multiple authors on the frontpage.
Need to show 1 recent product per author.
Currently i'm using basic wp query to show recent 8 products.
```
$args = array (
'post_type' => array( 'product' ),
'posts_per_page' => '8',
'order' => 'DESC',
'orderby' => 'date',
);
// The Query
$query = new WP_Query( $args );
```
What's the best way to achieve this?
|
I believe that you can achieve this effect by grouping the query by author ID, which will require a filter([mostly cribbed from the Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/posts_groupby)):
```
function my_posts_groupby($groupby) {
global $wpdb;
$groupby = "{$wpdb->posts}.post_author";
return $groupby;
}
add_filter( 'posts_groupby', 'my_posts_groupby' );
```
If you have less than 8 authors, however, this won't work. (You will get a number of results equal to your number of authors.) If that is the case you will need much more complicated logic and a much more complicated code.
|
209,105 |
<p>I have created a custom route in WP API (v2 beta 4) to set a site option. I'm using AngularJS to make the API call, and for some reason, I'm not able to access the data sent within the request. Here is what I have so far:</p>
<pre><code>gvl.service('gvlOptionService', ['$http', function($http) {
this.updateOption = function(option, value) {
return $http({
method : 'POST',
url : wpAPIdata.gvlapi_base + 'options',
data : { "option" : option,
"value" : value
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded',
'X-WP-Nonce' : wpAPIdata.api_nonce
}
})
}
}]);
</code></pre>
<p>This successfully sends the request and the data posted looks something like this:</p>
<pre><code>{"option":"siteColor","value":"ff0000"}
</code></pre>
<p>The request successfully makes it to my custom route and to the callback that I have specified. Here is that callback function within the class:</p>
<pre><code>public function update_option( WP_REST_Request $request ) {
if(isset($request['option']) && $request['option'] == 'siteColor') {
$request_prepared = $this->prepare_item_for_database($request);
$color_updated = update_option('site_color', $request_prepared['value'], false);
if($color_updated) {
$response = $this->prepare_item_for_response('site_color');
$response->set_status( 201 );
$response->header('Location', rest_url('/gvl/v1/options'));
return $response;
} else {
// ...
}
} else {
return new WP_Error( 'cant_update_option', __( 'Cannot update option.' ), array( 'status' => 400 ) );
}
}
</code></pre>
<p>The problem is that this always fails and returns the WP_Error because $request['option'] is null.</p>
<p>When I var_dump($request), I see the JSON string in the ['body'] portion of the object, but it won't let me access that when calling that portion of the array. I've also tried using the methods for retrieving parameters noted in the documentation (<a href="http://v2.wp-api.org/extending/adding/" rel="noreferrer">http://v2.wp-api.org/extending/adding/</a>), but none of those seem to return the data either. Am I missing something really basic here?</p>
|
[
{
"answer_id": 212119,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 3,
"selected": false,
"text": "<p>In a <a href=\"https://wordpress.stackexchange.com/questions/210597/query-wp-rest-api-v2-by-multiple-meta-keys/212113#212113\">previous answer</a> is was able to access the data in a <a href=\"http://v2.wp-api.org/extending/adding/\" rel=\"nofollow noreferrer\">custom endpoint</a> using</p>\n<pre><code>$parameters = $request->get_query_params(); \n</code></pre>\n<p>Check the query params for <code>option</code></p>\n<pre><code>$parameters['option']\n</code></pre>\n<p>Two options for getting the body of the request:</p>\n<pre><code>$body = $request->get_body();\n\n$body_params = $request->get_body_params();\n</code></pre>\n<h2>Example</h2>\n<pre><code><?php\nfunction my_awesome_func( WP_REST_Request $request ) {\n\n // Two ways to get the body from the request.\n $body = $request->get_body();\n $body_params = $request->get_body_params();\n\n // You can access parameters via direct array access on the object:\n $param = $request['some_param'];\n\n // Or via the helper method:\n $param = $request->get_param( 'some_param' );\n\n // You can get the combined, merged set of parameters:\n $parameters = $request->get_params();\n\n // The individual sets of parameters are also available, if needed:\n $parameters = $request->get_url_params();\n $parameters = $request->get_query_params();\n $parameters = $request->get_default_params();\n\n // Uploads aren't merged in, but can be accessed separately:\n $parameters = $request->get_file_params();\n}\n</code></pre>\n"
},
{
"answer_id": 260428,
"author": "Gerardlamo",
"author_id": 115619,
"author_profile": "https://wordpress.stackexchange.com/users/115619",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <code>$request->get_body()</code></p>\n"
},
{
"answer_id": 330297,
"author": "mkly",
"author_id": 162255,
"author_profile": "https://wordpress.stackexchange.com/users/162255",
"pm_score": 3,
"selected": false,
"text": "<p>You can use <code>$request->get_json_params()</code> which will return an array of key => values.</p>\n\n<p>With these conditions(possibly a few more):</p>\n\n<ol>\n<li>The client sending the request has <code>Content-Type: application/json</code> in the header</li>\n<li>There is a raw body like <code>{\"option\":\"siteColor\",\"value\":\"ff0000\"}</code>.</li>\n</ol>\n\n<p><a href=\"https://developer.wordpress.org/reference/classes/wp_rest_request/get_json_params/\" rel=\"noreferrer\">https://developer.wordpress.org/reference/classes/wp_rest_request/get_json_params/</a></p>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83856/"
] |
I have created a custom route in WP API (v2 beta 4) to set a site option. I'm using AngularJS to make the API call, and for some reason, I'm not able to access the data sent within the request. Here is what I have so far:
```
gvl.service('gvlOptionService', ['$http', function($http) {
this.updateOption = function(option, value) {
return $http({
method : 'POST',
url : wpAPIdata.gvlapi_base + 'options',
data : { "option" : option,
"value" : value
},
headers : { 'Content-Type': 'application/x-www-form-urlencoded',
'X-WP-Nonce' : wpAPIdata.api_nonce
}
})
}
}]);
```
This successfully sends the request and the data posted looks something like this:
```
{"option":"siteColor","value":"ff0000"}
```
The request successfully makes it to my custom route and to the callback that I have specified. Here is that callback function within the class:
```
public function update_option( WP_REST_Request $request ) {
if(isset($request['option']) && $request['option'] == 'siteColor') {
$request_prepared = $this->prepare_item_for_database($request);
$color_updated = update_option('site_color', $request_prepared['value'], false);
if($color_updated) {
$response = $this->prepare_item_for_response('site_color');
$response->set_status( 201 );
$response->header('Location', rest_url('/gvl/v1/options'));
return $response;
} else {
// ...
}
} else {
return new WP_Error( 'cant_update_option', __( 'Cannot update option.' ), array( 'status' => 400 ) );
}
}
```
The problem is that this always fails and returns the WP\_Error because $request['option'] is null.
When I var\_dump($request), I see the JSON string in the ['body'] portion of the object, but it won't let me access that when calling that portion of the array. I've also tried using the methods for retrieving parameters noted in the documentation (<http://v2.wp-api.org/extending/adding/>), but none of those seem to return the data either. Am I missing something really basic here?
|
In a [previous answer](https://wordpress.stackexchange.com/questions/210597/query-wp-rest-api-v2-by-multiple-meta-keys/212113#212113) is was able to access the data in a [custom endpoint](http://v2.wp-api.org/extending/adding/) using
```
$parameters = $request->get_query_params();
```
Check the query params for `option`
```
$parameters['option']
```
Two options for getting the body of the request:
```
$body = $request->get_body();
$body_params = $request->get_body_params();
```
Example
-------
```
<?php
function my_awesome_func( WP_REST_Request $request ) {
// Two ways to get the body from the request.
$body = $request->get_body();
$body_params = $request->get_body_params();
// You can access parameters via direct array access on the object:
$param = $request['some_param'];
// Or via the helper method:
$param = $request->get_param( 'some_param' );
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
// The individual sets of parameters are also available, if needed:
$parameters = $request->get_url_params();
$parameters = $request->get_query_params();
$parameters = $request->get_default_params();
// Uploads aren't merged in, but can be accessed separately:
$parameters = $request->get_file_params();
}
```
|
209,109 |
<p>I'm trying to update a custom field after a post thumbnail (Featured Image) is either added or removed from a post. The aim of this is to keep track of whether a featured image has been added or removed in order to do a synchronised export of only the updated 'dirty' posts for use in an external service.</p>
<p>I've looked throughout the codex for a hook that would be triggered after a post_thumbnail is set but I haven't been able to find anything. The solution I'd hoped would work was to use the slimly documented 'updated_post_meta' action (not to be confused with 'update_post_meta'!), using the following code:</p>
<pre><code>add_action('updated_post_meta', 'check_dirty_fields_updated_post_meta', 10, 4);
function check_dirty_fields_updated_post_meta($meta_id, $post_id, $meta_key, $meta_value) {
if ('_thumbnail_id' == $meta_key) {
update_post_meta($post_id, 'thumbnails_dirty', 1);
}
if ('schedule' == $meta_key) {
update_post_meta($post_id, 'schedule_dirty', 1);
}
}
</code></pre>
<p>So, 'updated_post_meta' should be triggered whenever post_meta is updated, but unfortunately '_thumbnail_id' never gets triggered so the 'thumbnails_dirty' custom field that I subsequently want to set doesn't get updated. </p>
<p>You'll see from that code that I'm also checking to see if a meta_key of 'schedule' is ever updated and then marking another custom field called 'schedule_dirty' (the 'schedule' post_meta value is a custom field that gets set within the standard post UI) In the case of this more standard custom field the 'updated_post_meta' action does see it when it's updated and set the 'schedule_dirty' as intended.</p>
<p>The problem I have is that I can't see why the '_thumbnail_id' post_meta isn't triggering the 'updated_post_meta' action. </p>
<p>Compounding the problem further I just can't find any clear documentation on when the post thumbnail is set and subsequently updating it's related '_thumbnail_id' post_meta field. I note that when setting the Featured Image on a post that this is set straight away and therefore does not seem to be dependent on the 'save_post' action, so whilst I have looked through various aspects related to saving posts I think the answer lies elsewhere.</p>
<p>A few other bits of info that might be relevant to know:</p>
<ul>
<li><p>The posts in question here are a custom post type</p></li>
<li><p>I'm also using the <a href="https://wordpress.org/plugins/multiple-post-thumbnails/" rel="nofollow">Multiple Post Thumbnails plugin</a> and
subsequently want to check for the updated state of these additional
post thumbnails too.</p></li>
</ul>
|
[
{
"answer_id": 209967,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I think you want to use the <code>added_post_meta</code> hook instead of <code>updated_post_meta</code> because you're not updating the meta here, only adding it. At least in the case of the <code>_thumbnail_id</code>, where we must delete it before adding it again (no update) through the admin UI.</p>\n\n<p>Investigating this further we see that this part of the <code>update_metadata()</code> function:</p>\n\n<pre><code>if ( empty( $meta_ids ) ) {\n return add_metadata($meta_type, $object_id, $meta_key, $passed_value);\n}\n</code></pre>\n\n<p>is causing you the problem, because it calls <code>add_metadata()</code> and returns it, before the <code>update_{$meta_type}_meta</code> and <code>updated_{$meta_type}_meta</code> hooks are ever fired.</p>\n\n<p>You therefore need to hook into the <code>add_metadata()</code> function, instead of the <code>update_metadata()</code> function, through e.g. the <code>add_{$meta_type}_meta</code> (<em>before</em>) or <code>added_{$meta_type}_meta</code> (<em>after</em>) hooks.</p>\n\n<p>If we check out the <code>wp_ajax_set_post_thumbnail()</code> function, that's ajax-requested from the admin UI when adding/removing the featured image, we see that it uses the functions \n<code>set_post_thumbnail()</code> and <code>delete_post_thumbnail()</code>.</p>\n\n<p>The latter one is a wrapper for <code>delete_metadata()</code>, that fires up the <code>delete_{$meta_type}_meta</code> (<em>before</em>) and <code>deleted_{$meta_type}_meta</code> (<em>after</em>) hooks.</p>\n"
},
{
"answer_id": 210091,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 1,
"selected": false,
"text": "<p>This is a working example that hooks into the add / remove events for a post thumbnail. It also includes the meta key required for the Secondary thumbnail created by the MultiPostThumbnail. Help for this solution came from <a href=\"https://wordpress.stackexchange.com/questions/16835/how-to-hook-update-post-meta-and-delete-post-meta\">here</a> and the MultiPostThumbnail docs. birgire gives a good explanation about these hooks in the accepted answer. </p>\n\n<pre><code>// Initialize the MultiPostThumbnails based on https://github.com/voceconnect/multi-post-thumbnails/wiki\n\nif (class_exists('MultiPostThumbnails')) {\n new MultiPostThumbnails(\n array(\n 'label' => 'Secondary Image',\n 'id' => 'secondary-image',\n 'post_type' => 'post'\n )\n );\n}\n\n// Listen for Updates\n\nadd_action( 'added_post_meta', '___after_post_meta', 10, 4 );\nadd_action( 'updated_post_meta', '___after_post_meta', 10, 4 );\n\nfunction ___after_post_meta( $meta_id, $post_id, $meta_key, $meta_value )\n{\n if( $meta_key === '_thumbnail_id' ){\n\n // Primary Thumbnail Added\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n\n } else if ( $meta_key === 'post_secondary-image_thumbnail_id' ) {\n\n // Secondary Thumbnail Added\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n } \n}\n\nadd_action( 'deleted_post_meta', '___deleted_post_meta', 10, 4 );\n\nfunction ___deleted_post_meta ( $deleted_meta_ids, $post_id, $meta_key, $only_delete_these_meta_values )\n{\n if( $meta_key === '_thumbnail_id'){\n\n // Primary Thumbnail Deleted\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n\n } else if ( $meta_key === 'post_secondary-image_thumbnail_id' ) {\n\n // Secondary Thumbnail Deleted\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n } \n}\n</code></pre>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/184/"
] |
I'm trying to update a custom field after a post thumbnail (Featured Image) is either added or removed from a post. The aim of this is to keep track of whether a featured image has been added or removed in order to do a synchronised export of only the updated 'dirty' posts for use in an external service.
I've looked throughout the codex for a hook that would be triggered after a post\_thumbnail is set but I haven't been able to find anything. The solution I'd hoped would work was to use the slimly documented 'updated\_post\_meta' action (not to be confused with 'update\_post\_meta'!), using the following code:
```
add_action('updated_post_meta', 'check_dirty_fields_updated_post_meta', 10, 4);
function check_dirty_fields_updated_post_meta($meta_id, $post_id, $meta_key, $meta_value) {
if ('_thumbnail_id' == $meta_key) {
update_post_meta($post_id, 'thumbnails_dirty', 1);
}
if ('schedule' == $meta_key) {
update_post_meta($post_id, 'schedule_dirty', 1);
}
}
```
So, 'updated\_post\_meta' should be triggered whenever post\_meta is updated, but unfortunately '\_thumbnail\_id' never gets triggered so the 'thumbnails\_dirty' custom field that I subsequently want to set doesn't get updated.
You'll see from that code that I'm also checking to see if a meta\_key of 'schedule' is ever updated and then marking another custom field called 'schedule\_dirty' (the 'schedule' post\_meta value is a custom field that gets set within the standard post UI) In the case of this more standard custom field the 'updated\_post\_meta' action does see it when it's updated and set the 'schedule\_dirty' as intended.
The problem I have is that I can't see why the '\_thumbnail\_id' post\_meta isn't triggering the 'updated\_post\_meta' action.
Compounding the problem further I just can't find any clear documentation on when the post thumbnail is set and subsequently updating it's related '\_thumbnail\_id' post\_meta field. I note that when setting the Featured Image on a post that this is set straight away and therefore does not seem to be dependent on the 'save\_post' action, so whilst I have looked through various aspects related to saving posts I think the answer lies elsewhere.
A few other bits of info that might be relevant to know:
* The posts in question here are a custom post type
* I'm also using the [Multiple Post Thumbnails plugin](https://wordpress.org/plugins/multiple-post-thumbnails/) and
subsequently want to check for the updated state of these additional
post thumbnails too.
|
I think you want to use the `added_post_meta` hook instead of `updated_post_meta` because you're not updating the meta here, only adding it. At least in the case of the `_thumbnail_id`, where we must delete it before adding it again (no update) through the admin UI.
Investigating this further we see that this part of the `update_metadata()` function:
```
if ( empty( $meta_ids ) ) {
return add_metadata($meta_type, $object_id, $meta_key, $passed_value);
}
```
is causing you the problem, because it calls `add_metadata()` and returns it, before the `update_{$meta_type}_meta` and `updated_{$meta_type}_meta` hooks are ever fired.
You therefore need to hook into the `add_metadata()` function, instead of the `update_metadata()` function, through e.g. the `add_{$meta_type}_meta` (*before*) or `added_{$meta_type}_meta` (*after*) hooks.
If we check out the `wp_ajax_set_post_thumbnail()` function, that's ajax-requested from the admin UI when adding/removing the featured image, we see that it uses the functions
`set_post_thumbnail()` and `delete_post_thumbnail()`.
The latter one is a wrapper for `delete_metadata()`, that fires up the `delete_{$meta_type}_meta` (*before*) and `deleted_{$meta_type}_meta` (*after*) hooks.
|
209,128 |
<p>Can you please let me know how I can add a class to an image getting from Post Content?
I have a page called <code>promotion</code> and it only contains an image which I uploaded through <code>Add Media</code> now in page I have </p>
<pre><code><div class="container">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php endif; ?>
</div>
</code></pre>
<p>and at front end I am getting this:</p>
<pre><code><img class="size-full wp-image-2202 alignright" src="http://rumioptical.com/wp-content/uploads/2014/11/Promotion-Banner.jpg" alt="Promotion Banner" width="800" height="640">
</code></pre>
<p>but I need only to get</p>
<pre><code><img class="img-responsive" src="http://rumioptical.com/wp-content/uploads/2014/11/Promotion-Banner.jpg" alt="Promotion">
</code></pre>
<p>removing the <code>size-full wp-image-2202 alignright</code> classes and <code>width</code> and <code>height</code> attributes and adding the <code>img-responsive</code> class?</p>
|
[
{
"answer_id": 209967,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 3,
"selected": true,
"text": "<p>I think you want to use the <code>added_post_meta</code> hook instead of <code>updated_post_meta</code> because you're not updating the meta here, only adding it. At least in the case of the <code>_thumbnail_id</code>, where we must delete it before adding it again (no update) through the admin UI.</p>\n\n<p>Investigating this further we see that this part of the <code>update_metadata()</code> function:</p>\n\n<pre><code>if ( empty( $meta_ids ) ) {\n return add_metadata($meta_type, $object_id, $meta_key, $passed_value);\n}\n</code></pre>\n\n<p>is causing you the problem, because it calls <code>add_metadata()</code> and returns it, before the <code>update_{$meta_type}_meta</code> and <code>updated_{$meta_type}_meta</code> hooks are ever fired.</p>\n\n<p>You therefore need to hook into the <code>add_metadata()</code> function, instead of the <code>update_metadata()</code> function, through e.g. the <code>add_{$meta_type}_meta</code> (<em>before</em>) or <code>added_{$meta_type}_meta</code> (<em>after</em>) hooks.</p>\n\n<p>If we check out the <code>wp_ajax_set_post_thumbnail()</code> function, that's ajax-requested from the admin UI when adding/removing the featured image, we see that it uses the functions \n<code>set_post_thumbnail()</code> and <code>delete_post_thumbnail()</code>.</p>\n\n<p>The latter one is a wrapper for <code>delete_metadata()</code>, that fires up the <code>delete_{$meta_type}_meta</code> (<em>before</em>) and <code>deleted_{$meta_type}_meta</code> (<em>after</em>) hooks.</p>\n"
},
{
"answer_id": 210091,
"author": "jgraup",
"author_id": 84219,
"author_profile": "https://wordpress.stackexchange.com/users/84219",
"pm_score": 1,
"selected": false,
"text": "<p>This is a working example that hooks into the add / remove events for a post thumbnail. It also includes the meta key required for the Secondary thumbnail created by the MultiPostThumbnail. Help for this solution came from <a href=\"https://wordpress.stackexchange.com/questions/16835/how-to-hook-update-post-meta-and-delete-post-meta\">here</a> and the MultiPostThumbnail docs. birgire gives a good explanation about these hooks in the accepted answer. </p>\n\n<pre><code>// Initialize the MultiPostThumbnails based on https://github.com/voceconnect/multi-post-thumbnails/wiki\n\nif (class_exists('MultiPostThumbnails')) {\n new MultiPostThumbnails(\n array(\n 'label' => 'Secondary Image',\n 'id' => 'secondary-image',\n 'post_type' => 'post'\n )\n );\n}\n\n// Listen for Updates\n\nadd_action( 'added_post_meta', '___after_post_meta', 10, 4 );\nadd_action( 'updated_post_meta', '___after_post_meta', 10, 4 );\n\nfunction ___after_post_meta( $meta_id, $post_id, $meta_key, $meta_value )\n{\n if( $meta_key === '_thumbnail_id' ){\n\n // Primary Thumbnail Added\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n\n } else if ( $meta_key === 'post_secondary-image_thumbnail_id' ) {\n\n // Secondary Thumbnail Added\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n } \n}\n\nadd_action( 'deleted_post_meta', '___deleted_post_meta', 10, 4 );\n\nfunction ___deleted_post_meta ( $deleted_meta_ids, $post_id, $meta_key, $only_delete_these_meta_values )\n{\n if( $meta_key === '_thumbnail_id'){\n\n // Primary Thumbnail Deleted\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n\n } else if ( $meta_key === 'post_secondary-image_thumbnail_id' ) {\n\n // Secondary Thumbnail Deleted\n update_post_meta($post_id, 'thumbnails_dirty', 1);\n } \n}\n</code></pre>\n"
}
] |
2015/11/18
|
[
"https://wordpress.stackexchange.com/questions/209128",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/31793/"
] |
Can you please let me know how I can add a class to an image getting from Post Content?
I have a page called `promotion` and it only contains an image which I uploaded through `Add Media` now in page I have
```
<div class="container">
<?php if ( have_posts() ) : ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php the_content(); ?>
<?php endwhile; ?>
<?php endif; ?>
</div>
```
and at front end I am getting this:
```
<img class="size-full wp-image-2202 alignright" src="http://rumioptical.com/wp-content/uploads/2014/11/Promotion-Banner.jpg" alt="Promotion Banner" width="800" height="640">
```
but I need only to get
```
<img class="img-responsive" src="http://rumioptical.com/wp-content/uploads/2014/11/Promotion-Banner.jpg" alt="Promotion">
```
removing the `size-full wp-image-2202 alignright` classes and `width` and `height` attributes and adding the `img-responsive` class?
|
I think you want to use the `added_post_meta` hook instead of `updated_post_meta` because you're not updating the meta here, only adding it. At least in the case of the `_thumbnail_id`, where we must delete it before adding it again (no update) through the admin UI.
Investigating this further we see that this part of the `update_metadata()` function:
```
if ( empty( $meta_ids ) ) {
return add_metadata($meta_type, $object_id, $meta_key, $passed_value);
}
```
is causing you the problem, because it calls `add_metadata()` and returns it, before the `update_{$meta_type}_meta` and `updated_{$meta_type}_meta` hooks are ever fired.
You therefore need to hook into the `add_metadata()` function, instead of the `update_metadata()` function, through e.g. the `add_{$meta_type}_meta` (*before*) or `added_{$meta_type}_meta` (*after*) hooks.
If we check out the `wp_ajax_set_post_thumbnail()` function, that's ajax-requested from the admin UI when adding/removing the featured image, we see that it uses the functions
`set_post_thumbnail()` and `delete_post_thumbnail()`.
The latter one is a wrapper for `delete_metadata()`, that fires up the `delete_{$meta_type}_meta` (*before*) and `deleted_{$meta_type}_meta` (*after*) hooks.
|
209,183 |
<p>I'm using a custom meta field, to specify which post will appear as a featured one in the front page.</p>
<p>This meta field is a true/false value, declared through ACF.</p>
<p>I want this condition to only be applied to one post, i.e. when the user declares a post as "featured", and saves it, all the other ones (theoretically only the last one) that have this meta value checked, should be turned "off".</p>
<p>To achieve this, I've declared a function attached to the "save_post" action, that turns to "false" this specific post meta value, for the older featured posts.</p>
<p>This is my approximation, but there's something that I'm missing, because it is not working at all.</p>
<pre><code>function only_one_agenda_featured( $post_id ) {
// If this isn't a 'agenda' post, don't update it.
if ( 'agenda' != $post->post_type ) {
return;
}
// Stop when it is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Prevent quick edit from clearing custom fields
if (defined('DOING_AJAX') && DOING_AJAX) {
return;
}
$post_meta_value = get_post_meta( $post_id, 'agenda_featured', TRUE );
if ( $post_meta_value == '1' ) {
$args = array(
'meta_key' => 'agenda_featured',
'meta_value' => '1',
'post_type' => 'agenda',
'post__not_in' => array($post_id),
);
$posts_to_update = get_posts( $args );
foreach ( $posts_to_update as $post_to_update ) {
update_post_meta( $post_to_update->ID, 'agenda_featured', '0', '1' );
}
}
}
add_action( 'save_post', 'only_one_agenda_featured' );
</code></pre>
<p>Any help will be appreciated.</p>
|
[
{
"answer_id": 209187,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<blockquote>\n <p>I want this condition to only be applied to one post, i.e. when the\n user declares a post as \"featured\", and saves it, all the other ones\n (theoretically only the last one) that have this meta value checked,\n should be turned \"off\".</p>\n</blockquote>\n\n<p>You might then try to save the one and only featured post ID as an <em>option</em> instead.</p>\n\n<p>Then you don't need to pollute the post meta table with multiple <em>false</em> values.</p>\n"
},
{
"answer_id": 209198,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>The first problem is that <code>$post</code> is not in scope in your callback. You need to alter the code to pull that in:</p>\n\n<pre><code>function only_one_agenda_featured( $post_id, $post ) {\n // ...\n}\nadd_action( 'save_post', 'only_one_agenda_featured' ,10, 2);\n</code></pre>\n\n<p>Given that change, things should work better, but the code is overly complicated. Unless you need a history of old <code>agenda_featured</code> posts, all you need to do is delete the old field and then set the new one.</p>\n\n<pre><code>function only_one_agenda_featured( $post_id, $post ) {\n\n // If this isn't a 'agenda' post, don't update it.\n if ( 'agenda' != $post->post_type ) {\n return;\n }\n\n // Stop when it is an autosave\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {\n return;\n }\n\n // Prevent quick edit from clearing custom fields\n if (defined('DOING_AJAX') && DOING_AJAX) {\n return;\n }\n\n if (!empty($_POST['agenda_featured']) && true == $_POST['agenda_featured']) {\n // delete\n delete_metadata ( 'agenda', null, 'agenda_featured', null, true );\n // and insert\n add_post_meta( $post_id, 'agenda_featured', true);\n }\n\n}\nadd_action( 'save_post', 'only_one_agenda_featured' ,10, 2);\n</code></pre>\n\n<p>You can further simplify that by using a <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/post.php#L3580\" rel=\"nofollow\">post-type specific hook</a>:</p>\n\n<pre><code>3580 do_action( \"save_post_{$post->post_type}\", $post_ID, $post, $update );\n</code></pre>\n\n<p>Something like:</p>\n\n<pre><code>function only_one_agenda_featured( $post_id, $post ) {\n\n // Stop when it is an autosave\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {\n return;\n }\n\n // Prevent quick edit from clearing custom fields\n if (defined('DOING_AJAX') && DOING_AJAX) {\n return;\n }\n\n if (!empty($_POST['agenda_featured']) && true == $_POST['agenda_featured']) {\n // delete\n delete_metadata ( 'agenda', null, 'agenda_featured', null, true );\n // and insert\n add_post_meta( $post_id, 'agenda_featured', true);\n }\n\n}\nadd_action( 'save_post_agenda', 'only_one_agenda_featured' ,10, 2);\n</code></pre>\n\n<p>You could make the delete/save a bit more efficient with straight SQL but I stuck to Core functions like a good boy ;)</p>\n"
},
{
"answer_id": 341876,
"author": "GigiSan",
"author_id": 107437,
"author_profile": "https://wordpress.stackexchange.com/users/107437",
"pm_score": 0,
"selected": false,
"text": "<p>I apologize for resuming this old post, but I had a very similar need and investigated a bit on the answers posted here. Since I found a working way, let me share it.</p>\n\n<p>My need was that only one post of type <code>question</code> had the <code>first_question</code> ACF flag checked. An answer suggests bringing it to options, but I needed that flag to control the visibility of other ACF fields.</p>\n\n<p>The code I came up with for my solution is the following:</p>\n\n<pre><code>function update_first_question( $post_id ) {\n\n // If it's not the correct post type\n $post = get_post( $post_id );\n if ( $post->post_type != 'question' ) {\n return;\n }\n // Stop when it is an autosave\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {\n return;\n }\n // Prevent quick edit from clearing custom fields\n if (defined('DOING_AJAX') && DOING_AJAX) {\n return;\n }\n\n // Check if the post being saved has first_question checked\n if (!empty($_POST['acf']['field_5d19b7f96cb7f']) && $_POST['acf']['field_5d19b7f96cb7f'] == TRUE) {\n\n // Delete 'first_question' meta from all posts\n delete_metadata ( 'post', NULL, 'first_question', NULL, TRUE );\n\n // Set 'first_question' meta for the post bring saved\n add_post_meta( $post_id, 'first_question', TRUE);\n\n }\n\n}\nadd_action( 'acf/save_post', 'update_first_question', 5, 2);\n</code></pre>\n\n<p>What changes from the answers posted?</p>\n\n<ul>\n<li><code>delete_metadata</code> does not accept a custom post type, so it must be called with <code>'post'</code></li>\n<li>When checking the <code>$_POST</code> array, you have to check the <code>acf</code> array with the field key in order to check its value</li>\n<li>Since we're working with ACF fields it's better to hook it to <code>acf/save_post</code> in order to have the ACF values in <code>$_POST</code>. The hooked function should have a priority less than 10, to work with the value BEFORE being saved.</li>\n<li>The above hook does not provide <code>$post</code>, so it must be retrieved by <code>$post_id</code></li>\n</ul>\n\n<p>So to answer the question, let me elaborate from <a href=\"https://wordpress.stackexchange.com/a/209198/107437\">s_ha_dum's answer</a>. What you need is the following:</p>\n\n<pre><code>function only_one_agenda_featured( $post_id ) {\n\n // If it's not the correct post type\n $post = get_post( $post_id );\n if ( $post->post_type != 'agenda' ) {\n return;\n }\n // Stop when it is an autosave\n if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {\n return;\n }\n // Prevent quick edit from clearing custom fields\n if (defined('DOING_AJAX') && DOING_AJAX) {\n return;\n }\n\n // Check if agenda_featured is being checked \n if (!empty($_POST['acf']['field_562100c6cd7ad']) && $_POST['acf']['field_562100c6cd7ad'] == TRUE) {\n // delete\n delete_metadata ( 'post', NULL, 'agenda_featured', NULL, TRUE );\n // and insert\n add_post_meta( $post_id, 'agenda_featured', TRUE);\n }\n\n}\nadd_action( 'acf/save_post', 'only_one_agenda_featured' , 5, 2); \n</code></pre>\n\n<p>It probably won't help the OP 3 years after, but I hope it will help someone!\nHave a nice day!</p>\n"
}
] |
2015/11/19
|
[
"https://wordpress.stackexchange.com/questions/209183",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/39150/"
] |
I'm using a custom meta field, to specify which post will appear as a featured one in the front page.
This meta field is a true/false value, declared through ACF.
I want this condition to only be applied to one post, i.e. when the user declares a post as "featured", and saves it, all the other ones (theoretically only the last one) that have this meta value checked, should be turned "off".
To achieve this, I've declared a function attached to the "save\_post" action, that turns to "false" this specific post meta value, for the older featured posts.
This is my approximation, but there's something that I'm missing, because it is not working at all.
```
function only_one_agenda_featured( $post_id ) {
// If this isn't a 'agenda' post, don't update it.
if ( 'agenda' != $post->post_type ) {
return;
}
// Stop when it is an autosave
if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
return;
}
// Prevent quick edit from clearing custom fields
if (defined('DOING_AJAX') && DOING_AJAX) {
return;
}
$post_meta_value = get_post_meta( $post_id, 'agenda_featured', TRUE );
if ( $post_meta_value == '1' ) {
$args = array(
'meta_key' => 'agenda_featured',
'meta_value' => '1',
'post_type' => 'agenda',
'post__not_in' => array($post_id),
);
$posts_to_update = get_posts( $args );
foreach ( $posts_to_update as $post_to_update ) {
update_post_meta( $post_to_update->ID, 'agenda_featured', '0', '1' );
}
}
}
add_action( 'save_post', 'only_one_agenda_featured' );
```
Any help will be appreciated.
|
>
> I want this condition to only be applied to one post, i.e. when the
> user declares a post as "featured", and saves it, all the other ones
> (theoretically only the last one) that have this meta value checked,
> should be turned "off".
>
>
>
You might then try to save the one and only featured post ID as an *option* instead.
Then you don't need to pollute the post meta table with multiple *false* values.
|
209,201 |
<p>djeddiedavid.info</p>
<p>this is my website i want to remove a date that show on wordpress posts anyone help me ?</p>
<p><a href="https://i.stack.imgur.com/5Rhn7.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5Rhn7.jpg" alt="enter image description here"></a></p>
<p>date that show on the bottom of DJ upcoming event </p>
|
[
{
"answer_id": 209203,
"author": "Tomme",
"author_id": 83919,
"author_profile": "https://wordpress.stackexchange.com/users/83919",
"pm_score": 0,
"selected": false,
"text": "<p>Based of the theme Twenty Fifteen and other popular ones, simply adding <code>.entry-date { display: none; }</code> to your stylesheet should hide the date.</p>\n"
},
{
"answer_id": 209204,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>You can try a filter on <code>get_the_date</code> but it is likely there will be some formatting/markup left behind:</p>\n\n<pre><code>add_filter( 'get_the_date', '__return_empty_string' ); \n</code></pre>\n\n<p>Using the Core function <a href=\"https://codex.wordpress.org/Function_Reference/_return_empty_string\" rel=\"nofollow\"><code>_return_empty_string()</code></a> as a callback</p>\n"
},
{
"answer_id": 209206,
"author": "IXN",
"author_id": 80031,
"author_profile": "https://wordpress.stackexchange.com/users/80031",
"pm_score": 0,
"selected": false,
"text": "<p>Go to your index.php or whatever file is used for latest post.\nFind the <code><h4>.....</h4></code>\nJust after this is </p>\n\n<pre><code><p>...the code that adds the date and comments...<p>\n<p>...post content...</p>\n</code></pre>\n\n<p>delete or edit the <p>...the code that adds the date and comments...<p></p>\n"
},
{
"answer_id": 209207,
"author": "Ricardo Andres",
"author_id": 70093,
"author_profile": "https://wordpress.stackexchange.com/users/70093",
"pm_score": 2,
"selected": true,
"text": "<p>Try adding this to your CSS:</p>\n\n<pre><code>.latest-post h4 + p {\ndisplay: none;\n}\n</code></pre>\n"
}
] |
2015/11/19
|
[
"https://wordpress.stackexchange.com/questions/209201",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/79858/"
] |
djeddiedavid.info
this is my website i want to remove a date that show on wordpress posts anyone help me ?
[](https://i.stack.imgur.com/5Rhn7.jpg)
date that show on the bottom of DJ upcoming event
|
Try adding this to your CSS:
```
.latest-post h4 + p {
display: none;
}
```
|
209,224 |
<pre><code>function the_alt_title($title= '') {
$page = get_page_by_title($title);
if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
$title = $p;
}
return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1);
</code></pre>
<p>My theme uses something called <code>alternate index title</code> and I also have the above custom function in my <code>functions.php</code></p>
<p>I presume the <code>alternate index title</code> is recognised as a custom field in wordpress?</p>
<p>How can I call the <code>alternate index title</code> using php code on a page?</p>
|
[
{
"answer_id": 209203,
"author": "Tomme",
"author_id": 83919,
"author_profile": "https://wordpress.stackexchange.com/users/83919",
"pm_score": 0,
"selected": false,
"text": "<p>Based of the theme Twenty Fifteen and other popular ones, simply adding <code>.entry-date { display: none; }</code> to your stylesheet should hide the date.</p>\n"
},
{
"answer_id": 209204,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>You can try a filter on <code>get_the_date</code> but it is likely there will be some formatting/markup left behind:</p>\n\n<pre><code>add_filter( 'get_the_date', '__return_empty_string' ); \n</code></pre>\n\n<p>Using the Core function <a href=\"https://codex.wordpress.org/Function_Reference/_return_empty_string\" rel=\"nofollow\"><code>_return_empty_string()</code></a> as a callback</p>\n"
},
{
"answer_id": 209206,
"author": "IXN",
"author_id": 80031,
"author_profile": "https://wordpress.stackexchange.com/users/80031",
"pm_score": 0,
"selected": false,
"text": "<p>Go to your index.php or whatever file is used for latest post.\nFind the <code><h4>.....</h4></code>\nJust after this is </p>\n\n<pre><code><p>...the code that adds the date and comments...<p>\n<p>...post content...</p>\n</code></pre>\n\n<p>delete or edit the <p>...the code that adds the date and comments...<p></p>\n"
},
{
"answer_id": 209207,
"author": "Ricardo Andres",
"author_id": 70093,
"author_profile": "https://wordpress.stackexchange.com/users/70093",
"pm_score": 2,
"selected": true,
"text": "<p>Try adding this to your CSS:</p>\n\n<pre><code>.latest-post h4 + p {\ndisplay: none;\n}\n</code></pre>\n"
}
] |
2015/11/19
|
[
"https://wordpress.stackexchange.com/questions/209224",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/40727/"
] |
```
function the_alt_title($title= '') {
$page = get_page_by_title($title);
if ($p = get_post_meta($page->ID, "_x_entry_alternate_index_title", true)) {
$title = $p;
}
return $title;
}
add_filter('the_title', 'the_alt_title', 10, 1);
```
My theme uses something called `alternate index title` and I also have the above custom function in my `functions.php`
I presume the `alternate index title` is recognised as a custom field in wordpress?
How can I call the `alternate index title` using php code on a page?
|
Try adding this to your CSS:
```
.latest-post h4 + p {
display: none;
}
```
|
209,246 |
<p>I'm very new to WordPress. I've read a common problem beginners make is installing in the wrong directory. Could someone verify mine is installed correctly? I'd like to use Storefront theme with Boutique child theme. <br/></p>
<pre><code> Host1/mydomain/public_html/wp
Host1/mydomain/public_html/wp-admin
Host1/mydomain/public_html/wp-content (contains themes/boutique & themes/storefront)
Host1/mydomain/public_html/wp-includes
</code></pre>
|
[
{
"answer_id": 209203,
"author": "Tomme",
"author_id": 83919,
"author_profile": "https://wordpress.stackexchange.com/users/83919",
"pm_score": 0,
"selected": false,
"text": "<p>Based of the theme Twenty Fifteen and other popular ones, simply adding <code>.entry-date { display: none; }</code> to your stylesheet should hide the date.</p>\n"
},
{
"answer_id": 209204,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 0,
"selected": false,
"text": "<p>You can try a filter on <code>get_the_date</code> but it is likely there will be some formatting/markup left behind:</p>\n\n<pre><code>add_filter( 'get_the_date', '__return_empty_string' ); \n</code></pre>\n\n<p>Using the Core function <a href=\"https://codex.wordpress.org/Function_Reference/_return_empty_string\" rel=\"nofollow\"><code>_return_empty_string()</code></a> as a callback</p>\n"
},
{
"answer_id": 209206,
"author": "IXN",
"author_id": 80031,
"author_profile": "https://wordpress.stackexchange.com/users/80031",
"pm_score": 0,
"selected": false,
"text": "<p>Go to your index.php or whatever file is used for latest post.\nFind the <code><h4>.....</h4></code>\nJust after this is </p>\n\n<pre><code><p>...the code that adds the date and comments...<p>\n<p>...post content...</p>\n</code></pre>\n\n<p>delete or edit the <p>...the code that adds the date and comments...<p></p>\n"
},
{
"answer_id": 209207,
"author": "Ricardo Andres",
"author_id": 70093,
"author_profile": "https://wordpress.stackexchange.com/users/70093",
"pm_score": 2,
"selected": true,
"text": "<p>Try adding this to your CSS:</p>\n\n<pre><code>.latest-post h4 + p {\ndisplay: none;\n}\n</code></pre>\n"
}
] |
2015/11/19
|
[
"https://wordpress.stackexchange.com/questions/209246",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83935/"
] |
I'm very new to WordPress. I've read a common problem beginners make is installing in the wrong directory. Could someone verify mine is installed correctly? I'd like to use Storefront theme with Boutique child theme.
```
Host1/mydomain/public_html/wp
Host1/mydomain/public_html/wp-admin
Host1/mydomain/public_html/wp-content (contains themes/boutique & themes/storefront)
Host1/mydomain/public_html/wp-includes
```
|
Try adding this to your CSS:
```
.latest-post h4 + p {
display: none;
}
```
|
209,256 |
<p>I was customizing theme for some body, basically i just added a taxonomy for the custom post type client which was allready there. There were already 6 posts ,
I added like 30 more posts , set featured image ,page attributes title , selcted taxonomy term etc.</p>
<p>But suddenly now i am unable to add featured image for the posts.</p>
<p>when i try to set featured image, i am unable to see images in media library</p>
<p><a href="https://i.stack.imgur.com/QRysc.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/QRysc.png" alt="enter image description here"></a> </p>
<p>Even if i select some image after uploading or from the on already there then when i hit publish, browser keeps on processing and never stops..</p>
<p>If i go to see if the post i.e client has been saved, the post is saved but when i open but if i try to open it again i am not able to see the image.</p>
<p>So i thought may be the issue with theme. i tried switching to default theme twentyfourteen , Now i tried the same process for normal post but again i don't see any thing in media library, same as in above image</p>
<p>Never faced any problem like that, and i am on deadline. </p>
<p>May the server issue, but please help</p>
|
[
{
"answer_id": 209279,
"author": "Vig",
"author_id": 83950,
"author_profile": "https://wordpress.stackexchange.com/users/83950",
"pm_score": 1,
"selected": false,
"text": "<p>It looks like there's something wrong with the images or the media path WordPress is using to search for the files. Try taking a look at your FTP and check if the path is correct and all the files are OK.</p>\n"
},
{
"answer_id": 209280,
"author": "riteshsanap",
"author_id": 55324,
"author_profile": "https://wordpress.stackexchange.com/users/55324",
"pm_score": 2,
"selected": false,
"text": "<p>Try checking your Browsers Javascript console, Media Library in WordPress is heavily depended on javascript's such as jQuery.</p>\n\n<p>also if your Javascript is broken due to concatenation, then add the below line in your <code>wp-config.php</code> file.</p>\n\n<pre>\ndefine( 'CONCATENATE_SCRIPTS', false );\n</pre>\n\n<p>Or you can even try re-installing WordPress.</p>\n"
}
] |
2015/11/19
|
[
"https://wordpress.stackexchange.com/questions/209256",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/55034/"
] |
I was customizing theme for some body, basically i just added a taxonomy for the custom post type client which was allready there. There were already 6 posts ,
I added like 30 more posts , set featured image ,page attributes title , selcted taxonomy term etc.
But suddenly now i am unable to add featured image for the posts.
when i try to set featured image, i am unable to see images in media library
[](https://i.stack.imgur.com/QRysc.png)
Even if i select some image after uploading or from the on already there then when i hit publish, browser keeps on processing and never stops..
If i go to see if the post i.e client has been saved, the post is saved but when i open but if i try to open it again i am not able to see the image.
So i thought may be the issue with theme. i tried switching to default theme twentyfourteen , Now i tried the same process for normal post but again i don't see any thing in media library, same as in above image
Never faced any problem like that, and i am on deadline.
May the server issue, but please help
|
Try checking your Browsers Javascript console, Media Library in WordPress is heavily depended on javascript's such as jQuery.
also if your Javascript is broken due to concatenation, then add the below line in your `wp-config.php` file.
```
define( 'CONCATENATE_SCRIPTS', false );
```
Or you can even try re-installing WordPress.
|
209,275 |
<p>If I pass in <code>'style' => 'none'</code> as an argument to <code>wp_list_categories</code>, the <code><li></code> tags are removed. That's great, but <code><br></code> tags are injected. How can I remove them?</p>
|
[
{
"answer_id": 209277,
"author": "James Jones",
"author_id": 58884,
"author_profile": "https://wordpress.stackexchange.com/users/58884",
"pm_score": 1,
"selected": false,
"text": "<p>Try something like this:</p>\n\n<pre><code>$args = array( \n 'echo' => 0,\n // your other parameters\n);\necho str_replace( \"<br>\", \"\", wp_list_categories( $args ) );\n</code></pre>\n"
},
{
"answer_id": 209300,
"author": "Hans Koch",
"author_id": 82711,
"author_profile": "https://wordpress.stackexchange.com/users/82711",
"pm_score": 1,
"selected": false,
"text": "<p>Sadly i can not comment yet but James Jones is right in wp-includes/category-template.php @1103 you'll see that if the style parameter is not set it will produce a <code><br /></code> at the end of each element.</p>\n\n<p>the only thing that is not right is that it should be</p>\n\n<pre><code>str_replace( \"<br />\", \"\", wp_list_categories( $args ) );\n</code></pre>\n\n<p>alsoe keep in mind to set the parameter <code>echo</code> to false otherwise it will output the html right away.</p>\n"
},
{
"answer_id": 209302,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<h2>The new <code>separator</code> attribute of <code>wp_list_categories()</code></h2>\n\n<p>I think you are looking for the new <code>separator</code> attribute, that will be <a href=\"https://github.com/WordPress/WordPress/blob/1579e45d4199a7fe8f7bae0e49f81ba483bdf6ab/wp-includes/category-template.php#L539\" rel=\"nofollow\">introduced here in WordPress 4.4</a> that's just around the corner. I located the trac ticket here <a href=\"https://core.trac.wordpress.org/ticket/9025\" rel=\"nofollow\">#9025</a>.</p>\n\n<p>Then you can use:</p>\n\n<pre><code>$args = [\n 'style' => 'none',\n 'separator' => '', // <-- Removes the default one\n];\n\nwp_list_categories( $args );\n</code></pre>\n\n<p>where by default it's <code>'seperator' => '<br />'</code>;</p>\n\n<h2>Example:</h2>\n\n<p>We get:</p>\n\n<pre><code><a href=\"http://example.tld/category/red/\" >Red</a>\n<a href=\"http://example.tld/category/green/\" >Green</a>\n<a href=\"http://example.tld/category/blue/\" >Blue</a>\n</code></pre>\n\n<p>instead of</p>\n\n<pre><code><a href=\"http://example.tld/category/red/\" >Red</a><br />\n<a href=\"http://example.tld/category/green/\" >Green</a><br />\n<a href=\"http://example.tld/category/blue/\" >Blue</a><br />\n</code></pre>\n"
}
] |
2015/11/20
|
[
"https://wordpress.stackexchange.com/questions/209275",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/51378/"
] |
If I pass in `'style' => 'none'` as an argument to `wp_list_categories`, the `<li>` tags are removed. That's great, but `<br>` tags are injected. How can I remove them?
|
The new `separator` attribute of `wp_list_categories()`
-------------------------------------------------------
I think you are looking for the new `separator` attribute, that will be [introduced here in WordPress 4.4](https://github.com/WordPress/WordPress/blob/1579e45d4199a7fe8f7bae0e49f81ba483bdf6ab/wp-includes/category-template.php#L539) that's just around the corner. I located the trac ticket here [#9025](https://core.trac.wordpress.org/ticket/9025).
Then you can use:
```
$args = [
'style' => 'none',
'separator' => '', // <-- Removes the default one
];
wp_list_categories( $args );
```
where by default it's `'seperator' => '<br />'`;
Example:
--------
We get:
```
<a href="http://example.tld/category/red/" >Red</a>
<a href="http://example.tld/category/green/" >Green</a>
<a href="http://example.tld/category/blue/" >Blue</a>
```
instead of
```
<a href="http://example.tld/category/red/" >Red</a><br />
<a href="http://example.tld/category/green/" >Green</a><br />
<a href="http://example.tld/category/blue/" >Blue</a><br />
```
|
209,283 |
<p>I created a custom post type <code>tickets</code>, than I added few tickets in it. But with the following code, I tried to show list of tickets submitted by the current user and its not working for me. </p>
<pre><code>global $post, $paged, $current_user;
get_currentuserinfo();
if(empty($paged)) $paged = 1;
$args = array(
'post_type' => 'tickets',
'post_author' => $current_user->ID,
'paged'=> $paged
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
echo "test echo"; // testing purpose
echo "<tr><td>".the_title()."</td><td>".the_excerpt()."</td><td>".$post->post_status."</td></tr>";
endforeach;
wp_reset_postdata();
</code></pre>
<p>And its showing empty results in the table. I am not sure about similar questions. But this is my code. so please dont vote it down, if you think its not a right question. i need solution for my issues, i am breaking my head more than one hour. </p>
<p>Thank you for all of your comments, actually I found solution myself. Sometimes, we may not think a small thing can cause certain unexpected results. The problem is simple. the current user has few pending tickets. The important thing , here, if we didn't specify the <code>post_status</code>. It will assign default <code>publish</code>. So it didn't get results. </p>
|
[
{
"answer_id": 209284,
"author": "Mr Rethman",
"author_id": 27393,
"author_profile": "https://wordpress.stackexchange.com/users/27393",
"pm_score": 0,
"selected": false,
"text": "<p>Hard to say without seeing the code. But ill give it a try.\n1. ) If your not seeing any results of your published custom post type posts in the db, are you seeing them in WP Admin?\n2. ) Double check your implementation of how your defining your $paged variable, should be get_query_var( 'paged' ) ? get_query_var( 'paged' ) : 1;\n3. ) You shouldn't need either of those global vars.\n4. ) How have you setup the $current var used for author argument?</p>\n\n<p>Some more details would make easier to help.</p>\n"
},
{
"answer_id": 209295,
"author": "Kvvaradha",
"author_id": 43308,
"author_profile": "https://wordpress.stackexchange.com/users/43308",
"pm_score": 1,
"selected": false,
"text": "<p>As of @cybmeta word's, I answered my question here.</p>\n\n<p>Thank you for all of your effort. In future, if someone comes to read this article, just remember, default arguments also affecting your results. So my final working code it. </p>\n\n<pre><code> global $post, $paged, $current_user;\nget_currentuserinfo();\nif(empty($paged)) $paged = 1; \n $args = array(\n 'post_type' => 'tickets',\n 'post_author' => $current_user->ID,\n 'post_status' => 'any', \n 'paged'=> $paged\n ); \n $myposts = get_posts( $args );\n foreach( $myposts as $post ) : setup_postdata($post);\n echo \"test echo\"; // testing purpose\n echo \"<tr><td>\".the_title().\"</td><td>\".the_excerpt().\"</td><td>\".$post->post_status.\"</td></tr>\";\n endforeach; \n wp_reset_postdata();\n</code></pre>\n"
}
] |
2015/11/20
|
[
"https://wordpress.stackexchange.com/questions/209283",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/43308/"
] |
I created a custom post type `tickets`, than I added few tickets in it. But with the following code, I tried to show list of tickets submitted by the current user and its not working for me.
```
global $post, $paged, $current_user;
get_currentuserinfo();
if(empty($paged)) $paged = 1;
$args = array(
'post_type' => 'tickets',
'post_author' => $current_user->ID,
'paged'=> $paged
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
echo "test echo"; // testing purpose
echo "<tr><td>".the_title()."</td><td>".the_excerpt()."</td><td>".$post->post_status."</td></tr>";
endforeach;
wp_reset_postdata();
```
And its showing empty results in the table. I am not sure about similar questions. But this is my code. so please dont vote it down, if you think its not a right question. i need solution for my issues, i am breaking my head more than one hour.
Thank you for all of your comments, actually I found solution myself. Sometimes, we may not think a small thing can cause certain unexpected results. The problem is simple. the current user has few pending tickets. The important thing , here, if we didn't specify the `post_status`. It will assign default `publish`. So it didn't get results.
|
As of @cybmeta word's, I answered my question here.
Thank you for all of your effort. In future, if someone comes to read this article, just remember, default arguments also affecting your results. So my final working code it.
```
global $post, $paged, $current_user;
get_currentuserinfo();
if(empty($paged)) $paged = 1;
$args = array(
'post_type' => 'tickets',
'post_author' => $current_user->ID,
'post_status' => 'any',
'paged'=> $paged
);
$myposts = get_posts( $args );
foreach( $myposts as $post ) : setup_postdata($post);
echo "test echo"; // testing purpose
echo "<tr><td>".the_title()."</td><td>".the_excerpt()."</td><td>".$post->post_status."</td></tr>";
endforeach;
wp_reset_postdata();
```
|
209,338 |
<p>I have a page on my wordpresss with url <code>/sca</code>. I want all traffic from <code>/sca/project_0</code> to direct to <code>/sca?urn=project_0</code>. I added a rule to my <code>.htaccess</code> file but it is not working. I don't think this a problem with mod_rewrite as permalinks are working. Here is my <code>.htaccess</code> file:</p>
<pre><code> # BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^sca/([^/]*)$ sca/urn=$1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p><code>RewriteRule ^sca/* sca?urn=$1 [R=301,L]</code> is partly working, only that I'm not getting any parameter, it is returning <code>/sca/project_0</code> as <code>/sca?urn=</code>.</p>
|
[
{
"answer_id": 209342,
"author": "Jeff Mattson",
"author_id": 93714,
"author_profile": "https://wordpress.stackexchange.com/users/93714",
"pm_score": 0,
"selected": false,
"text": "<p>Try:</p>\n\n<pre><code> RewriteRule ^sca/([^/]*)$ sca\\?urn=$1 \n</code></pre>\n"
},
{
"answer_id": 209356,
"author": "IXN",
"author_id": 80031,
"author_profile": "https://wordpress.stackexchange.com/users/80031",
"pm_score": 1,
"selected": false,
"text": "<p>If this address already gets traffic (from inbound links etc.) why don't you try a good old fashioned redirect like this:</p>\n\n<pre><code>Redirect 301 /sca/project_0 http://www.yourdomain.com/sca?urn=project_0\n\n# 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</code></pre>\n\n<p>Or use the 301 redirect in addition to your rewrite rule:</p>\n\n<pre><code>Redirect 301 /sca/project_0 http://www.yourdomain.com/sca?urn=project_0\n\n# BEGIN WordPress\n<IfModule mod_rewrite.c>\nRewriteEngine On\nRewriteBase /\nRewriteRule ^sca/([^/]*)$ sca/urn=$1 \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>Also note that WP is often deleting additional rewrite rules inside <code>#Begin WordPress #End WordPress</code>. And sometimes rewrite rules do not behave like they should in localhost.</p>\n"
}
] |
2015/11/20
|
[
"https://wordpress.stackexchange.com/questions/209338",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/12000/"
] |
I have a page on my wordpresss with url `/sca`. I want all traffic from `/sca/project_0` to direct to `/sca?urn=project_0`. I added a rule to my `.htaccess` file but it is not working. I don't think this a problem with mod\_rewrite as permalinks are working. Here is my `.htaccess` file:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^sca/([^/]*)$ sca/urn=$1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
`RewriteRule ^sca/* sca?urn=$1 [R=301,L]` is partly working, only that I'm not getting any parameter, it is returning `/sca/project_0` as `/sca?urn=`.
|
If this address already gets traffic (from inbound links etc.) why don't you try a good old fashioned redirect like this:
```
Redirect 301 /sca/project_0 http://www.yourdomain.com/sca?urn=project_0
# 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>
```
Or use the 301 redirect in addition to your rewrite rule:
```
Redirect 301 /sca/project_0 http://www.yourdomain.com/sca?urn=project_0
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^sca/([^/]*)$ sca/urn=$1
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
Also note that WP is often deleting additional rewrite rules inside `#Begin WordPress #End WordPress`. And sometimes rewrite rules do not behave like they should in localhost.
|
209,348 |
<p>I am building a child theme for my personal use. Not very familiar with php, can only do basic things based on logic. I need to exclude one tag from being displayed on the tag list on a single post. Preferably so nothing is displayed at all when this tag is the only tag assigned to the post (I mean, no "Tags" title, nothing). </p>
<p>Here is what I have from the parent theme: </p>
<pre><code>$tags = get_the_tags( $post->ID );
$separator = ' ';
$output = '';
if($tags){
echo '<div class="entry-tags">';
echo "<p><span>" . __('Tags', 'tracks') . "</span>";
foreach($tags as $tag) {
$output .= '<a href="'.get_tag_link( $tag->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts tagged %s", 'tracks' ), $tag->name ) ) . '">'.$tag->name.'</a>'.$separator;
}
echo trim($output, $separator);
echo "</p>";
echo "</div>";
}
</code></pre>
<p>I tried applying <a href="https://wordpress.stackexchange.com/questions/45566/add-exception-for-specific-tag?rq=1">this</a> solution, but it didn't work. Probably because I don't fully understand what I'm doing. :)</p>
<p>Could someone maybe help me with this.</p>
|
[
{
"answer_id": 209349,
"author": "jas",
"author_id": 80247,
"author_profile": "https://wordpress.stackexchange.com/users/80247",
"pm_score": 2,
"selected": true,
"text": "<pre><code>$tags = get_the_tags( $post->ID );\n$separator = ' ';\n$output = '';\nif($tags){\necho '<div class=\"entry-tags\">';\n echo \"<p><span>\" . __('Tags', 'tracks') . \"</span>\";\n foreach($tags as $tag) {\n // dpm($tag) here by uncomment you can check tag slug which you want to exclude\n if($tag->slug != \"yourtag\"){ // replace yourtag with you required tag name\n $output .= '<a href=\"'.get_tag_link( $tag->term_id ).'\" title=\"' . esc_attr( sprintf( __( \"View all posts tagged %s\", 'tracks' ), $tag->name ) ) . '\">'.$tag->name.'</a>'.$separator;\n }\n }\n echo trim($output, $separator);\n echo \"</p>\";\n echo \"</div>\";\n}\n</code></pre>\n\n<p>You can apply condition that if tagname is not equal to your tag then only it will be added to out put.</p>\n\n<p>Thanks!</p>\n"
},
{
"answer_id": 209372,
"author": "s_ha_dum",
"author_id": 21376,
"author_profile": "https://wordpress.stackexchange.com/users/21376",
"pm_score": 1,
"selected": false,
"text": "<p><a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/category-template.php#L1265\" rel=\"nofollow noreferrer\"><code>get_the_tags()</code> uses <code>get_the_terms()</code></a>:</p>\n\n<pre><code>1265 return apply_filters( 'get_the_tags', get_the_terms( $id, 'post_tag' ) );\n</code></pre>\n\n<p>Which in turn <a href=\"https://core.trac.wordpress.org/browser/tags/4.3.1/src/wp-includes/category-template.php#L1372\" rel=\"nofollow noreferrer\">applies a filter</a>:</p>\n\n<pre><code>1372 $terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy );\n</code></pre>\n\n<p>You can use that filter to exclude the term(s) you wish. The answer is effectively the same as for <a href=\"https://wordpress.stackexchange.com/q/208807/21376\">this question</a>, though the sequence of function calls in Core is slightly different:</p>\n\n<pre><code>function exclude_my_term($terms, $post, $taxonomy) {\n remove_filter('get_the_terms','exclude_my_term',10,3);\n unset($terms[123]); // where 123 is the ID of the term to exclude\n return $terms;\n}\nadd_filter('get_the_terms','exclude_my_term',10,3);\n</code></pre>\n"
},
{
"answer_id": 220922,
"author": "Bernard Meisler",
"author_id": 90742,
"author_profile": "https://wordpress.stackexchange.com/users/90742",
"pm_score": 0,
"selected": false,
"text": "<p>I found a similar answer on Stack Overflow, which I think is clearer. To exclude a tag from <code>get_the_tag_list</code>, apply a filter to <code>get_terms</code>:</p>\n\n<pre><code>add_filter('get_the_terms', 'exclude_terms');\necho get_the_tag_list('<p class=\"text-muted\"><i class=\"fa fa-tags\">',', ','</i></p>');\nremove_filter('get_the_terms', 'exclude_terms');\n</code></pre>\n\n<p>Add a filter on <code>get_the_terms</code> and then immediately remove it after echoing.</p>\n\n<p>The callback function removes terms by IDs or slugs:</p>\n\n<pre><code>function exclude_terms($terms) {\n $exclude_terms = array(9,11); //put term ids here to remove!\n if (!empty($terms) && is_array($terms)) {\n foreach ($terms as $key => $term) {\n if (in_array($term->term_id, $exclude_terms)) {\n unset($terms[$key]);\n }\n }\n }\n\n return $terms;\n}\n</code></pre>\n\n<p>You can do the exact same thing for <code>get_the_category_list</code> - just create a duplicate callback function with a different name - e.g., exclude-cats - and then add the ids you want to exclude and apply the filter:</p>\n\n<pre><code>add_filter('get_the_terms', 'exclude_cats');\necho get_the_category_list('<p class=\"text-muted\"><i class=\"fa fa-tags\">',', ','</i></p>');\nremove_filter('get_the_terms', 'exclude_cats');\n</code></pre>\n\n<p>I suppose you could make this one function and pass in the IDs...</p>\n"
}
] |
2015/11/20
|
[
"https://wordpress.stackexchange.com/questions/209348",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83992/"
] |
I am building a child theme for my personal use. Not very familiar with php, can only do basic things based on logic. I need to exclude one tag from being displayed on the tag list on a single post. Preferably so nothing is displayed at all when this tag is the only tag assigned to the post (I mean, no "Tags" title, nothing).
Here is what I have from the parent theme:
```
$tags = get_the_tags( $post->ID );
$separator = ' ';
$output = '';
if($tags){
echo '<div class="entry-tags">';
echo "<p><span>" . __('Tags', 'tracks') . "</span>";
foreach($tags as $tag) {
$output .= '<a href="'.get_tag_link( $tag->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts tagged %s", 'tracks' ), $tag->name ) ) . '">'.$tag->name.'</a>'.$separator;
}
echo trim($output, $separator);
echo "</p>";
echo "</div>";
}
```
I tried applying [this](https://wordpress.stackexchange.com/questions/45566/add-exception-for-specific-tag?rq=1) solution, but it didn't work. Probably because I don't fully understand what I'm doing. :)
Could someone maybe help me with this.
|
```
$tags = get_the_tags( $post->ID );
$separator = ' ';
$output = '';
if($tags){
echo '<div class="entry-tags">';
echo "<p><span>" . __('Tags', 'tracks') . "</span>";
foreach($tags as $tag) {
// dpm($tag) here by uncomment you can check tag slug which you want to exclude
if($tag->slug != "yourtag"){ // replace yourtag with you required tag name
$output .= '<a href="'.get_tag_link( $tag->term_id ).'" title="' . esc_attr( sprintf( __( "View all posts tagged %s", 'tracks' ), $tag->name ) ) . '">'.$tag->name.'</a>'.$separator;
}
}
echo trim($output, $separator);
echo "</p>";
echo "</div>";
}
```
You can apply condition that if tagname is not equal to your tag then only it will be added to out put.
Thanks!
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.