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 |
|---|---|---|---|---|---|---|
277,558 | <p><a href="https://i.stack.imgur.com/bvUt0.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/bvUt0.png" alt="this is the directory"></a>I am trying to integrate an animation in my Wordpress home page, for this I am trying to load scripts from "skrollr" library, but my styles and scripts don't load.</p>
<p>this is the code I added is function.php in the child theme:</p>
<pre><code>function add_scripts() {
wp_enqueue_style( 'main', get_stylesheet_directory_uri() . '/images/main.css' );
wp_enqueue_script( 'skrollr', get_template_directory_uri() . '/js/skrollr.min.js', '', '', false);
}
add_action ('wp_enqueue_scripts', 'add_scripts');
</code></pre>
<p>and these are the errors that I get from the console:
<a href="https://i.stack.imgur.com/5E9E1.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/5E9E1.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 277548,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>You can fix this by changes <code>site_url</code> and <code>home_url</code> in your database.</p>\... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277558",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126245/"
] | [](https://i.stack.imgur.com/bvUt0.png)I am trying to integrate an animation in my Wordpress home page, for this I am trying to load scripts from "skrollr" library, but my styles and scripts don't load.
this is the code I added is function.php in the child theme:
```
function add_scripts() {
wp_enqueue_style( 'main', get_stylesheet_directory_uri() . '/images/main.css' );
wp_enqueue_script( 'skrollr', get_template_directory_uri() . '/js/skrollr.min.js', '', '', false);
}
add_action ('wp_enqueue_scripts', 'add_scripts');
```
and these are the errors that I get from the console:
[](https://i.stack.imgur.com/5E9E1.png) | You can fix this by changes `site_url` and `home_url` in your database.
If you have access to your database(phpmyadmin) go to `options` table and change `site_url` and `home_url` from HTTPS to HTTP.
You can also change it through `wp-config` file.
```
define('WP_HOME','http://www.example.com');
define('WP_SITEURL','http://www.example.com');
```
See: <https://codex.wordpress.org/Changing_The_Site_URL> for possible methods.
Hope this helps. |
277,559 | <p>I want to redirect every user, depending on its user role, who wants to access home page (its my welcome login page).</p>
<p>I don't want to redirect users just after they log in, but after they are logged in and if they maybe again access home page incidentally.</p>
<p>Thanks</p>
| [
{
"answer_id": 277548,
"author": "Aniruddha Gawade",
"author_id": 101818,
"author_profile": "https://wordpress.stackexchange.com/users/101818",
"pm_score": 1,
"selected": false,
"text": "<p>You can fix this by changes <code>site_url</code> and <code>home_url</code> in your database.</p>\... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277559",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126244/"
] | I want to redirect every user, depending on its user role, who wants to access home page (its my welcome login page).
I don't want to redirect users just after they log in, but after they are logged in and if they maybe again access home page incidentally.
Thanks | You can fix this by changes `site_url` and `home_url` in your database.
If you have access to your database(phpmyadmin) go to `options` table and change `site_url` and `home_url` from HTTPS to HTTP.
You can also change it through `wp-config` file.
```
define('WP_HOME','http://www.example.com');
define('WP_SITEURL','http://www.example.com');
```
See: <https://codex.wordpress.org/Changing_The_Site_URL> for possible methods.
Hope this helps. |
277,575 | <p>media file has <code>//example.com/wp-content/uploads/2015/08/logo.png</code> without <code>http:</code>.</p>
<p>How to change it?</p>
<p><a href="https://i.stack.imgur.com/MxJmC.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MxJmC.jpg" alt="picture URL without http://"></a></p>
<p>I need full <code>http://</code> address in my posts</p>
| [
{
"answer_id": 277580,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The URLs in your media library are protocol-relative. This means, no matter if you are on a secure protocol... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277575",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126260/"
] | media file has `//example.com/wp-content/uploads/2015/08/logo.png` without `http:`.
How to change it?
[](https://i.stack.imgur.com/MxJmC.jpg)
I need full `http://` address in my posts | I'm sure some plugin or your theme modifies your attachment url.
Try to find `wp_get_attachment_url` hook in your code or simply create your own with high priority this way:
```
add_filter('wp_get_attachment_url', function($url) {
return preg_replace("~^//(.+)$~", "https://$1", $url);
}, 999);
```
or better:
```
add_filter('wp_get_attachment_url', function($url) {
return set_url_scheme($url, 'https');
}, 999);
```
But I recommend you to find the reason of this attachment url behavior first. |
277,599 | <p>I need to capture a value displayed on the website to the user, and then store it in a variable. Ideally, I'd like to do this in functions.php. </p>
<p>More specifically, we use dynamic phone number replacement on the sites, and we’d like to know which phone number is displayed to the user when they are submitting a contact form (via Gravity Forms).</p>
<p>I can wrap the phone number in a class or ID, but am struggling to understand how to write a function to pull this value into a variable.</p>
<p>I have submitted my question to Gravity Forms, but they will not assist. Thanks.</p>
| [
{
"answer_id": 277580,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The URLs in your media library are protocol-relative. This means, no matter if you are on a secure protocol... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277599",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126276/"
] | I need to capture a value displayed on the website to the user, and then store it in a variable. Ideally, I'd like to do this in functions.php.
More specifically, we use dynamic phone number replacement on the sites, and we’d like to know which phone number is displayed to the user when they are submitting a contact form (via Gravity Forms).
I can wrap the phone number in a class or ID, but am struggling to understand how to write a function to pull this value into a variable.
I have submitted my question to Gravity Forms, but they will not assist. Thanks. | I'm sure some plugin or your theme modifies your attachment url.
Try to find `wp_get_attachment_url` hook in your code or simply create your own with high priority this way:
```
add_filter('wp_get_attachment_url', function($url) {
return preg_replace("~^//(.+)$~", "https://$1", $url);
}, 999);
```
or better:
```
add_filter('wp_get_attachment_url', function($url) {
return set_url_scheme($url, 'https');
}, 999);
```
But I recommend you to find the reason of this attachment url behavior first. |
277,602 | <p>I recently migrated a live wordpress site, watershedgeo.com, over to a development site using the temp url, <a href="http://vps3813.inmotionhosting.com/~watershedgeo/dev.watershedgeo.com/" rel="nofollow noreferrer">http://vps3813.inmotionhosting.com/~watershedgeo/dev.watershedgeo.com/</a>.</p>
<p>I finally got it launched but the images and links don't show, they're all broken, but a lot of the images are showing their alt text. Here's the weird thing:</p>
<p>If I inspect the images in chrome, they show the temp url as the src of the image, but if I change the root before wp-content to watershedgeo.com, they show up. However, if I inspect the images on the live site, they show the source as <a href="http://1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com/wp-content/uploads/2016/04/imageName" rel="nofollow noreferrer">http://1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com/wp-content/uploads/2016/04/imageName</a></p>
<p>Is there a plugin or a way that I can change it so all the images use 1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com as the root so the images can show for development? All folders match, it's just the root that needs to be changed</p>
<p>The temp url is what is in the site url for the database and the wp-config.php file.</p>
| [
{
"answer_id": 277580,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>The URLs in your media library are protocol-relative. This means, no matter if you are on a secure protocol... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277602",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/115321/"
] | I recently migrated a live wordpress site, watershedgeo.com, over to a development site using the temp url, <http://vps3813.inmotionhosting.com/~watershedgeo/dev.watershedgeo.com/>.
I finally got it launched but the images and links don't show, they're all broken, but a lot of the images are showing their alt text. Here's the weird thing:
If I inspect the images in chrome, they show the temp url as the src of the image, but if I change the root before wp-content to watershedgeo.com, they show up. However, if I inspect the images on the live site, they show the source as <http://1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com/wp-content/uploads/2016/04/imageName>
Is there a plugin or a way that I can change it so all the images use 1qy8tt40p7n9v7tao3knw537.wpengine.netdna-cdn.com as the root so the images can show for development? All folders match, it's just the root that needs to be changed
The temp url is what is in the site url for the database and the wp-config.php file. | I'm sure some plugin or your theme modifies your attachment url.
Try to find `wp_get_attachment_url` hook in your code or simply create your own with high priority this way:
```
add_filter('wp_get_attachment_url', function($url) {
return preg_replace("~^//(.+)$~", "https://$1", $url);
}, 999);
```
or better:
```
add_filter('wp_get_attachment_url', function($url) {
return set_url_scheme($url, 'https');
}, 999);
```
But I recommend you to find the reason of this attachment url behavior first. |
277,617 | <p>How can I redirect users if they want to visit any other pages, but login page and password reset page?</p>
<p>My login page is actually my homepage and I want to redirect all of them to login page if they are not logged in. Also to allow them to reset password if they have forgotten them.</p>
<p>Thanks</p>
| [
{
"answer_id": 277623,
"author": "Fabio Marzocca",
"author_id": 65278,
"author_profile": "https://wordpress.stackexchange.com/users/65278",
"pm_score": 0,
"selected": false,
"text": "<p>You can add a rewrite rule into your .htaccess, checking for not-logged users, and redirect them to ho... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277617",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126244/"
] | How can I redirect users if they want to visit any other pages, but login page and password reset page?
My login page is actually my homepage and I want to redirect all of them to login page if they are not logged in. Also to allow them to reset password if they have forgotten them.
Thanks | You indicated that your login page is your home page. If you want all non-logged in users to then be directed to the home page to log in, you need to check a couple of things:
1. Is the user logged in?
2. Is the current page the home page?
You can do these things with `is_user_logged_in()` and is\_front\_page(). If these are not true, then you can use `wp_redirect()` to redirect the user to the home page.
Assuming your forgot password page is a "page," you could use `is_page()` in your logic as well.
You'll need to hook it to an action so that it fires late enough to allow checking the page, but early enough to still safely redirect the user (i.e. before headers are sent). `template_redirect` is ideal for this.
```
add_action( 'template_redirect', 'my_frontpage_redirect' );
function my_frontpage_redirect() {
if ( ! is_user_logged_in() ) {
if ( ! is_front_page() && ! is_page( 'my-password-reset' ) ) {
wp_redirect( home_url() );
exit();
}
}
}
```
Adjust the slug in the `is_page()` call according to whatever the page slug is for your password reset. |
277,618 | <p>I have a page that contain all my servers data, it really sensitive information.
Is there any strong way to hide it from google spiders and non login users.</p>
<p>I found small solutions that's hide the page, but not secured at all, if someone search in the website directory he will get access to that page easily.
Any hints here?!</p>
| [
{
"answer_id": 277620,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 3,
"selected": true,
"text": "<p>Use <a href=\"https://codex.wordpress.org/Using_Password_Protection\" rel=\"nofollow noreferrer\">passwo... | 2017/08/21 | [
"https://wordpress.stackexchange.com/questions/277618",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124400/"
] | I have a page that contain all my servers data, it really sensitive information.
Is there any strong way to hide it from google spiders and non login users.
I found small solutions that's hide the page, but not secured at all, if someone search in the website directory he will get access to that page easily.
Any hints here?! | Use [password protection mechanism](https://codex.wordpress.org/Using_Password_Protection)
Alterative you can use wordpress hook in your theme to show your post/page only for administrators this way:
```
add_action('wp', function() {
if(is_page('my-data') && !current_user_can('manage_options'))
die("123")
});
```
Note: don't use this code. It is just for demonstration. Better use hook `template_redirect` or something else.
We need more info about your environment to answer more specifically.
Perhaps the best option for you would be set password by http-server.
For apache using .htacces with something:
```
AuthType Basic
AuthName "restricted area"
AuthUserFile .htpasswd
require valid-user
``` |
277,649 | <p>I submitted my site to Google and now the author page is showing up in the search results. </p>
<pre><code>http://www.domain.com/author/myusername
</code></pre>
<p>How do I prevent my and others author names from showing up in search results? </p>
<p>It would be best to disable completely the path "/author/" all together because it's not a blog but a product site (it only has pages). </p>
<p>I did a search earlier and saw that there are plugins to do this but I'd rather not install a plugin (sometimes they are not updated) if there is another way but will if I have to. </p>
<p>I also searched through the source code of the pages and did not see any links to the author page. </p>
| [
{
"answer_id": 315604,
"author": "Cbinger",
"author_id": 144946,
"author_profile": "https://wordpress.stackexchange.com/users/144946",
"pm_score": 2,
"selected": false,
"text": "<p>You can disable the access to author pages by adding this snippet to functions.php:</p>\n\n<pre><code>// D... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277649",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29247/"
] | I submitted my site to Google and now the author page is showing up in the search results.
```
http://www.domain.com/author/myusername
```
How do I prevent my and others author names from showing up in search results?
It would be best to disable completely the path "/author/" all together because it's not a blog but a product site (it only has pages).
I did a search earlier and saw that there are plugins to do this but I'd rather not install a plugin (sometimes they are not updated) if there is another way but will if I have to.
I also searched through the source code of the pages and did not see any links to the author page. | The above answer is good, but if redirecting to home page, it should specify a 301 status and exit after.
```
add_action('template_redirect', 'my_custom_disable_author_page');
function my_custom_disable_author_page() {
global $wp_query;
if ( is_author() ) {
// Redirect to homepage, set status to 301 permenant redirect.
// Function defaults to 302 temporary redirect.
wp_redirect(get_option('home'), 301);
exit;
}
}
```
wp\_redirect() documentation <https://developer.wordpress.org/reference/functions/wp_redirect/> |
277,670 | <p>I'm currently using the Hemingway theme as seen here: </p>
<p>gamingprofessors.com</p>
<p>Currently this theme provides a pleasing tag when generated, however I can't change what the tag reads as. At least individually. I know I can go into the functions.php and change the $more_link_text:</p>
<pre><code>// Custom more-link text
add_filter( 'the_content_more_link', 'hemingway_custom_more_link', 10, 2 );
function hemingway_custom_more_link( $more_link, $more_link_text ) {
return str_replace( $more_link_text, __('Episode Summary and Extras',
'hemingway'), $more_link );
}
</code></pre>
<p>as I have done. However, I also am interested in writing normal blog posts and don't wish for them to take up large amounts of page real estate. The reason I chose "episode summary and extras" as the text is it's more obvious and entices a click vs "read more". However during a regular blog post this tag wouldn't make sense. Is there anyway to allow me to customize the tag and have it display, for example and without losing the formatting and colored box behind the tag currently? Also Hemingway doesn't support excerpts, at least not on blog posts as far as I can tell. So this isn't an option. I don't mind typing out the custom tag each post.</p>
| [
{
"answer_id": 277676,
"author": "deflime",
"author_id": 18907,
"author_profile": "https://wordpress.stackexchange.com/users/18907",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress has the functionality <a href=\"https://codex.wordpress.org/Customizing_the_Read_More\" rel=\"nofoll... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277670",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126310/"
] | I'm currently using the Hemingway theme as seen here:
gamingprofessors.com
Currently this theme provides a pleasing tag when generated, however I can't change what the tag reads as. At least individually. I know I can go into the functions.php and change the $more\_link\_text:
```
// Custom more-link text
add_filter( 'the_content_more_link', 'hemingway_custom_more_link', 10, 2 );
function hemingway_custom_more_link( $more_link, $more_link_text ) {
return str_replace( $more_link_text, __('Episode Summary and Extras',
'hemingway'), $more_link );
}
```
as I have done. However, I also am interested in writing normal blog posts and don't wish for them to take up large amounts of page real estate. The reason I chose "episode summary and extras" as the text is it's more obvious and entices a click vs "read more". However during a regular blog post this tag wouldn't make sense. Is there anyway to allow me to customize the tag and have it display, for example and without losing the formatting and colored box behind the tag currently? Also Hemingway doesn't support excerpts, at least not on blog posts as far as I can tell. So this isn't an option. I don't mind typing out the custom tag each post. | WordPress has the functionality [built-in](https://codex.wordpress.org/Customizing_the_Read_More) natively.
Try updating the read more tag in the `Text` editor. Examples:
```
<!--more Episode Summary and Extras -->
<!--more Regular Blog Post -->
<!--more Read More About My Cats -->
```
This only works with `the_content()`, but it sounds like your theme's blog loop is using that. |
277,677 | <p>i created website in local using word press theme, then uploaded on server but in server database have table like <strong>wp_2xxfpfb5qn_options</strong> and local have tables like "doc_options" so its not taking value from proper table, hence my theme not showing as i did changes in local theme. so what i have do for it?</p>
<p>Now, it's showing please check this link
<a href="http://clinic2.cruxbytes.com" rel="nofollow noreferrer">Site</a></p>
| [
{
"answer_id": 277676,
"author": "deflime",
"author_id": 18907,
"author_profile": "https://wordpress.stackexchange.com/users/18907",
"pm_score": 2,
"selected": true,
"text": "<p>WordPress has the functionality <a href=\"https://codex.wordpress.org/Customizing_the_Read_More\" rel=\"nofoll... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277677",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126317/"
] | i created website in local using word press theme, then uploaded on server but in server database have table like **wp\_2xxfpfb5qn\_options** and local have tables like "doc\_options" so its not taking value from proper table, hence my theme not showing as i did changes in local theme. so what i have do for it?
Now, it's showing please check this link
[Site](http://clinic2.cruxbytes.com) | WordPress has the functionality [built-in](https://codex.wordpress.org/Customizing_the_Read_More) natively.
Try updating the read more tag in the `Text` editor. Examples:
```
<!--more Episode Summary and Extras -->
<!--more Regular Blog Post -->
<!--more Read More About My Cats -->
```
This only works with `the_content()`, but it sounds like your theme's blog loop is using that. |
277,718 | <p>I am having problem when I want to display my taxonomy template.<br>
I have created one custom taxonomy 'Location' for my custom post type 'Project'. Moreover, I have created templates for it as :</p>
<pre><code>taxonomy-{taxonomy_name}-{term}.php
taxonomy-{taxonomy_name}.php
taxonomy.php
</code></pre>
<p>None of them work... I just get my archive-{post_type}.php in all case. </p>
<p>My targetted URLs are :<br>
<code>mywebsite.com/holliday/united-kingdom/</code> (Location taxonomy)<br>
<code>mywebsite.com/holliday/united-kingdom/london</code> (Location taxonomy child)</p>
<p>I should have messed up or missed something when creating my taxonomy but can't get it right.</p>
<p>Here is my code (register post type and register taxonomy) :</p>
<pre><code>// Register Post Type (Holliday)
$capability = 'publish_posts';
$cpt_args = array(
'menu_icon' => 'dashicons-groups',
'labels' => array(
'name' => __( 'Holliday', 'mon-plugin' ),
'singular_name' => __( 'Holliday', 'mon-plugin' ),
'add_new' => __( 'Add Holliday', 'mon-plugin' ),
'add_new_item' => __( 'Add Holliday', 'mon-plugin' ),
'edit' => __( 'Edit', 'mon-plugin' ),
'edit_item' => __( 'Edit Holliday', 'mon-plugin' ),
'new_item' => __( 'New Holliday', 'mon-plugin' ),
'view' => __( 'View Holliday', 'mon-plugin' ),
'view_item' => __( 'View Holliday', 'mon-plugin' ),
'search_items' => __( 'Search Holliday', 'mon-plugin' ),
'not_found' => __( 'No Holliday found', 'mon-plugin' ),
'not_found_in_trash'=> __( 'No Holliday found in Trash', 'mon-plugin' ),
'parent' => __( 'Parent Holliday', 'mon-plugin' ),
),
'public' => true,
'has_archive' => true,
'rewrite' => array(
'slug' => 'holliday/%my_project_location%',
),
'supports' => array('title', 'custom-fields', 'excerpt', 'editor', 'author', 'thumbnail', 'comments'),
'capabilities' => array(
'publish_posts' => $capability,
'edit_posts' => $capability,
'edit_others_posts' => $capability,
'delete_posts' => $capability,
'delete_others_posts'=> $capability,
'read_private_posts'=> $capability,
'edit_post' => $capability,
'delete_post' => $capability,
'read_post' => $capability
),
);
register_post_type( 'my_project', $cpt_args );
// Register Taxonomy (Location)
$cats_args = array(
'labels' => array(
'name' => _x( 'Project Location', 'mon-plugin' ),
'singular_name' => _x( 'Location', 'mon-plugin' ),
'search_items' => __( 'Search Location', 'mon-plugin' ),
'all_items' => __( 'All Location', 'mon-plugin' ),
'parent_item' => __( 'Parent Location', 'mon-plugin' ),
'parent_item_colon' => __( 'Parent Location:', 'mon-plugin' ),
'edit_item' => __( 'Edit Location', 'mon-plugin' ),
'update_item' => __( 'Update Location', 'mon-plugin' ),
'add_new_item' => __( 'Add New Location', 'mon-plugin' ),
'new_item_name' => __( 'New Location Name', 'mon-plugin' ),
'menu_name' => __( 'Location', 'mon-plugin' ),
),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'has_archive' => true,
'rewrite' => array(
'slug' => 'holliday',
'hierarchical' => true
)
);
register_taxonomy( 'my_project_location', 'my_project', $cats_args );
</code></pre>
<p>EDIT:<br>
If I change my taxonomy slug into something else, I get my taxonomy template working.<br>
Example: </p>
<pre><code> taxonomy slug => "location"
mywebsite.com/location/united-kingdom/ => Taxonomy template working !
</code></pre>
<p>But I want my taxonomy to work with my custom post type. To get my taxonomy template when accessing <code>mywebsite.com/{custom-post-type}/{taxonomy}/</code><br>
But this give me <code>archive-{custom-post-type}.php</code> file instead. </p>
<p>Following the <a href="https://developer.wordpress.org/themes/basics/template-hierarchy/" rel="nofollow noreferrer">Template Hierarchy</a> I expect Wordpress to find me the taxonomy template before the archive template. </p>
<p>Is there something I am missing ?<br>
Thank you for your help.</p>
| [
{
"answer_id": 278029,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>There are a couple of different solutions if you want to have only the /holliday/project-location/ URL an... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277718",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116160/"
] | I am having problem when I want to display my taxonomy template.
I have created one custom taxonomy 'Location' for my custom post type 'Project'. Moreover, I have created templates for it as :
```
taxonomy-{taxonomy_name}-{term}.php
taxonomy-{taxonomy_name}.php
taxonomy.php
```
None of them work... I just get my archive-{post\_type}.php in all case.
My targetted URLs are :
`mywebsite.com/holliday/united-kingdom/` (Location taxonomy)
`mywebsite.com/holliday/united-kingdom/london` (Location taxonomy child)
I should have messed up or missed something when creating my taxonomy but can't get it right.
Here is my code (register post type and register taxonomy) :
```
// Register Post Type (Holliday)
$capability = 'publish_posts';
$cpt_args = array(
'menu_icon' => 'dashicons-groups',
'labels' => array(
'name' => __( 'Holliday', 'mon-plugin' ),
'singular_name' => __( 'Holliday', 'mon-plugin' ),
'add_new' => __( 'Add Holliday', 'mon-plugin' ),
'add_new_item' => __( 'Add Holliday', 'mon-plugin' ),
'edit' => __( 'Edit', 'mon-plugin' ),
'edit_item' => __( 'Edit Holliday', 'mon-plugin' ),
'new_item' => __( 'New Holliday', 'mon-plugin' ),
'view' => __( 'View Holliday', 'mon-plugin' ),
'view_item' => __( 'View Holliday', 'mon-plugin' ),
'search_items' => __( 'Search Holliday', 'mon-plugin' ),
'not_found' => __( 'No Holliday found', 'mon-plugin' ),
'not_found_in_trash'=> __( 'No Holliday found in Trash', 'mon-plugin' ),
'parent' => __( 'Parent Holliday', 'mon-plugin' ),
),
'public' => true,
'has_archive' => true,
'rewrite' => array(
'slug' => 'holliday/%my_project_location%',
),
'supports' => array('title', 'custom-fields', 'excerpt', 'editor', 'author', 'thumbnail', 'comments'),
'capabilities' => array(
'publish_posts' => $capability,
'edit_posts' => $capability,
'edit_others_posts' => $capability,
'delete_posts' => $capability,
'delete_others_posts'=> $capability,
'read_private_posts'=> $capability,
'edit_post' => $capability,
'delete_post' => $capability,
'read_post' => $capability
),
);
register_post_type( 'my_project', $cpt_args );
// Register Taxonomy (Location)
$cats_args = array(
'labels' => array(
'name' => _x( 'Project Location', 'mon-plugin' ),
'singular_name' => _x( 'Location', 'mon-plugin' ),
'search_items' => __( 'Search Location', 'mon-plugin' ),
'all_items' => __( 'All Location', 'mon-plugin' ),
'parent_item' => __( 'Parent Location', 'mon-plugin' ),
'parent_item_colon' => __( 'Parent Location:', 'mon-plugin' ),
'edit_item' => __( 'Edit Location', 'mon-plugin' ),
'update_item' => __( 'Update Location', 'mon-plugin' ),
'add_new_item' => __( 'Add New Location', 'mon-plugin' ),
'new_item_name' => __( 'New Location Name', 'mon-plugin' ),
'menu_name' => __( 'Location', 'mon-plugin' ),
),
'hierarchical' => true,
'public' => true,
'show_ui' => true,
'has_archive' => true,
'rewrite' => array(
'slug' => 'holliday',
'hierarchical' => true
)
);
register_taxonomy( 'my_project_location', 'my_project', $cats_args );
```
EDIT:
If I change my taxonomy slug into something else, I get my taxonomy template working.
Example:
```
taxonomy slug => "location"
mywebsite.com/location/united-kingdom/ => Taxonomy template working !
```
But I want my taxonomy to work with my custom post type. To get my taxonomy template when accessing `mywebsite.com/{custom-post-type}/{taxonomy}/`
But this give me `archive-{custom-post-type}.php` file instead.
Following the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) I expect Wordpress to find me the taxonomy template before the archive template.
Is there something I am missing ?
Thank you for your help. | Thank you WebElaine for your help ! I figured out a way to solve it.
It looks a bit as you proposed in **Option 2**. Except that I used the filter **`parse_query`** to change my CPT `'has_archive'` to false when accessing my taxonomy.
Here is the code :
```
function check_taxonomy_query( $query ) {
if ($query->query['my_project_location'] && !$query->query['my_project']) {
$query->is_post_type_archive = false;
}
}
add_action( 'parse_query', 'check_taxonomy_query' );
```
`my_project_location` and `my_project` are the query vars used for my rewrite rules:
```
$newRules['holliday/?$'] = 'index.php?lang=en&post_type=my_project';
$newRules['holliday/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]';
$newRules['holliday/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]';
$newRules['holliday/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]&my_project=$matches[3]';
```
So in the `check_taxonomy_query` function, I simply check if I am in the case of the 2nd or 3rd line of my rewrite rules. If yes, I turn the post type archive down.
Hope it could help someone ;) |
277,724 | <p><a href="https://i.stack.imgur.com/Md1Uq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Md1Uq.png" alt="HTTPS ERROR"></a></p>
<p>How to fix Mixed content for wordpress plugin and themes, my images already served with https</p>
<p>i also test with <a href="https://www.whynopadlock.com/" rel="nofollow noreferrer">https://www.whynopadlock.com/</a></p>
| [
{
"answer_id": 278029,
"author": "WebElaine",
"author_id": 102815,
"author_profile": "https://wordpress.stackexchange.com/users/102815",
"pm_score": 1,
"selected": false,
"text": "<p>There are a couple of different solutions if you want to have only the /holliday/project-location/ URL an... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117129/"
] | [](https://i.stack.imgur.com/Md1Uq.png)
How to fix Mixed content for wordpress plugin and themes, my images already served with https
i also test with <https://www.whynopadlock.com/> | Thank you WebElaine for your help ! I figured out a way to solve it.
It looks a bit as you proposed in **Option 2**. Except that I used the filter **`parse_query`** to change my CPT `'has_archive'` to false when accessing my taxonomy.
Here is the code :
```
function check_taxonomy_query( $query ) {
if ($query->query['my_project_location'] && !$query->query['my_project']) {
$query->is_post_type_archive = false;
}
}
add_action( 'parse_query', 'check_taxonomy_query' );
```
`my_project_location` and `my_project` are the query vars used for my rewrite rules:
```
$newRules['holliday/?$'] = 'index.php?lang=en&post_type=my_project';
$newRules['holliday/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]';
$newRules['holliday/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]';
$newRules['holliday/([^/]+)/([^/]+)/([^/]+)/?$'] = 'index.php?lang=en&post_type=my_project&my_project_location=$matches[1]/$matches[2]&my_project=$matches[3]';
```
So in the `check_taxonomy_query` function, I simply check if I am in the case of the 2nd or 3rd line of my rewrite rules. If yes, I turn the post type archive down.
Hope it could help someone ;) |
277,725 | <p>I've a Custom Post Type called clock and a taxonomy called clock_category on my website.
It is working well and All the clocks can be accessed from the REST endpoint
<a href="https://myapp.dev/wp-json/wp/v2/clock" rel="noreferrer">https://myapp.dev/wp-json/wp/v2/clock</a></p>
<p>But I don't know how to filter them by the Clock category, say I want to get all the clocks which are made of wood </p>
<p>I tried different URLs but none of them seems to be working
<a href="https://myapp.dev/wp-json/wp/v2/clock?clock_category=wood" rel="noreferrer">https://myapp.dev/wp-json/wp/v2/clock?clock_category=wood</a>
<a href="https://myapp.dev/wp-json/wp/v2/clock?clock_category=10" rel="noreferrer">https://myapp.dev/wp-json/wp/v2/clock?clock_category=10</a></p>
<p>and many more. All I got was the full result set.</p>
<p>Here is the code</p>
<pre><code><?php
add_action( 'init', 'clock' );
function clock() {
$labels = array(
"name" => __( 'Clock', 'mywp' ),
"singular_name" => __( 'clock', 'mywp' ),
"menu_name" => __( 'Clock', 'mywp' ),
"all_items" => __( 'All Clock', 'mywp' ),
"add_new" => __( 'Add New Clock', 'mywp' ),
"add_new_item" => __( 'Add New Clock', 'mywp' ),
"edit_item" => __( 'Edit Clock', 'mywp' ),
"new_item" => __( 'New Clock', 'mywp' ),
"view_item" => __( 'View Clock', 'mywp' ),
"search_items" => __( 'Search Clock', 'mywp' ),
"not_found" => __( 'No Clock Found', 'mywp' ),
"not_found_in_trash" => __( 'No Clock found in trash', 'mywp' ),
"parent_item_colon" => __( 'Parent Clock', 'mywp' ),
"featured_image" => __( 'Feature Image for Clock', 'mywp' ),
"set_featured_image" => __( 'Set featured Clock image', 'mywp' ),
"remove_featured_image" => __( 'Remove featured image for Clock', 'mywp' ),
"use_featured_image" => __( 'Use featured image for Clock', 'mywp' ),
"archives" => __( 'Clock archives', 'mywp' ),
"insert_into_item" => __( 'Insert into Clock', 'mywp' ),
"uploaded_to_this_item" => __( 'Uploaded to this Clock', 'mywp' ),
"items_list_navigation" => __( 'Clock list navigation', 'mywp' ),
"items_list" => __( 'Clock List', 'mywp' ),
"parent_item_colon" => __( 'Parent Clock', 'mywp' ),
);
$args = array(
"label" => __( 'Clock', 'mywp' ),
"labels" => $labels,
"description" => "Clock",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => true,
"rest_base" => "clock",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "clock", "with_front" => true ),
"query_var" => true,
"supports" => array( "title", "editor", "thumbnail", "custom-fields", "page-attributes", "post-formats" ),
"taxonomies" => array( ),
);
register_post_type( "clock", $args );
</code></pre>
<p>}</p>
<pre><code>add_action( 'init', 'create_clock_tax' );
function create_clock_tax() {
register_taxonomy(
'clock_category',
'clock',
array(
'label' => __( 'Clock Category' ),
'rewrite' => array( 'slug' => 'clock_category' ),
'hierarchical' => true,
)
);
}
</code></pre>
<p>Hope someone help me out on this. I've been trying to solve this for 5 hours and nothing seems to be working.</p>
| [
{
"answer_id": 277744,
"author": "birgire",
"author_id": 26350,
"author_profile": "https://wordpress.stackexchange.com/users/26350",
"pm_score": 2,
"selected": false,
"text": "<p>We can check out the <code>/wp/v2/clock</code> endpoint's arguments here:</p>\n\n<pre><code>https://myapp.dev... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277725",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126346/"
] | I've a Custom Post Type called clock and a taxonomy called clock\_category on my website.
It is working well and All the clocks can be accessed from the REST endpoint
<https://myapp.dev/wp-json/wp/v2/clock>
But I don't know how to filter them by the Clock category, say I want to get all the clocks which are made of wood
I tried different URLs but none of them seems to be working
<https://myapp.dev/wp-json/wp/v2/clock?clock_category=wood>
<https://myapp.dev/wp-json/wp/v2/clock?clock_category=10>
and many more. All I got was the full result set.
Here is the code
```
<?php
add_action( 'init', 'clock' );
function clock() {
$labels = array(
"name" => __( 'Clock', 'mywp' ),
"singular_name" => __( 'clock', 'mywp' ),
"menu_name" => __( 'Clock', 'mywp' ),
"all_items" => __( 'All Clock', 'mywp' ),
"add_new" => __( 'Add New Clock', 'mywp' ),
"add_new_item" => __( 'Add New Clock', 'mywp' ),
"edit_item" => __( 'Edit Clock', 'mywp' ),
"new_item" => __( 'New Clock', 'mywp' ),
"view_item" => __( 'View Clock', 'mywp' ),
"search_items" => __( 'Search Clock', 'mywp' ),
"not_found" => __( 'No Clock Found', 'mywp' ),
"not_found_in_trash" => __( 'No Clock found in trash', 'mywp' ),
"parent_item_colon" => __( 'Parent Clock', 'mywp' ),
"featured_image" => __( 'Feature Image for Clock', 'mywp' ),
"set_featured_image" => __( 'Set featured Clock image', 'mywp' ),
"remove_featured_image" => __( 'Remove featured image for Clock', 'mywp' ),
"use_featured_image" => __( 'Use featured image for Clock', 'mywp' ),
"archives" => __( 'Clock archives', 'mywp' ),
"insert_into_item" => __( 'Insert into Clock', 'mywp' ),
"uploaded_to_this_item" => __( 'Uploaded to this Clock', 'mywp' ),
"items_list_navigation" => __( 'Clock list navigation', 'mywp' ),
"items_list" => __( 'Clock List', 'mywp' ),
"parent_item_colon" => __( 'Parent Clock', 'mywp' ),
);
$args = array(
"label" => __( 'Clock', 'mywp' ),
"labels" => $labels,
"description" => "Clock",
"public" => true,
"publicly_queryable" => true,
"show_ui" => true,
"show_in_rest" => true,
"rest_base" => "clock",
"has_archive" => false,
"show_in_menu" => true,
"exclude_from_search" => false,
"capability_type" => "post",
"map_meta_cap" => true,
"hierarchical" => false,
"rewrite" => array( "slug" => "clock", "with_front" => true ),
"query_var" => true,
"supports" => array( "title", "editor", "thumbnail", "custom-fields", "page-attributes", "post-formats" ),
"taxonomies" => array( ),
);
register_post_type( "clock", $args );
```
}
```
add_action( 'init', 'create_clock_tax' );
function create_clock_tax() {
register_taxonomy(
'clock_category',
'clock',
array(
'label' => __( 'Clock Category' ),
'rewrite' => array( 'slug' => 'clock_category' ),
'hierarchical' => true,
)
);
}
```
Hope someone help me out on this. I've been trying to solve this for 5 hours and nothing seems to be working. | We can check out the `/wp/v2/clock` endpoint's arguments here:
```
https://myapp.dev/wp-json/wp/v2/
```
If we add the `'show_in_rest' => true,` argument, when registering the custom `clock_category` taxonomy, it will add a support for this GET/POST argument:
```
clock_category: {
required: false,
default: [ ],
description: "Limit result set to all items that have the
specified term assigned in the clock_category taxonomy.",
type: "array",
items: {
type: "integer"
}
},
```
and this GET argument:
```
clock_category_exclude: {
required: false,
default: [ ],
description: "Limit result set to all items except those that have the
specified term assigned in the clock_category taxonomy.",
type: "array",
items: {
type: "integer"
}
}
```
It will also add the `/wp/v2/clock_category` endpoint.
So to filter the clock posts by a single clock category ID:
```
https://myapp.dev/wp-json/wp/v2/clock?clock_category=10
```
or by multiple clock category IDs:
```
https://myapp.dev/wp-json/wp/v2/clock?clock_category=10,11,12
```
To exclude from a single category ID:
```
https://myapp.dev/wp-json/wp/v2/clock?clock_category_exclude=13
```
or exclude from multiple clock category IDs:
```
https://myapp.dev/wp-json/wp/v2/clock?clock_category_exclude=13,14
``` |
277,731 | <p>I'm creating a custom php/js pages querying and displaying results from a separate non-wordpress DB on a 2nd page. The header and footer will be the same as my theme so I'm calling the theme's footer and header but I haven't figured out why my hook to customize the pages' title aren't working and am asking which hook to use to display my designated title. </p>
<p>I don't need to call any content from wordpress besides the theme's header and footer (1 reason why I'm not using a page template). </p>
<p>I thought to do </p>
<pre><code>require('../wp-blog-header.php');
get_header();
add_filter( 'wp_title', 'mycustom_title', 4);
function mycustom_title($teetitle) {
$teetitle = 'My Custom Title Here';
return $teetitle;
}
</code></pre>
<p>as described <a href="https://stackoverflow.com/questions/42009768/wordpress-set-custom-title-on-custom-page/42010001#42010001">here</a> and <a href="https://gist.github.com/skorasaurus/d2ea1ad0b0b0de75e7635ed57d0074b3" rel="nofollow noreferrer">(my full php file is here)</a></p>
<p>I'm able to call the header using 'get_header' and my header.php file in my theme calls wp_head.</p>
<p>At this point, I'm stumped because my hook to wp_title is not firing and is following the default logic of stating 'page not found' for a 404 in general-template.php</p>
<p>I thought I could override by issuing a hook immediately after calling get_header in my php file ;
<a href="https://stackoverflow.com/questions/9926292/set-custom-page-title-with-hook">https://stackoverflow.com/questions/9926292/set-custom-page-title-with-hook</a>
but this is not working. </p>
<p>When I issue $echo wp_title in the body later in the same file, wp_title gives me my modified title. </p>
<p>I've also tried a couple default different themes (2013, 2012, etc) and the page title is not correct so I think there's something fundamental that I'm missing or that I'm not calling the correct hook.
I've also tried placing my hook in my theme's function.php and had the same result. I've also tried using a priority of a 6 digit integer, and still had same result. </p>
| [
{
"answer_id": 277735,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": -1,
"selected": false,
"text": "<p>It doesn't work this way.\nYou should load all wordpress environment, than with <code>template_include... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277731",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/48698/"
] | I'm creating a custom php/js pages querying and displaying results from a separate non-wordpress DB on a 2nd page. The header and footer will be the same as my theme so I'm calling the theme's footer and header but I haven't figured out why my hook to customize the pages' title aren't working and am asking which hook to use to display my designated title.
I don't need to call any content from wordpress besides the theme's header and footer (1 reason why I'm not using a page template).
I thought to do
```
require('../wp-blog-header.php');
get_header();
add_filter( 'wp_title', 'mycustom_title', 4);
function mycustom_title($teetitle) {
$teetitle = 'My Custom Title Here';
return $teetitle;
}
```
as described [here](https://stackoverflow.com/questions/42009768/wordpress-set-custom-title-on-custom-page/42010001#42010001) and [(my full php file is here)](https://gist.github.com/skorasaurus/d2ea1ad0b0b0de75e7635ed57d0074b3)
I'm able to call the header using 'get\_header' and my header.php file in my theme calls wp\_head.
At this point, I'm stumped because my hook to wp\_title is not firing and is following the default logic of stating 'page not found' for a 404 in general-template.php
I thought I could override by issuing a hook immediately after calling get\_header in my php file ;
<https://stackoverflow.com/questions/9926292/set-custom-page-title-with-hook>
but this is not working.
When I issue $echo wp\_title in the body later in the same file, wp\_title gives me my modified title.
I've also tried a couple default different themes (2013, 2012, etc) and the page title is not correct so I think there's something fundamental that I'm missing or that I'm not calling the correct hook.
I've also tried placing my hook in my theme's function.php and had the same result. I've also tried using a priority of a 6 digit integer, and still had same result. | I ended up making a page template anyways and inserting the page title when making the post. |
277,740 | <p>I'm using Types plugin to create user metaboxes but it doesn't save. My HTML:</p>
<pre><code><form id="new-user" action="" method="POST" name="new-user" novalidate="" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="wpcf-nombre-u" id="nombre" placeholder="<?php _e('Nombre', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="text" name="wpcf-apellidos-u" id="apellidos" placeholder="<?php _e('Apellidos', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="password" name="wpcf-contrasena-u" id="contrasena" placeholder="<?php _e('Contraseña', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="password" name="wpcf-rep-contrasena-u" id="rep-contrasena" placeholder="<?php _e('Repita contraseña', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="email" name="wpcf-email-u" id="email" placeholder="Email" >
</div>
<div class="form-group">
<input type="checkbox" name="sectores[]" id="sector-nutricion-deportiva" value="nutricion-deportiva">
<label for="sector-nutricion-deportiva">Nutrición deportiva</label>
<input type="checkbox" name="sectores[]" id="sector-rutinas-de-gimnasio" value="rutinas-de-gimnasio">
<label for="sector-rutinas-de-gimnasio">Rutinas de gimnasio</label>
<input type="checkbox" name="sectores[]" id="sector-clases-dirigidas" value="clases-dirigidas">
<label for="sector-clases-dirigidas">Clases dirigidas</label>
<input type="checkbox" name="sectores[]" id="sector-entrenamiento-personal" value="entrenamiento-personal">
<label for="sector-entrenamiento-personal">Entrenamiento personal</label>
<input type="checkbox" name="sectores[]" id="sector-deportes-de-equipo" value="deportes-de-equipo">
<label for="sector-deportes-de-equipo">Deportes de equipo</label>
<input type="checkbox" name="sectores[]" id="sector-deportes-individuales" value="deportes-individuales">
<label for="sector-deportes-individuales">Deportes individuales</label>
<input type="submit" value="¡Registrate ya!" />
<input type="hidden" name="task" value="register" />
</div>
</form>
</code></pre>
<p>PHP:</p>
<pre><code>$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if( isset($_POST['task']) && $_POST['task'] == 'register' ) {
$nombre = $wpdb->escape(trim($_POST['wpcf-nombre-u']));
$apellidos = $wpdb->escape(trim($_POST['wpcf-apellidos-u']));
$contrasena = $wpdb->escape(trim($_POST['wpcf-contrasena-u']));
$rep_contrasena = $wpdb->escape(trim($_POST['wpcf-rep-contrasena-u']));
$email = $wpdb->escape(trim($_POST['wpcf-email-u']));
if( $email == "" || $contrasena == "" || $rep_contrasena == "" || $username == "" || $nombre == "" || $apellidos == "") {
$err = 'Please don\'t leave the required fields.';
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err = 'Invalid email address.';
} else if(email_exists($email) ) {
$err = 'Email already exist.';
} else if($contrasena <> $rep_contrasena ){
$err = 'Password do not match.';
} else {
$user_id = wp_insert_user(
array (
'first_name' => apply_filters('pre_user_first_name', $nombre),
'last_name' => apply_filters('pre_user_last_name', $apellidos),
'user_pass' => apply_filters('pre_user_user_pass', $contrasena),
'user_login' => apply_filters('pre_user_user_login', $username),
'user_email' => apply_filters('pre_user_user_email', $email), 'role' => 'subscriber'
)
);
if( is_wp_error($user_id) ) {
$err = 'Error on user creation.';
} else {
$success = 'You\'re successfully register';
$sectores = $_POST['sectores'];
$count = count($sectores);
for($i=0; $i < $count; $i++){
update_user_meta( $user_id, 'wpcf-sectores-de-experiencia-u', $sectores[$i] );
}
}
}
}
</code></pre>
<p>My types backend is:
<a href="https://i.stack.imgur.com/oQ0lR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/oQ0lR.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 277735,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": -1,
"selected": false,
"text": "<p>It doesn't work this way.\nYou should load all wordpress environment, than with <code>template_include... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277740",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126358/"
] | I'm using Types plugin to create user metaboxes but it doesn't save. My HTML:
```
<form id="new-user" action="" method="POST" name="new-user" novalidate="" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="wpcf-nombre-u" id="nombre" placeholder="<?php _e('Nombre', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="text" name="wpcf-apellidos-u" id="apellidos" placeholder="<?php _e('Apellidos', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="password" name="wpcf-contrasena-u" id="contrasena" placeholder="<?php _e('Contraseña', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="password" name="wpcf-rep-contrasena-u" id="rep-contrasena" placeholder="<?php _e('Repita contraseña', 'wm'); ?>" >
</div>
<div class="form-group">
<input type="email" name="wpcf-email-u" id="email" placeholder="Email" >
</div>
<div class="form-group">
<input type="checkbox" name="sectores[]" id="sector-nutricion-deportiva" value="nutricion-deportiva">
<label for="sector-nutricion-deportiva">Nutrición deportiva</label>
<input type="checkbox" name="sectores[]" id="sector-rutinas-de-gimnasio" value="rutinas-de-gimnasio">
<label for="sector-rutinas-de-gimnasio">Rutinas de gimnasio</label>
<input type="checkbox" name="sectores[]" id="sector-clases-dirigidas" value="clases-dirigidas">
<label for="sector-clases-dirigidas">Clases dirigidas</label>
<input type="checkbox" name="sectores[]" id="sector-entrenamiento-personal" value="entrenamiento-personal">
<label for="sector-entrenamiento-personal">Entrenamiento personal</label>
<input type="checkbox" name="sectores[]" id="sector-deportes-de-equipo" value="deportes-de-equipo">
<label for="sector-deportes-de-equipo">Deportes de equipo</label>
<input type="checkbox" name="sectores[]" id="sector-deportes-individuales" value="deportes-individuales">
<label for="sector-deportes-individuales">Deportes individuales</label>
<input type="submit" value="¡Registrate ya!" />
<input type="hidden" name="task" value="register" />
</div>
</form>
```
PHP:
```
$err = '';
$success = '';
global $wpdb, $PasswordHash, $current_user, $user_ID;
if( isset($_POST['task']) && $_POST['task'] == 'register' ) {
$nombre = $wpdb->escape(trim($_POST['wpcf-nombre-u']));
$apellidos = $wpdb->escape(trim($_POST['wpcf-apellidos-u']));
$contrasena = $wpdb->escape(trim($_POST['wpcf-contrasena-u']));
$rep_contrasena = $wpdb->escape(trim($_POST['wpcf-rep-contrasena-u']));
$email = $wpdb->escape(trim($_POST['wpcf-email-u']));
if( $email == "" || $contrasena == "" || $rep_contrasena == "" || $username == "" || $nombre == "" || $apellidos == "") {
$err = 'Please don\'t leave the required fields.';
} else if(!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$err = 'Invalid email address.';
} else if(email_exists($email) ) {
$err = 'Email already exist.';
} else if($contrasena <> $rep_contrasena ){
$err = 'Password do not match.';
} else {
$user_id = wp_insert_user(
array (
'first_name' => apply_filters('pre_user_first_name', $nombre),
'last_name' => apply_filters('pre_user_last_name', $apellidos),
'user_pass' => apply_filters('pre_user_user_pass', $contrasena),
'user_login' => apply_filters('pre_user_user_login', $username),
'user_email' => apply_filters('pre_user_user_email', $email), 'role' => 'subscriber'
)
);
if( is_wp_error($user_id) ) {
$err = 'Error on user creation.';
} else {
$success = 'You\'re successfully register';
$sectores = $_POST['sectores'];
$count = count($sectores);
for($i=0; $i < $count; $i++){
update_user_meta( $user_id, 'wpcf-sectores-de-experiencia-u', $sectores[$i] );
}
}
}
}
```
My types backend is:
[](https://i.stack.imgur.com/oQ0lR.png) | I ended up making a page template anyways and inserting the page title when making the post. |
277,763 | <p>I could see previous –next image option in the default Twenty Sixteen theme even without installation any plugins.</p>
<p>But I would like to use Big Blue theme instead of default one and I could not see previous –next image option regardless that I’ve installed different plugins related gallery like Gallery Portfolio, NextGEN Gallery, PB SEO Friendly Images……</p>
<p>What need to be done to see previous –next image option in Big Blue or any other (not only default ) themes?</p>
<p>Thanks.</p>
<p>//Edited
//single.php</p>
<pre><code><?php
/**
* The template for displaying all single posts.
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
*
* @package Big Blue
*/
get_header(); ?>
<header class="entry-header article-header <?php if(has_post_thumbnail()){echo 'featured-image'; } ?>">
<?php the_post_thumbnail( 'single-post-thumbnail', array( 'class' => 'single-post-thumbnail' ) ); ?>
<div class="blue-overlay"></div>
<div class="container">
<div class="entry-detail">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php $tags_list = get_the_tag_list( '', esc_html__( ', ', 'big-blue' ) ); ?>
<div class="entry-meta">
<?php big_blue_posted_on(); ?>
</div><!-- .entry-meta -->
</div>
</div>
</header><!-- .entry-header -->
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="inner-wrapper">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'single');
the_post_navigation();
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</div>
<div class="col-md-4">
<?php get_sidebar(); ?>
</div>
</div>
</div>
</div>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
</code></pre>
| [
{
"answer_id": 277735,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": -1,
"selected": false,
"text": "<p>It doesn't work this way.\nYou should load all wordpress environment, than with <code>template_include... | 2017/08/22 | [
"https://wordpress.stackexchange.com/questions/277763",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126051/"
] | I could see previous –next image option in the default Twenty Sixteen theme even without installation any plugins.
But I would like to use Big Blue theme instead of default one and I could not see previous –next image option regardless that I’ve installed different plugins related gallery like Gallery Portfolio, NextGEN Gallery, PB SEO Friendly Images……
What need to be done to see previous –next image option in Big Blue or any other (not only default ) themes?
Thanks.
//Edited
//single.php
```
<?php
/**
* The template for displaying all single posts.
*
* @link https://developer.wordpress.org/themes/basics/template-hierarchy/#single-post
*
* @package Big Blue
*/
get_header(); ?>
<header class="entry-header article-header <?php if(has_post_thumbnail()){echo 'featured-image'; } ?>">
<?php the_post_thumbnail( 'single-post-thumbnail', array( 'class' => 'single-post-thumbnail' ) ); ?>
<div class="blue-overlay"></div>
<div class="container">
<div class="entry-detail">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
<?php $tags_list = get_the_tag_list( '', esc_html__( ', ', 'big-blue' ) ); ?>
<div class="entry-meta">
<?php big_blue_posted_on(); ?>
</div><!-- .entry-meta -->
</div>
</div>
</header><!-- .entry-header -->
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<div class="inner-wrapper">
<div class="container">
<div class="row">
<div class="col-md-8">
<?php
while ( have_posts() ) : the_post();
get_template_part( 'template-parts/content', 'single');
the_post_navigation();
// If comments are open or we have at least one comment, load up the comment template.
if ( comments_open() || get_comments_number() ) :
comments_template();
endif;
endwhile; // End of the loop.
?>
</div>
<div class="col-md-4">
<?php get_sidebar(); ?>
</div>
</div>
</div>
</div>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_footer();
``` | I ended up making a page template anyways and inserting the page title when making the post. |
277,786 | <p>I want to try calling the pre-defined functions from the <a href="https://wordpress.org/plugins/front-end-pm/" rel="nofollow noreferrer">front end private messages plugin</a> in my custom template. But It shows that the function does not exist. But that function is working fine in the plugin.</p>
<p>What should I do?</p>
| [
{
"answer_id": 277794,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": -1,
"selected": true,
"text": "<p>There can be various reason for the undefined function error:</p>\n\n<ul>\n<li><p>The plugin might load its function ... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277786",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126392/"
] | I want to try calling the pre-defined functions from the [front end private messages plugin](https://wordpress.org/plugins/front-end-pm/) in my custom template. But It shows that the function does not exist. But that function is working fine in the plugin.
What should I do? | There can be various reason for the undefined function error:
* The plugin might load its function definitions later than `template_include` or in the admin backend only.
* You might have made a syntax error, for example if the plugin is using a [namespace](http://php.net/manual/en/language.namespaces.php), but you are calling the function without that namespace. Or the function is really a class method, and you treat it as a function …
Another question is: Why would you call that function directly? Templates should have as little dependencies as possible. Imagine someone finds a security problem in the plugin, and you have to turn it off. Do you really want to edit all your template files then? Probably not. :)
It is much better to keep that dependency out of the template and call a custom action instead. For example, in your template you can replace the direct call with an action call:
```
do_action( 'frontend.message' );
```
In your theme's `functions.php`, you register a callback for that action:
```
add_action( 'frontend.message', 'my_frontend_message' );
function my_frontend_message()
{
if ( ! function_exists( 'plugin_frontend_message' ) ) {
// Show debug info for those who can do something about it.
if ( current_user_can( 'manage_option' ) ) {
print '<p class="error">Function plugin_frontend_message() not found.</p>';
}
return;
}
print plugin_frontend_message();
}
```
If you turn off the plugin now, nothing bad will happen, your visitors will just see nothing instead of a message. |
277,787 | <p>I'm trying to Show User List in WordPress Admin in Descending order by "ID" column.</p>
<p>I tried below code</p>
<pre><code>add_action('pre_user_search', 'change_user_order');
function change_user_order($query)
{
$query->query_orderby = ' ORDER BY ID DESC';
}
</code></pre>
<p>But its not working.</p>
| [
{
"answer_id": 277789,
"author": "Bhagchandani",
"author_id": 101627,
"author_profile": "https://wordpress.stackexchange.com/users/101627",
"pm_score": 0,
"selected": false,
"text": "<p>As per user @toni_lehtimaki <strong>pre_user_search</strong> is deprecated. Below code is working.</p>... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277787",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124611/"
] | I'm trying to Show User List in WordPress Admin in Descending order by "ID" column.
I tried below code
```
add_action('pre_user_search', 'change_user_order');
function change_user_order($query)
{
$query->query_orderby = ' ORDER BY ID DESC';
}
```
But its not working. | I first thought that `pre_user_query` would be that hook for the job. But I think using the equivalent of `pre_get_posts`, which is [`pre_get_users`](https://developer.wordpress.org/reference/hooks/pre_get_users/), would be suitable here.
You also said you wanted to run this in admin. So we will check that before running this.
```
function my_custom_order_users_by_id( $query ) {
//Check that we are in admin otherwise return
if( !is_admin() ) {
return;
}
// We are changing the query_vars to reorder
$query->query_vars['orderby'] = 'ID';
$query->query_vars['order'] = 'DESC';
// We need to remember to return the altered query.
return $query;
}
// Lets apply our function to hook.
add_action( 'pre_get_users', 'my_custom_order_users_by_id' );
``` |
277,804 | <p>sorry for my english...
So I want to get my data from a https live site back to localhost. Using duplicator plugin works fine exept that I run (especially in Chrome) to a problem with absolute setted image links, wich refer to <a href="https://localhost" rel="nofollow noreferrer">https://localhost</a> ... .</p>
<p>I wonder if someone is out there who knows a solution for this issue. </p>
<p>Many thanks in advance</p>
| [
{
"answer_id": 277789,
"author": "Bhagchandani",
"author_id": 101627,
"author_profile": "https://wordpress.stackexchange.com/users/101627",
"pm_score": 0,
"selected": false,
"text": "<p>As per user @toni_lehtimaki <strong>pre_user_search</strong> is deprecated. Below code is working.</p>... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107825/"
] | sorry for my english...
So I want to get my data from a https live site back to localhost. Using duplicator plugin works fine exept that I run (especially in Chrome) to a problem with absolute setted image links, wich refer to <https://localhost> ... .
I wonder if someone is out there who knows a solution for this issue.
Many thanks in advance | I first thought that `pre_user_query` would be that hook for the job. But I think using the equivalent of `pre_get_posts`, which is [`pre_get_users`](https://developer.wordpress.org/reference/hooks/pre_get_users/), would be suitable here.
You also said you wanted to run this in admin. So we will check that before running this.
```
function my_custom_order_users_by_id( $query ) {
//Check that we are in admin otherwise return
if( !is_admin() ) {
return;
}
// We are changing the query_vars to reorder
$query->query_vars['orderby'] = 'ID';
$query->query_vars['order'] = 'DESC';
// We need to remember to return the altered query.
return $query;
}
// Lets apply our function to hook.
add_action( 'pre_get_users', 'my_custom_order_users_by_id' );
``` |
277,828 | <p>This is a rather simple question, so I'll keep it short.</p>
<p>Update1: In this context <code>{page-structure}</code> means just that: <code>page1/page1-1/page1-1-1/{...}</code>.</p>
<p>Update2: For further clarification, I want to do about the same <a href="https://www.advancedcustomfields.com/resources/post-object/" rel="nofollow noreferrer">the ACF Post Object field</a> is doing, except I want to do it dynamically based on the URL structure as explained below.</p>
<p>I'm making a custom multilingual site, with a dual page structure (with and without <code>/en</code>). Any page at <code>mysite.com/en/{page-structure}</code> are getting its locale changed to <code>en_US</code> and the content (ACF) is fetched from the corresponding page at <code>mysite.com/{page-structure}</code>. Based on the locale different content is displayed.</p>
<p>How can I on <code>mysite.com/en/{page-structure}</code> automatically get the $post Object from <code>mysite.com/{page-structure}</code> (i.e. without <code>en/</code>)?</p>
<p>(Currently I'm using ACF to fetch fields from the corresponding page by rewriting the field requests, but it I could change the $post Object on the fly, it would make everything a little simpler.)</p>
| [
{
"answer_id": 277830,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <code>$global</code> in before your <code>$post</code></p>\n\n<p>For example:</p>\n\n<pre><co... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277828",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/59140/"
] | This is a rather simple question, so I'll keep it short.
Update1: In this context `{page-structure}` means just that: `page1/page1-1/page1-1-1/{...}`.
Update2: For further clarification, I want to do about the same [the ACF Post Object field](https://www.advancedcustomfields.com/resources/post-object/) is doing, except I want to do it dynamically based on the URL structure as explained below.
I'm making a custom multilingual site, with a dual page structure (with and without `/en`). Any page at `mysite.com/en/{page-structure}` are getting its locale changed to `en_US` and the content (ACF) is fetched from the corresponding page at `mysite.com/{page-structure}`. Based on the locale different content is displayed.
How can I on `mysite.com/en/{page-structure}` automatically get the $post Object from `mysite.com/{page-structure}` (i.e. without `en/`)?
(Currently I'm using ACF to fetch fields from the corresponding page by rewriting the field requests, but it I could change the $post Object on the fly, it would make everything a little simpler.) | This is how you can get the post object of a page with a matching path, minus the `/en` part:
```
$page_path = get_page_uri( get_queried_object_id() ); // en/page/child-page
$target_page_path = str_replace( 'en/', '', $page_path ); // page/child-page
$target_page = get_page_by_path( $target_page_path ); // WP_Post of target page.
``` |
277,836 | <p>I'm trying to make a code to display a image at the end of each post, but i need to show a specific image for each post category.
I'm using the code below:</p>
<pre><code><?php
if (in_category('category1')||){
echo '<img src="https://example.com/category1">';
}
elseif (in_category('category2')){
echo '<img src="https://example.com/category2">';
}
elseif (in_category('category3')){
echo '<img src="https://example.com/category3">';
}
elseif (in_category('category4')){
echo '<img src="https://example.com/category4">';
}
?>
</code></pre>
<p>It's working, but my problem now is that some posts have all the categories, and I need to test the primary category of the post.
Is there a function to do this?</p>
| [
{
"answer_id": 277830,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 0,
"selected": false,
"text": "<p>Use the <code>$global</code> in before your <code>$post</code></p>\n\n<p>For example:</p>\n\n<pre><co... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277836",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126419/"
] | I'm trying to make a code to display a image at the end of each post, but i need to show a specific image for each post category.
I'm using the code below:
```
<?php
if (in_category('category1')||){
echo '<img src="https://example.com/category1">';
}
elseif (in_category('category2')){
echo '<img src="https://example.com/category2">';
}
elseif (in_category('category3')){
echo '<img src="https://example.com/category3">';
}
elseif (in_category('category4')){
echo '<img src="https://example.com/category4">';
}
?>
```
It's working, but my problem now is that some posts have all the categories, and I need to test the primary category of the post.
Is there a function to do this? | This is how you can get the post object of a page with a matching path, minus the `/en` part:
```
$page_path = get_page_uri( get_queried_object_id() ); // en/page/child-page
$target_page_path = str_replace( 'en/', '', $page_path ); // page/child-page
$target_page = get_page_by_path( $target_page_path ); // WP_Post of target page.
``` |
277,837 | <p><code>$wpdb->insert()</code> returns <code>false</code> which I've learned means that the insert failed. Now, I would like to know why it fails with the insert.</p>
<p>According to this ticket <a href="https://core.trac.wordpress.org/ticket/32315" rel="noreferrer">https://core.trac.wordpress.org/ticket/32315</a> the problem could be that the value is either too long or contains bad characters.</p>
<p>Here is the insert query:</p>
<pre><code>$result = $wpdb->insert('table', $ins_args, array('%d', '%d', '%s', '%s', '%s', '%s'));
</code></pre>
<p>It's difficult to show the <code>$ins_args</code> array values since some values are pretty long. Specially the one for field named <code>value</code>. But I use type <code>longtext</code> for that field. And this insert is used a lot. And most times it works with success. So it really feels like a encoding or size problem.</p>
<p>How do I get to know what the problem is? <code>$wpdb->last_error</code> is empty</p>
| [
{
"answer_id": 326322,
"author": "Krzysiek Dróżdż",
"author_id": 34172,
"author_profile": "https://wordpress.stackexchange.com/users/34172",
"pm_score": 4,
"selected": false,
"text": "<p><code>$wpdb->insert()</code> method returns <code>false</code> if the row could not be inserted. O... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277837",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3216/"
] | `$wpdb->insert()` returns `false` which I've learned means that the insert failed. Now, I would like to know why it fails with the insert.
According to this ticket <https://core.trac.wordpress.org/ticket/32315> the problem could be that the value is either too long or contains bad characters.
Here is the insert query:
```
$result = $wpdb->insert('table', $ins_args, array('%d', '%d', '%s', '%s', '%s', '%s'));
```
It's difficult to show the `$ins_args` array values since some values are pretty long. Specially the one for field named `value`. But I use type `longtext` for that field. And this insert is used a lot. And most times it works with success. So it really feels like a encoding or size problem.
How do I get to know what the problem is? `$wpdb->last_error` is empty | `$wpdb->insert()` method returns `false` if the row could not be inserted. Otherwise, it returns the number of affected rows (which will always be 1).
You can turn error echoing on and off with the `show_errors` and `hide_errors`, respectively.
```
<?php $wpdb->show_errors(); ?>
<?php $wpdb->hide_errors(); ?>
```
You can also print the error (if any) generated by the most recent query with `print_error`.
```
<?php $wpdb->print_error(); ?>
```
You can also use `$last_error` field, which will contain the most recent error text generated by MySQL. |
277,841 | <p>I want to show all posts like <code>mywebsite.com/postname/1/</code>, <code>mywebsite.com/postname/2/</code> ...... <code>mywebsite.com/postname/7/</code> .. </p>
<p>Below code works perfectly for me, the only problem is that it shows only first posts <code>mywebsite.com/postname/</code>... </p>
<p>How can I do this? </p>
<pre><code><?php
/**
* Template Name: Random Post
* This template will only display the content you entered in the page editor
*/
?>
<html>
<head>
</head>
<body>
<?php
/*
Random Post Picker
Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'rand',
'order' => 'DESC',
// Using the date_query to filter posts from last week
'date_query' => array(
array(
'after' => '2 week ago'
)
)
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
// redirect to the random post
wp_redirect ( get_permalink () );
exit;
}
?>
</body>
</html>
</code></pre>
| [
{
"answer_id": 277844,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need to redirect the user to the random post page, and you can't even if you want, because you ca... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126422/"
] | I want to show all posts like `mywebsite.com/postname/1/`, `mywebsite.com/postname/2/` ...... `mywebsite.com/postname/7/` ..
Below code works perfectly for me, the only problem is that it shows only first posts `mywebsite.com/postname/`...
How can I do this?
```
<?php
/**
* Template Name: Random Post
* This template will only display the content you entered in the page editor
*/
?>
<html>
<head>
</head>
<body>
<?php
/*
Random Post Picker
Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'rand',
'order' => 'DESC',
// Using the date_query to filter posts from last week
'date_query' => array(
array(
'after' => '2 week ago'
)
)
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
// redirect to the random post
wp_redirect ( get_permalink () );
exit;
}
?>
</body>
</html>
``` | Only 1 post is displaying on your side because of you are using `exit()` in your loop. In your code when WP\_Query start and loop exit after one counter.
Remove `exit()` and use this code:
```
<?php
/*
* Random Post Picker
* Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'rand',
'order' => 'DESC',
// Using the date_query to filter posts from last week
'date_query' => array(
array(
'after' => '2 week ago'
)
)
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
if($my_random_post->have_posts()){
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
echo '<a href="'.get_the_permalink().'">'.get_the_title().'</a>';
}
}
?>
``` |
277,872 | <p>For some reason I am unable to output the custom post type content using the following code. what am I missing here? It works fine for <code>get_the_title</code> yet using <code>get_the_content</code> using same parameters yields nothing.</p>
<pre><code><?php
$query = new WP_Query( ['post_type' => 'testimonials', 'posts_per_page' => -1 ] );
foreach($query->get_posts() as $testimonial):
$meta = get_post_meta($testimonial->ID);
foreach($meta as &$m){
if(is_array($m)){
$m = $m[0];
}
} ?>
<div class="content"><?=get_the_content($testimonial->ID); ?></div>
<div class="author">- <?=get_the_title($testimonial->ID); ?> / <span class="company_name"><?=$meta['_testimonial_company_name'] ?></span></div>
<div class="link"><a href="<?=home_url('/testimonials'); ?>" title="View All Testimonials">View More</a></div>
<?php endforeach; ?>
</code></pre>
| [
{
"answer_id": 277844,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>You don't need to redirect the user to the random post page, and you can't even if you want, because you ca... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277872",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/1354/"
] | For some reason I am unable to output the custom post type content using the following code. what am I missing here? It works fine for `get_the_title` yet using `get_the_content` using same parameters yields nothing.
```
<?php
$query = new WP_Query( ['post_type' => 'testimonials', 'posts_per_page' => -1 ] );
foreach($query->get_posts() as $testimonial):
$meta = get_post_meta($testimonial->ID);
foreach($meta as &$m){
if(is_array($m)){
$m = $m[0];
}
} ?>
<div class="content"><?=get_the_content($testimonial->ID); ?></div>
<div class="author">- <?=get_the_title($testimonial->ID); ?> / <span class="company_name"><?=$meta['_testimonial_company_name'] ?></span></div>
<div class="link"><a href="<?=home_url('/testimonials'); ?>" title="View All Testimonials">View More</a></div>
<?php endforeach; ?>
``` | Only 1 post is displaying on your side because of you are using `exit()` in your loop. In your code when WP\_Query start and loop exit after one counter.
Remove `exit()` and use this code:
```
<?php
/*
* Random Post Picker
* Use on page to send viewer to random post optionally mod query
*/
// set arguments for WP_Query on published posts to get 1 at random
$args = array(
'post_type' => 'post',
'post_status' => 'publish',
'orderby' => 'rand',
'order' => 'DESC',
// Using the date_query to filter posts from last week
'date_query' => array(
array(
'after' => '2 week ago'
)
)
);
// It's time! Go someplace random
$my_random_post = new WP_Query ( $args );
if($my_random_post->have_posts()){
while ( $my_random_post->have_posts () ) {
$my_random_post->the_post ();
echo '<a href="'.get_the_permalink().'">'.get_the_title().'</a>';
}
}
?>
``` |
277,874 | <p>I have 2 menus.</p>
<ol>
<li>Main Navigation</li>
<li>Footer Navigation</li>
</ol>
<p>And 3 locations:</p>
<ol>
<li>Top Bar Navigation</li>
<li>Main Navigation</li>
<li>Footer Navigation</li>
</ol>
<p>If I try to create a new menu, wp displays <strong>error</strong></p>
<pre><code>A name is required for this term.
</code></pre>
<p>Obviously I am giving a name in <code>Menu Name</code> textbox...
Is this a bug?<br />
Is there a limit to WP menus?<br />
How can I go about adding another menu to use on an existing page as submenu within the page itself?<br />
Thanx</p>
<p><strong>EDIT 1</strong><br />
Do I need to add:</p>
<pre><code>function register_shop_submenu() {
register_nav_menu('shop-submenu',__( 'Shop Sub Menu' ));
}
add_action( 'init', 'register_shop_submenu' );
</code></pre>
<p>to <code>functions.php</code>?<br />
Is that it??<br />
The admin button option exists in vain??</p>
<p><strong>EDIT 2</strong><br />
The code above just added a new location.<br />
While <code>Manage Locations</code> tab on <code>admin panel</code> now displays:</p>
<blockquote>
<p>Your theme supports 4 menus. Select which menu appears in each
location.</p>
</blockquote>
<p>Clicking the <code>use new menu</code> next to the <code>drop-down</code> of this new location yields same error....<br />
rrrrrrrrrrrrrrr</p>
| [
{
"answer_id": 279647,
"author": "mperrin",
"author_id": 127640,
"author_profile": "https://wordpress.stackexchange.com/users/127640",
"pm_score": 2,
"selected": true,
"text": "<p>I got the same issue and found that the plugin <code>user-activity-log</code> was at the origin of the probl... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277874",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52581/"
] | I have 2 menus.
1. Main Navigation
2. Footer Navigation
And 3 locations:
1. Top Bar Navigation
2. Main Navigation
3. Footer Navigation
If I try to create a new menu, wp displays **error**
```
A name is required for this term.
```
Obviously I am giving a name in `Menu Name` textbox...
Is this a bug?
Is there a limit to WP menus?
How can I go about adding another menu to use on an existing page as submenu within the page itself?
Thanx
**EDIT 1**
Do I need to add:
```
function register_shop_submenu() {
register_nav_menu('shop-submenu',__( 'Shop Sub Menu' ));
}
add_action( 'init', 'register_shop_submenu' );
```
to `functions.php`?
Is that it??
The admin button option exists in vain??
**EDIT 2**
The code above just added a new location.
While `Manage Locations` tab on `admin panel` now displays:
>
> Your theme supports 4 menus. Select which menu appears in each
> location.
>
>
>
Clicking the `use new menu` next to the `drop-down` of this new location yields same error....
rrrrrrrrrrrrrrr | I got the same issue and found that the plugin `user-activity-log` was at the origin of the problem.
As I reported [here](https://wordpress.org/support/topic/cant-create-new-menus-a-name-is-required-for-this-term),the problem is related to the hooks:
* ual\_shook\_created\_term
* ual\_shook\_edited\_term
* ual\_shook\_delete\_term
They return nothing instead of the given term when the taxonomy is ‘nav\_menu’.
If you don't use this plugin, check the others plugins that call for example the `pre_insert_term` filter. They should return something. |
277,883 | <p>The theme I am using has a function to embed videos from Facebook. The problem is that whenever I use it it loads the SDK in <code>uk_UA</code> for whatever reasons (Ukrainian).</p>
<p>Nothing related to my Website or Facebook is using this language. After contacting the theme developers i was told it's not their fault and <em>might</em> be something related to the server configuration.</p>
<p>I tried an hacky solution I found here with adding to the <em>funcitons.php</em> the following script</p>
<pre><code>add_filter( 'the_content', 'facebook_sdk_replace' );
function facebook_sdk_replace( $content ) { if ( is_single() ) { $content = str_replace("/uk_UA/", "/en_US/", $content); } return $content; }
</code></pre>
<p>As it had no effect, the developer suggested I should add to the _header_php the following</p>
<pre><code><div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
</code></pre>
<p>The problem I am facing is that by doing so, I am getting the following error:</p>
<p><em>Cannot modify header information - headers already sent by...</em></p>
<p>Therefore, I reverted back my <em>header.php</em>.
Is there a way to fix this issue without altering the header?</p>
<p>Later edit:
The only code snippet I found is the following:</p>
<pre><code> /* $buffy = '
<div class="wpb_video_wrapper td-facebook-video">
<iframe src="' . td_global::$http_or_https . '://www.facebook.com/plugins/video.php?href=' . urlencode($videoUrl) . '&show_text=0" width="' . $width . '" height="' . $height . '" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true" ></iframe>
</div>
';
*/
/**
* cache & oembed implementation
*/
$cache_key = self::get_facebook_id($videoUrl);
$group = 'td_facebook_video';
if (td_remote_cache::is_expired($group, $cache_key) === true) {
// cache is expired - do a request
$facebook_api_json = td_remote_http::get_page('https://www.facebook.com/plugins/video/oembed.json/?url=' . urlencode($videoUrl) , __CLASS__);
if ($facebook_api_json !== false) {
$facebook_api = @json_decode($facebook_api_json);
//json data decode
if ($facebook_api === null and json_last_error() !== JSON_ERROR_NONE) {
td_log::log(__FILE__, __FUNCTION__, 'json decode failed for facebook video embed api', $videoUrl);
}
if (is_object($facebook_api) and !empty($facebook_api->html)) {
//add the html to the buffer
$buffy = '<div class="wpb_video_wrapper">' . $facebook_api->html . '</div>';
//set the cache
td_remote_cache::set($group, $cache_key, $facebook_api->html, self::$caching_time);
}
} else {
td_log::log(__FILE__, __FUNCTION__, 'facebook api html data cannot be retrieved/json request failed', $videoUrl);
}
} else {
// cache is valid
$api_html_embed_data = td_remote_cache::get($group, $cache_key);
$buffy = '<div class="wpb_video_wrapper">' . $api_html_embed_data . '</div>';
}
break;
</code></pre>
| [
{
"answer_id": 277955,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 1,
"selected": false,
"text": "<p>I've found your problem.</p>\n\n<p>You've inserted video from facebook on your page with facebook init ... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277883",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112590/"
] | The theme I am using has a function to embed videos from Facebook. The problem is that whenever I use it it loads the SDK in `uk_UA` for whatever reasons (Ukrainian).
Nothing related to my Website or Facebook is using this language. After contacting the theme developers i was told it's not their fault and *might* be something related to the server configuration.
I tried an hacky solution I found here with adding to the *funcitons.php* the following script
```
add_filter( 'the_content', 'facebook_sdk_replace' );
function facebook_sdk_replace( $content ) { if ( is_single() ) { $content = str_replace("/uk_UA/", "/en_US/", $content); } return $content; }
```
As it had no effect, the developer suggested I should add to the \_header\_php the following
```
<div id="fb-root"></div>
<script>(function(d, s, id) {
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s); js.id = id;
js.src = "//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.6";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>
```
The problem I am facing is that by doing so, I am getting the following error:
*Cannot modify header information - headers already sent by...*
Therefore, I reverted back my *header.php*.
Is there a way to fix this issue without altering the header?
Later edit:
The only code snippet I found is the following:
```
/* $buffy = '
<div class="wpb_video_wrapper td-facebook-video">
<iframe src="' . td_global::$http_or_https . '://www.facebook.com/plugins/video.php?href=' . urlencode($videoUrl) . '&show_text=0" width="' . $width . '" height="' . $height . '" scrolling="no" frameborder="0" allowTransparency="true" allowFullScreen="true" ></iframe>
</div>
';
*/
/**
* cache & oembed implementation
*/
$cache_key = self::get_facebook_id($videoUrl);
$group = 'td_facebook_video';
if (td_remote_cache::is_expired($group, $cache_key) === true) {
// cache is expired - do a request
$facebook_api_json = td_remote_http::get_page('https://www.facebook.com/plugins/video/oembed.json/?url=' . urlencode($videoUrl) , __CLASS__);
if ($facebook_api_json !== false) {
$facebook_api = @json_decode($facebook_api_json);
//json data decode
if ($facebook_api === null and json_last_error() !== JSON_ERROR_NONE) {
td_log::log(__FILE__, __FUNCTION__, 'json decode failed for facebook video embed api', $videoUrl);
}
if (is_object($facebook_api) and !empty($facebook_api->html)) {
//add the html to the buffer
$buffy = '<div class="wpb_video_wrapper">' . $facebook_api->html . '</div>';
//set the cache
td_remote_cache::set($group, $cache_key, $facebook_api->html, self::$caching_time);
}
} else {
td_log::log(__FILE__, __FUNCTION__, 'facebook api html data cannot be retrieved/json request failed', $videoUrl);
}
} else {
// cache is valid
$api_html_embed_data = td_remote_cache::get($group, $cache_key);
$buffy = '<div class="wpb_video_wrapper">' . $api_html_embed_data . '</div>';
}
break;
``` | The reason for this issue was given on the [wordpress core ticketing system](https://core.trac.wordpress.org/ticket/40656).
>
> This is probably something you should report to Facebook (good luck),
> as WordPress is correctly outputting the lang attribute on the html
> element. Facebook likely uses heuristics to determine if the actual
> page language is indeed English or not when en\_US is used, similar to
> what Google Chrome does. This is the unfortunate situation that the
> web finds itself in when services cannot trust web standards due to
> incorrect implementations (ie. sites not in US English but still using
> en\_US as the lang). In your situation you may be able to make use of
> the og:locale OpenGraph tag to persuade Facebook that your content
> really is in US English.
>
>
> |
277,894 | <p>I would like to insert a full-width DIV at the topmost location in the site I'm building. The project is in overtime. All the other work is done, but I have been asked to add a small logo and a single link on top. This would be on all pages, so it's a modification to the header. I've looked at several plugins, but they seem to be creating a "notification bar" by positioning and z-index. The theme we're using is Velux, a child of Primer. </p>
| [
{
"answer_id": 277895,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>Take a look at this question, and the first answer: <a href=\"https://wordpress.stackexchange.com/ques... | 2017/08/23 | [
"https://wordpress.stackexchange.com/questions/277894",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121627/"
] | I would like to insert a full-width DIV at the topmost location in the site I'm building. The project is in overtime. All the other work is done, but I have been asked to add a small logo and a single link on top. This would be on all pages, so it's a modification to the header. I've looked at several plugins, but they seem to be creating a "notification bar" by positioning and z-index. The theme we're using is Velux, a child of Primer. | As I can see in [wp-primer-theme sources](https://github.com/godaddy/wp-primer-theme/blob/develop/header.php): there are `do_action( 'primer_body' );` on the top of content and `do_action( 'primer_before_header' );` just below.
You can update your child theme functions.php with your own action
```
add_action('primer_before_header', function() {
echo '<div class="logo"></div>';
});
``` |
277,910 | <p>I have a single-site Wordpress installed on example.com. The DNS is configured so that www.example.com is an ALIAS of example.com. The client wants the user to see www. on their nav bar if they entered it, so this is important.</p>
<p>I hosted their website on an apache server running cpanel. The cpanel has the domain set as example.com. Before I installed wordpress, typing www.example.com brought up the directory and kept the www. on the nav bar, so great.</p>
<p>After I installed wordpress though, the www. is getting removed. When I did a redirect trace I found this odd 302 redirect:</p>
<pre><code>http://www.example.com
Status: 302 Found
Code: 302
Date: Thu, 24 Aug 2017 00:23:08 GMT
Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4
Location: https://example.com
Content-Length: 346
Connection: close
Content-Type: text/html; charset=iso-8859-1
</code></pre>
<p>I modified wordpress's htaccess file to force ssl, but I thought this is a 301:</p>
<pre><code>SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "example.com"
ErrorDocument 403 https://example.com
</code></pre>
<p>Okay, whatever. So I removed this section of code, the URL bar is still not preserving the www. This time I get a 301 redirect:</p>
<pre><code>http://www.example.com
Status: 301 Moved Permanently
Code: 301
Date: Thu, 24 Aug 2017 00:35:22 GMT
Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4
X-Powered-By: PHP/5.6.16
Location: http://example.com/
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8
</code></pre>
<p>I don't know where else to look. What do I need to do in cpanel, htaccess, or wordpress to have the URL bar preserve the www.</p>
| [
{
"answer_id": 277947,
"author": "MrWhite",
"author_id": 8259,
"author_profile": "https://wordpress.stackexchange.com/users/8259",
"pm_score": 2,
"selected": true,
"text": "<p>You need to set the canonical hostname (ie. with <code>www</code>) in the WordPress dashboard... Under Settings ... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/277910",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126470/"
] | I have a single-site Wordpress installed on example.com. The DNS is configured so that www.example.com is an ALIAS of example.com. The client wants the user to see www. on their nav bar if they entered it, so this is important.
I hosted their website on an apache server running cpanel. The cpanel has the domain set as example.com. Before I installed wordpress, typing www.example.com brought up the directory and kept the www. on the nav bar, so great.
After I installed wordpress though, the www. is getting removed. When I did a redirect trace I found this odd 302 redirect:
```
http://www.example.com
Status: 302 Found
Code: 302
Date: Thu, 24 Aug 2017 00:23:08 GMT
Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4
Location: https://example.com
Content-Length: 346
Connection: close
Content-Type: text/html; charset=iso-8859-1
```
I modified wordpress's htaccess file to force ssl, but I thought this is a 301:
```
SSLOptions +StrictRequire
SSLRequireSSL
SSLRequire %{HTTP_HOST} eq "example.com"
ErrorDocument 403 https://example.com
```
Okay, whatever. So I removed this section of code, the URL bar is still not preserving the www. This time I get a 301 redirect:
```
http://www.example.com
Status: 301 Moved Permanently
Code: 301
Date: Thu, 24 Aug 2017 00:35:22 GMT
Server: Apache/2.4.16 (Unix) OpenSSL/1.0.1e-fips mod_bwlimited/1.4
X-Powered-By: PHP/5.6.16
Location: http://example.com/
Content-Length: 0
Connection: close
Content-Type: text/html; charset=UTF-8
```
I don't know where else to look. What do I need to do in cpanel, htaccess, or wordpress to have the URL bar preserve the www. | You need to set the canonical hostname (ie. with `www`) in the WordPress dashboard... Under Settings > General and set the appropriate "WordPress Address (URL)" and "Site Address (URL)" properties.
Alternatively, these values can be *hardcoded* in `wp_config.php` by defining the `WP_HOME` and `WP_SITEURL` constants respectively.
Reference:
<https://codex.wordpress.org/Changing_The_Site_URL>
>
>
> ```
> SSLOptions +StrictRequire
> SSLRequireSSL
> SSLRequire %{HTTP_HOST} eq "example.com"
> ErrorDocument 403 https://example.com
>
> ```
>
>
Bit of an aside, but this is a very roundabout (not recommended) way of *redirecting* to HTTPS. Yes, this will trigger a 302 (temporary), not a 301 (permanent) redirect. This only redirects at all because of a side effect of `ErrorDocument`. And it only redirects to the document root, the requested URL is lost.
This code actually blocks access to the HTTP-only site and triggers a 403 Forbidden. Because you have set an absolute URL as the 2nd argument to the custom 403, Apache triggers an external (302) redirect to the URL, the root of your site.
If you don't have access to the server config, then this redirect is normally achieved using mod\_rewrite in `.htaccess`. For example:
```
RewriteCond %{HTTPS} !on
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
```
This would need to go *before* the existing WordPress directives in `.htaccess`.
---
Once you have set the appropriate hostname within WordPress, you can handle both HTTPS and www redirection in `.htaccess` if you wish (it would be slightly more efficient). For example:
```
RewriteCond %{HTTPS} !on [OR]
RewriteCond %{HTTP_HOST} !www\.
RewriteRule ^ https://www.example.com%{REQUEST_URI} [R=301,L]
```
Make sure you clear your browser cache before testing.
---
>
> I need the www. preserved only if the user entered it to begin with.
>
>
>
Unless you have a specific reason to do this, then this is generally a bad idea. It potentially creates *duplicate content*, although you can set a `rel="canonical"` tag in the `head` section to alleviate this, and you can specify a preference in Google Search Console (to avoid both hosts being indexed). But the stats will be split between them. How are you setting cookies? If you want cookies shared between both www and non-www (login, sessions, etc.), you'll need to ensure that cookies are set on the apex domain, regardless of which host is accessed - I don't believe this is the default behaviour.
Anyway, if you want to redirect HTTP to HTTPS but preserve whatever host has been accessed (www, non-www or xyz alias) then this is a much simpler redirect as you can reference the `HTTP_HOST` server variable. For example:
```
RewriteCond %{HTTPS} !on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]
``` |
277,928 | <p>I haven't been able to find this on google and I thought this was a common requirement.</p>
<p>Is there a way to add a 5 stars (or whatever rating) to my products with a single plugin or PHP code? I need to show stars in every catalog so I can test my design.</p>
| [
{
"answer_id": 277935,
"author": "Nikola Miljković",
"author_id": 111583,
"author_profile": "https://wordpress.stackexchange.com/users/111583",
"pm_score": 2,
"selected": false,
"text": "<p>Since you need it just for visual purposes, it's better if you don't save the rating value to the ... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/277928",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126489/"
] | I haven't been able to find this on google and I thought this was a common requirement.
Is there a way to add a 5 stars (or whatever rating) to my products with a single plugin or PHP code? I need to show stars in every catalog so I can test my design. | [@Nikola](https://wordpress.stackexchange.com/users/111583/nikola-miljkovi%C4%87)'s [answer](https://wordpress.stackexchange.com/a/277935/43098) gives you what you want to need without saving anything to the database. If **you** need to save the values to the database and directly execute SQL, you can do the following.
Basically WooCommerce stores product reviews data as a postmeta under [meta keys](https://github.com/woocommerce/woocommerce/blob/bdba4f76362c3b3646c775c10e87f32dd062a25c/includes/data-stores/class-wc-product-data-store-cpt.php#L52-L54)
* \_wc\_rating\_count
* \_wc\_average\_rating
* \_wc\_review\_count
```
UPDATE fs_postmeta SET meta_value = 5
WHERE meta_key = '_wc_average_rating' AND post_id = 564;
UPDATE fs_postmeta SET meta_value = 105
WHERE meta_key = '_wc_review_count' AND post_id = 564;
```
or
```
<?php
/*
Plugin Name: BK
Version: 0.0.1
*/
function bk_get_all_products( ) {
$ps = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '-1'
) );
$arr = array();
while($ps->have_posts()){
$ps->the_post();
$arr[] = get_the_ID();
}
return $arr;
}
add_action('init','bk');
function bk(){
$products = bk_get_all_products();
// $re = array(
// "1" => 1,
// "2" => 2,
// "3" => 3,
// "4" => 5,
// "5" => 6,
// );
foreach ($products as $key => $value) {
update_post_meta( $value, '_wc_average_rating', 1 );
update_post_meta( $value, '_wc_review_count', 15 );
// update_post_meta( $value, '_wc_rating_count', $re );
}
}
```
Remember with this we are not changing the reviews list that appears under product tabs. |
277,939 | <p>I have to run a php function for around 10 minutes. Now I am sheduling the job as a wp-cron-job. But it is getting timed out after 30seconds which is the maximum execution time for php. How to get rid of this timeout issue?</p>
| [
{
"answer_id": 277935,
"author": "Nikola Miljković",
"author_id": 111583,
"author_profile": "https://wordpress.stackexchange.com/users/111583",
"pm_score": 2,
"selected": false,
"text": "<p>Since you need it just for visual purposes, it's better if you don't save the rating value to the ... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/277939",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119861/"
] | I have to run a php function for around 10 minutes. Now I am sheduling the job as a wp-cron-job. But it is getting timed out after 30seconds which is the maximum execution time for php. How to get rid of this timeout issue? | [@Nikola](https://wordpress.stackexchange.com/users/111583/nikola-miljkovi%C4%87)'s [answer](https://wordpress.stackexchange.com/a/277935/43098) gives you what you want to need without saving anything to the database. If **you** need to save the values to the database and directly execute SQL, you can do the following.
Basically WooCommerce stores product reviews data as a postmeta under [meta keys](https://github.com/woocommerce/woocommerce/blob/bdba4f76362c3b3646c775c10e87f32dd062a25c/includes/data-stores/class-wc-product-data-store-cpt.php#L52-L54)
* \_wc\_rating\_count
* \_wc\_average\_rating
* \_wc\_review\_count
```
UPDATE fs_postmeta SET meta_value = 5
WHERE meta_key = '_wc_average_rating' AND post_id = 564;
UPDATE fs_postmeta SET meta_value = 105
WHERE meta_key = '_wc_review_count' AND post_id = 564;
```
or
```
<?php
/*
Plugin Name: BK
Version: 0.0.1
*/
function bk_get_all_products( ) {
$ps = new WP_Query( array(
'post_type' => 'product',
'post_status' => 'publish',
'posts_per_page' => '-1'
) );
$arr = array();
while($ps->have_posts()){
$ps->the_post();
$arr[] = get_the_ID();
}
return $arr;
}
add_action('init','bk');
function bk(){
$products = bk_get_all_products();
// $re = array(
// "1" => 1,
// "2" => 2,
// "3" => 3,
// "4" => 5,
// "5" => 6,
// );
foreach ($products as $key => $value) {
update_post_meta( $value, '_wc_average_rating', 1 );
update_post_meta( $value, '_wc_review_count', 15 );
// update_post_meta( $value, '_wc_rating_count', $re );
}
}
```
Remember with this we are not changing the reviews list that appears under product tabs. |
277,943 | <p>I can't get any 'category' loops to load.</p>
<p>Here is my work flow.</p>
<p>I create a page called category.php and placed the following code (exactly like this):</p>
<pre><code><?php
/*
* Template Name: Category
*/
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
get_header();
?>
<?php while ( have_posts() ) : the_post(); ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
<?php get_footer(); ?>
</code></pre>
<p>I then created a page called 'Category' in the WP Admin and then selected the template for category.php and nothing - zero.</p>
<p>Why wouldn't this load posts that belong to the relevant category?</p>
<p>Thanks for all help with this...</p>
| [
{
"answer_id": 277949,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You don't assign category templates to pages. They are templates that will be used <em>automatically</e... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/277943",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | I can't get any 'category' loops to load.
Here is my work flow.
I create a page called category.php and placed the following code (exactly like this):
```
<?php
/*
* Template Name: Category
*/
if (!defined('ABSPATH'))
exit; // Exit if accessed directly
get_header();
?>
<?php while ( have_posts() ) : the_post(); ?>
<h1 class="entry-title"><?php the_title(); ?></h1>
<div class="entry-content">
<?php the_content(); ?>
<?php endwhile; // end of the loop. ?>
<?php get_footer(); ?>
```
I then created a page called 'Category' in the WP Admin and then selected the template for category.php and nothing - zero.
Why wouldn't this load posts that belong to the relevant category?
Thanks for all help with this... | You don't assign category templates to pages. They are templates that will be used *automatically* when you view a category.
Read the [Template Hierarchy](https://developer.wordpress.org/themes/basics/template-hierarchy/) documentation. You're using WordPress completely wrong. You don't create pages for archives, they exist automatically. |
277,953 | <p>I'm trying to add a custom field of event_month when a post is published or saved. I'm using the save_post action and getting the contents of a custom field containing the date and trying to store this in a separate custom field with just the month. This works perfectly when saving a post that has already been created. I've shown my code below.</p>
<pre><code>add_action('save_post', 'update_event_date');
function update_event_date($post_id){
$post_type = get_post_type($post_id);
$event_datee = get_post_meta($post_id, '_EventStartDate', true);
if ($post_type == 'tribe_events'){
$month = date("m",strtotime($event_datee));
update_post_meta($post_id, 'event_month', $month);
}
}
</code></pre>
<p>The problem arises when creating a new post. I think this is because the action fires before the <code>_EventStartDate</code> meta has been created and therefore the month can't be taken from this.</p>
<p>The hook is firing correctly and as intended when saving/updating a post but doesn't correctly get the month from the meta when creating a new post.</p>
<p>I'd really appreciate it if someone could provide me with some guidance.</p>
| [
{
"answer_id": 277954,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>pre_post_update</code> instead of <code>save_post</code></p>\n\n<p>Full explanation <a href=\... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/277953",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/118170/"
] | I'm trying to add a custom field of event\_month when a post is published or saved. I'm using the save\_post action and getting the contents of a custom field containing the date and trying to store this in a separate custom field with just the month. This works perfectly when saving a post that has already been created. I've shown my code below.
```
add_action('save_post', 'update_event_date');
function update_event_date($post_id){
$post_type = get_post_type($post_id);
$event_datee = get_post_meta($post_id, '_EventStartDate', true);
if ($post_type == 'tribe_events'){
$month = date("m",strtotime($event_datee));
update_post_meta($post_id, 'event_month', $month);
}
}
```
The problem arises when creating a new post. I think this is because the action fires before the `_EventStartDate` meta has been created and therefore the month can't be taken from this.
The hook is firing correctly and as intended when saving/updating a post but doesn't correctly get the month from the meta when creating a new post.
I'd really appreciate it if someone could provide me with some guidance. | You can hook into [`post_updated`](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) action, if you want to access the post's data *after* it's been published. This hook passes the post's ID, inundated post object, and updated post object.
```
add_action( 'post_updated', 'update_event_date', 10, 3 );
function update_event_date( $post_id, $post_after, $post_before ){
$post_type = get_post_type( $post_id );
$event_datee = get_post_meta( $post_id, '_EventStartDate', true );
if ( $post_type == 'tribe_events' ) {
$month = date( "m",strtotime( $event_datee ) );
update_post_meta( $post_id, 'event_month', $month );
}
}
``` |
277,956 | <p>I am using shortcode and in that I want to change the title by setting the value from the database using custom tables.I have tried using the_title filter as follows </p>
<pre><code>add_filter('the_title','set_page_title', 10, 2);
function set_page_title($title, $id){
if(in_the_loop()) {
return 'sdfdsfdsf';
}
return $title;
}
</code></pre>
<p>But my problem is I want to change this only on a specific page not all page.</p>
<p>This is my shortcode callback function </p>
<pre><code>function bmg_company_detail_shortcode($args, $content) {
global $wpdb;
$table_name = $wpdb->prefix . 'bmg_company';
$company_id = $_GET['id'];
$output = '';
$result = $wpdb->get_results($wpdb->prepare("SELECT id,maincategoryid,name,website,yearfounded,supportpageurl,contactpage,country,about, isactive,contact_name,contact_email,contact_phone,support_phone,open_times,support_email, username, password from $table_name where id=%s", $company_id));
if($result) {
foreach($result as $row) {
set_page_title('',$row->name);
$output = '
<h3 class="bmg-company-title">'. $row->name .'</h3>
';
}
}
return $output;
}
</code></pre>
<p>I want to send the parameter to the function set_page_title but that doesn't work. I want this to happen only on page called company.</p>
| [
{
"answer_id": 277954,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>pre_post_update</code> instead of <code>save_post</code></p>\n\n<p>Full explanation <a href=\... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/277956",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123210/"
] | I am using shortcode and in that I want to change the title by setting the value from the database using custom tables.I have tried using the\_title filter as follows
```
add_filter('the_title','set_page_title', 10, 2);
function set_page_title($title, $id){
if(in_the_loop()) {
return 'sdfdsfdsf';
}
return $title;
}
```
But my problem is I want to change this only on a specific page not all page.
This is my shortcode callback function
```
function bmg_company_detail_shortcode($args, $content) {
global $wpdb;
$table_name = $wpdb->prefix . 'bmg_company';
$company_id = $_GET['id'];
$output = '';
$result = $wpdb->get_results($wpdb->prepare("SELECT id,maincategoryid,name,website,yearfounded,supportpageurl,contactpage,country,about, isactive,contact_name,contact_email,contact_phone,support_phone,open_times,support_email, username, password from $table_name where id=%s", $company_id));
if($result) {
foreach($result as $row) {
set_page_title('',$row->name);
$output = '
<h3 class="bmg-company-title">'. $row->name .'</h3>
';
}
}
return $output;
}
```
I want to send the parameter to the function set\_page\_title but that doesn't work. I want this to happen only on page called company. | You can hook into [`post_updated`](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) action, if you want to access the post's data *after* it's been published. This hook passes the post's ID, inundated post object, and updated post object.
```
add_action( 'post_updated', 'update_event_date', 10, 3 );
function update_event_date( $post_id, $post_after, $post_before ){
$post_type = get_post_type( $post_id );
$event_datee = get_post_meta( $post_id, '_EventStartDate', true );
if ( $post_type == 'tribe_events' ) {
$month = date( "m",strtotime( $event_datee ) );
update_post_meta( $post_id, 'event_month', $month );
}
}
``` |
278,015 | <p>I am using the Zephyr theme for my site, but want to switch to a child theme as this seems to be recommended in case the theme is updated. I am worried I will lose my customization etc. </p>
<p>Are there any safeguards against this?</p>
| [
{
"answer_id": 277954,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>Use <code>pre_post_update</code> instead of <code>save_post</code></p>\n\n<p>Full explanation <a href=\... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/278015",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126536/"
] | I am using the Zephyr theme for my site, but want to switch to a child theme as this seems to be recommended in case the theme is updated. I am worried I will lose my customization etc.
Are there any safeguards against this? | You can hook into [`post_updated`](https://codex.wordpress.org/Plugin_API/Action_Reference/post_updated) action, if you want to access the post's data *after* it's been published. This hook passes the post's ID, inundated post object, and updated post object.
```
add_action( 'post_updated', 'update_event_date', 10, 3 );
function update_event_date( $post_id, $post_after, $post_before ){
$post_type = get_post_type( $post_id );
$event_datee = get_post_meta( $post_id, '_EventStartDate', true );
if ( $post_type == 'tribe_events' ) {
$month = date( "m",strtotime( $event_datee ) );
update_post_meta( $post_id, 'event_month', $month );
}
}
``` |
278,035 | <p>I have a quite extensive database, 30000+ items, and using this:</p>
<pre><code>$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s
);
$post_counts = count(get_posts($args));
</code></pre>
<p>seems to take forever.</p>
<pre><code>I solved this particular case with:
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'books' AND post_status = 'publish' AND post_title LIKE '%".$s."%'");
</code></pre>
<p>But I have many queries that I'd like to count without having to write them by hand. Is there any way to count the posts with the $args using wordpress native functions without having to store the whole querie but only the count?</p>
| [
{
"answer_id": 278036,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>There is <code>$wpdb->num_rows</code> parameter. \nBut I suggest you do it with </p>\n\n<pre><code>$... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/278035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/116224/"
] | I have a quite extensive database, 30000+ items, and using this:
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s
);
$post_counts = count(get_posts($args));
```
seems to take forever.
```
I solved this particular case with:
$post_count = $wpdb->get_var("SELECT COUNT(*) FROM $wpdb->posts WHERE post_type = 'books' AND post_status = 'publish' AND post_title LIKE '%".$s."%'");
```
But I have many queries that I'd like to count without having to write them by hand. Is there any way to count the posts with the $args using wordpress native functions without having to store the whole querie but only the count? | Here's one thing you could do. Create a WP\_Query object but only include ids:
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s,
'fields' => 'ids',
);
$query = new WP_Query( $args );
$post_counts = $query->post_count;
wp_reset_postdata();
```
By using [`fields => ids`](https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter) you're only returning the IDs. Also, WP\_Query already does a count and supplies it as a property: [`post_count`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties). Finally, since we are using a WP\_Query we need to reset the globals with [`wp_reset_postdata()`](https://codex.wordpress.org/Function_Reference/wp_reset_postdata). |
278,051 | <p>I have been trying to figure out how to add session variables to WordPress Custom Pages for the past few days but have still been unable to find a solution. From researching it seems WordPress does not allow you to move Session variables from one page to the next. I have tried removing all of the 'session_start();' from each page and adding the below to functions.php file.</p>
<pre><code>add_action('init', 'myStartSession', 1);
function myStartSession() {
if(!session_id()) {
session_start();
}
}
</code></pre>
<p>Have also tried adding code below to the wp-config.php but to no avail.</p>
<pre><code>if (!session_id())
session_start();
</code></pre>
<p>The session will create a unique id for each user which will be checked on the next page to see if it equals the previous id. The first page code is as follows:</p>
<pre><code>$_SESSION['t'] = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1');
session_write_close();
</code></pre>
<p>The next page is:</p>
<pre><code>$testValue = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1');
if ($testValue == $_SESSION['t'])
{$passFlag = 1;}
else
{$passFlag = 0;}
session_regenerate_id();
</code></pre>
<p>'session_write_close();' is called further down on this page.
Any help would be greatly appreciated and if you need any further information please don't hesitate to message. Thanks.</p>
| [
{
"answer_id": 278036,
"author": "Anton Lukin",
"author_id": 126253,
"author_profile": "https://wordpress.stackexchange.com/users/126253",
"pm_score": 0,
"selected": false,
"text": "<p>There is <code>$wpdb->num_rows</code> parameter. \nBut I suggest you do it with </p>\n\n<pre><code>$... | 2017/08/24 | [
"https://wordpress.stackexchange.com/questions/278051",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126550/"
] | I have been trying to figure out how to add session variables to WordPress Custom Pages for the past few days but have still been unable to find a solution. From researching it seems WordPress does not allow you to move Session variables from one page to the next. I have tried removing all of the 'session\_start();' from each page and adding the below to functions.php file.
```
add_action('init', 'myStartSession', 1);
function myStartSession() {
if(!session_id()) {
session_start();
}
}
```
Have also tried adding code below to the wp-config.php but to no avail.
```
if (!session_id())
session_start();
```
The session will create a unique id for each user which will be checked on the next page to see if it equals the previous id. The first page code is as follows:
```
$_SESSION['t'] = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1');
session_write_close();
```
The next page is:
```
$testValue = md5(session_id().'3ac49262e797b6a51b6362e264d9dbe1');
if ($testValue == $_SESSION['t'])
{$passFlag = 1;}
else
{$passFlag = 0;}
session_regenerate_id();
```
'session\_write\_close();' is called further down on this page.
Any help would be greatly appreciated and if you need any further information please don't hesitate to message. Thanks. | Here's one thing you could do. Create a WP\_Query object but only include ids:
```
$args = array(
'posts_per_page' => -1,
'post_type' => 'books',
's' => $s,
'fields' => 'ids',
);
$query = new WP_Query( $args );
$post_counts = $query->post_count;
wp_reset_postdata();
```
By using [`fields => ids`](https://codex.wordpress.org/Class_Reference/WP_Query#Return_Fields_Parameter) you're only returning the IDs. Also, WP\_Query already does a count and supplies it as a property: [`post_count`](https://codex.wordpress.org/Class_Reference/WP_Query#Properties). Finally, since we are using a WP\_Query we need to reset the globals with [`wp_reset_postdata()`](https://codex.wordpress.org/Function_Reference/wp_reset_postdata). |
278,076 | <p>I would like to display the last 3 articles of category 'camping-camping' with a shortcode but the function does not seem valid, an idea ?</p>
<pre><code>function derniers_articles_camping() {
// the query
$the_query = new WP_Query( array(
'category_name' => 'location-camping-var',
'posts_per_page' => 3,
));
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$contenu = '
</code></pre>
<p></p>
<pre><code><div class="effect-jazz">'.the_post_thumbnail();.'<div class="jazz-try">
<div class="h3"><a href="'.the_permalink();.'">'.the_title();.'</a></div>
<p>'the_resume(60);.'</p>
</div>
</div>
</code></pre>
<p></p>
<pre><code> ';
endwhile;
wp_reset_postdata();
return $contenu;
endif;
}
add_shortcode('camping', 'derniers_articles_camping');
</code></pre>
<p>Thank you in advance for your help !</p>
| [
{
"answer_id": 278070,
"author": "Atul",
"author_id": 126565,
"author_profile": "https://wordpress.stackexchange.com/users/126565",
"pm_score": -1,
"selected": false,
"text": "<p>If there are only few images which are required for the plugin itself then store it under plugins own image f... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278076",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109045/"
] | I would like to display the last 3 articles of category 'camping-camping' with a shortcode but the function does not seem valid, an idea ?
```
function derniers_articles_camping() {
// the query
$the_query = new WP_Query( array(
'category_name' => 'location-camping-var',
'posts_per_page' => 3,
));
if ( $the_query->have_posts() ) :
while ( $the_query->have_posts() ) : $the_query->the_post();
$contenu = '
```
```
<div class="effect-jazz">'.the_post_thumbnail();.'<div class="jazz-try">
<div class="h3"><a href="'.the_permalink();.'">'.the_title();.'</a></div>
<p>'the_resume(60);.'</p>
</div>
</div>
```
```
';
endwhile;
wp_reset_postdata();
return $contenu;
endif;
}
add_shortcode('camping', 'derniers_articles_camping');
```
Thank you in advance for your help ! | The only directory in which you have guaranteed write access is the uploads directory. Even your plugin's directory might be write protected, the same for `wp-content` (which doesn't even have to exist). |
278,078 | <p>Probably a silly one but hopefully someone has encountered this before.</p>
<h2>The problem:</h2>
<p>I have a local copy of my Wordpress site that works fine and a copy on the server. After uploading I get <code>Call to undefined function</code> from within the child theme's <code>header.php</code> referencing a function that should exist in its parent theme.</p>
<h2>Full error message:</h2>
<pre><code>Fatal error: Call to undefined function shapely_get_header_logo() in /home/twimp/training.twimp.co.uk/wp-content/themes/shapely-child/header.php on line 33
</code></pre>
<h2>Background:</h2>
<p>The server has recently had a Wordpress site running on it fine so I don't have particular reason to think its anything related to its configuration.</p>
<p>I'm using a different theme from the last time it was uploaded so I started by uploading these two directories, my child theme and its parent. A lot of changes had been made with the plugins so I cleared the plugins directory and re-uploaded everything.</p>
<p>I also completely wiped the database and imported from local and then modified the options table to put the correct server url back in.</p>
<p>wp_config has not been touched and so it still points at the right database.</p>
<h2>What I've tried:</h2>
<p>I initially thought that maybe a file or two hadn't uploaded so I checked the FTP server side by side, starting with the files it should have been looking at. They all seem to be there.</p>
<p>I thought perhaps it was a file permission problem so I reset all of the files in the wp_content directory.</p>
<p>Just in case I was losing my mind, I have tried making small changes to the <code>header.php</code> just to confirm it is in fact the right file on the right server and the database is looking at the right files. All normal.</p>
<p>I tried commenting out the erroneous function call but all that did was move the error down to the next function called.</p>
<p>I checked the <code>style.css</code> to check its parent declaration was correct. I noticed there is a difference in file size between server and local but I've downloaded the file and it looks correct.</p>
<p>I modified the <code>functions.php</code> on both parent and child simply to <code>var_dump</code> the current user. The child theme printed, the parent theme did not.</p>
<p><strong>Conclusion:</strong> It seems as if my child theme is not aware of its parent when on the server but I can't figure out why that might be.</p>
<h2>Child theme style.css</h2>
<pre><code>/*
Theme Name: Shapely Child
Template: Shapely
Version: 1.1.7
Author: colorlib
Author URI: LINK
*/
</code></pre>
<h2>Parent theme style.css</h2>
<pre><code>/*
Theme Name: Shapely
Theme URI: LINK
Author: colorlib
Author URI: LINK
...
*/
</code></pre>
<p>I apologise in advance if I've skipped over anything essential.</p>
<p>Any and all help is greatly appreciated.</p>
| [
{
"answer_id": 278070,
"author": "Atul",
"author_id": 126565,
"author_profile": "https://wordpress.stackexchange.com/users/126565",
"pm_score": -1,
"selected": false,
"text": "<p>If there are only few images which are required for the plugin itself then store it under plugins own image f... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278078",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122832/"
] | Probably a silly one but hopefully someone has encountered this before.
The problem:
------------
I have a local copy of my Wordpress site that works fine and a copy on the server. After uploading I get `Call to undefined function` from within the child theme's `header.php` referencing a function that should exist in its parent theme.
Full error message:
-------------------
```
Fatal error: Call to undefined function shapely_get_header_logo() in /home/twimp/training.twimp.co.uk/wp-content/themes/shapely-child/header.php on line 33
```
Background:
-----------
The server has recently had a Wordpress site running on it fine so I don't have particular reason to think its anything related to its configuration.
I'm using a different theme from the last time it was uploaded so I started by uploading these two directories, my child theme and its parent. A lot of changes had been made with the plugins so I cleared the plugins directory and re-uploaded everything.
I also completely wiped the database and imported from local and then modified the options table to put the correct server url back in.
wp\_config has not been touched and so it still points at the right database.
What I've tried:
----------------
I initially thought that maybe a file or two hadn't uploaded so I checked the FTP server side by side, starting with the files it should have been looking at. They all seem to be there.
I thought perhaps it was a file permission problem so I reset all of the files in the wp\_content directory.
Just in case I was losing my mind, I have tried making small changes to the `header.php` just to confirm it is in fact the right file on the right server and the database is looking at the right files. All normal.
I tried commenting out the erroneous function call but all that did was move the error down to the next function called.
I checked the `style.css` to check its parent declaration was correct. I noticed there is a difference in file size between server and local but I've downloaded the file and it looks correct.
I modified the `functions.php` on both parent and child simply to `var_dump` the current user. The child theme printed, the parent theme did not.
**Conclusion:** It seems as if my child theme is not aware of its parent when on the server but I can't figure out why that might be.
Child theme style.css
---------------------
```
/*
Theme Name: Shapely Child
Template: Shapely
Version: 1.1.7
Author: colorlib
Author URI: LINK
*/
```
Parent theme style.css
----------------------
```
/*
Theme Name: Shapely
Theme URI: LINK
Author: colorlib
Author URI: LINK
...
*/
```
I apologise in advance if I've skipped over anything essential.
Any and all help is greatly appreciated. | The only directory in which you have guaranteed write access is the uploads directory. Even your plugin's directory might be write protected, the same for `wp-content` (which doesn't even have to exist). |
278,081 | <p>I have a plugin rejected by wordpress.org, one of the resasons is this:</p>
<blockquote>
<h2>Unsafe Requiring of Common Libraries Since you're using a common library, it's important that you enqueue it safely. Example(s):</h2>
<p>require_once('jsonld.php');</p>
<p>Since that is a common library, you need to detect IF the code is
already included and not re-include it, as doing so will cause
conflicts if two people call the same defines and functions.</p>
</blockquote>
<p>I understand about enqueueing jQuery and CSS - but this is a PHP script with multiple functions.</p>
<ol>
<li>If this script is common do I need to just reference it in the WP Core?</li>
<li>Otherwise do I need to just look at the functions I'm calling and wrap them in a class (I'm uncertain about this) or can I refer to the whole php script?</li>
<li>What is the standard way of doing this?</li>
</ol>
<p>Thanks</p>
<p>Dan</p>
| [
{
"answer_id": 278082,
"author": "Fabio Marzocca",
"author_id": 65278,
"author_profile": "https://wordpress.stackexchange.com/users/65278",
"pm_score": 0,
"selected": false,
"text": "<p>You can check included files first.</p>\n\n<pre><code>$included_files = get_included_files();\n\nif (!... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278081",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/17157/"
] | I have a plugin rejected by wordpress.org, one of the resasons is this:
>
> Unsafe Requiring of Common Libraries Since you're using a common library, it's important that you enqueue it safely. Example(s):
> --------------------------------------------------------------------------------------------------------------------------------
>
>
> require\_once('jsonld.php');
>
>
> Since that is a common library, you need to detect IF the code is
> already included and not re-include it, as doing so will cause
> conflicts if two people call the same defines and functions.
>
>
>
I understand about enqueueing jQuery and CSS - but this is a PHP script with multiple functions.
1. If this script is common do I need to just reference it in the WP Core?
2. Otherwise do I need to just look at the functions I'm calling and wrap them in a class (I'm uncertain about this) or can I refer to the whole php script?
3. What is the standard way of doing this?
Thanks
Dan | 1. No, it just means it's used by many plugins, not that Core includes it.
2. Many of the functions in that library seem to use the `JsonLdProcessor` class that is also in that library, I'd check for that before including:
```
if ( ! class_exists( 'JsonLdProcessor' ) ) {
require_once( 'jsonld.php' )
}
``` |
278,096 | <p>I have 4 users roles on my wordpress platform (role1, role2, role3, role4)</p>
<p>I'm looking for to show front-end top bar only for Role1 Role2.</p>
<p>how can i add a condition on this code to show it only for this 2 roles?</p>
<pre><code>function wpc_show_admin_bar() {
return true;
}
add_filter('show_admin_bar' , 'wpc_show_admin_bar');
</code></pre>
<p>thanks</p>
| [
{
"answer_id": 278098,
"author": "Christine Cooper",
"author_id": 24875,
"author_profile": "https://wordpress.stackexchange.com/users/24875",
"pm_score": 4,
"selected": true,
"text": "<p>You can disable the admin bar via function:</p>\n\n<pre><code>show_admin_bar(false);\n</code></pre>\n... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278096",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119785/"
] | I have 4 users roles on my wordpress platform (role1, role2, role3, role4)
I'm looking for to show front-end top bar only for Role1 Role2.
how can i add a condition on this code to show it only for this 2 roles?
```
function wpc_show_admin_bar() {
return true;
}
add_filter('show_admin_bar' , 'wpc_show_admin_bar');
```
thanks | You can disable the admin bar via function:
```
show_admin_bar(false);
```
So with that in mind, we can hook into `after_setup_theme` and hide the admin bar for all users except `administrator` and `contributor`:
```
function cc_wpse_278096_disable_admin_bar() {
if (current_user_can('administrator') || current_user_can('contributor') ) {
// user can view admin bar
show_admin_bar(true); // this line isn't essentially needed by default...
} else {
// hide admin bar
show_admin_bar(false);
}
}
add_action('after_setup_theme', 'cc_wpse_278096_disable_admin_bar');
```
I am only using `administrator` and `contributor` as example. You can of course change this and add more roles. |
278,099 | <p>I'm creating a single page app with WP REST API and AngularJS. After solving a problem with nonces on <a href="https://wordpress.stackexchange.com/questions/278011/wp-rest-api-check-if-user-is-logged-in">this question</a>, now i'm facing something else.
To test the chance of adding fields and making them protected against non-logged users, i tried to create a custom field which exposes the result of <code>wp_verify_nonce</code></p>
<pre><code>if (isset($_SERVER['HTTP_X_WP_NONCE'])) {
$nonce = $_SERVER['HTTP_X_WP_NONCE'];
$nonce_verified = wp_verify_nonce($_SERVER['HTTP_X_WP_NONCE'], 'wp_rest');
}
return array('nonce' => $nonce,
'nonce_verified' => $nonce_verified);
</code></pre>
<p>Of course, this is a test and will remain so. Nonce is exposed and so is <code>nonce_verified</code>. At this point, i tried to login/logout a user and require this endpoint and users/me. But it happened that my nonce is always verified, either with logged in or logged out user. Nonce itself changes while doing this; still, when logged out, it's the same for all of its lifetime.</p>
<p>To create my nonce, i used a localized code as in my previous question:</p>
<pre><code>wp_localize_script('angularjs', 'params', array(
'nonce' => wp_create_nonce('wp_rest'),
));
</code></pre>
<p>which is passed through javascript, as i saw in a tutorial about AngularJS. Although this nonce gets validated, query to <code>users/me</code> leads to a 403 when not logged, as expected.</p>
<p>My theory is that a nonce for non-logged users is being created, so there is always a valid nonce available.
Should i protect nonce creation with <code>is_user_logged_in()</code>? Or should i hook the nonce creation somewhere? Thank you.</p>
| [
{
"answer_id": 278100,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress nonces are not real nonces, they remain valid for a period of 12 to 24 hours and will return the ... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278099",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119611/"
] | I'm creating a single page app with WP REST API and AngularJS. After solving a problem with nonces on [this question](https://wordpress.stackexchange.com/questions/278011/wp-rest-api-check-if-user-is-logged-in), now i'm facing something else.
To test the chance of adding fields and making them protected against non-logged users, i tried to create a custom field which exposes the result of `wp_verify_nonce`
```
if (isset($_SERVER['HTTP_X_WP_NONCE'])) {
$nonce = $_SERVER['HTTP_X_WP_NONCE'];
$nonce_verified = wp_verify_nonce($_SERVER['HTTP_X_WP_NONCE'], 'wp_rest');
}
return array('nonce' => $nonce,
'nonce_verified' => $nonce_verified);
```
Of course, this is a test and will remain so. Nonce is exposed and so is `nonce_verified`. At this point, i tried to login/logout a user and require this endpoint and users/me. But it happened that my nonce is always verified, either with logged in or logged out user. Nonce itself changes while doing this; still, when logged out, it's the same for all of its lifetime.
To create my nonce, i used a localized code as in my previous question:
```
wp_localize_script('angularjs', 'params', array(
'nonce' => wp_create_nonce('wp_rest'),
));
```
which is passed through javascript, as i saw in a tutorial about AngularJS. Although this nonce gets validated, query to `users/me` leads to a 403 when not logged, as expected.
My theory is that a nonce for non-logged users is being created, so there is always a valid nonce available.
Should i protect nonce creation with `is_user_logged_in()`? Or should i hook the nonce creation somewhere? Thank you. | The true reason of not using nonces for non logged in users, is that it adds a pointless burden on their usage as they need to refresh the page when the nonce expire, and the only way they will know that they need to do it is when something do not work.
There is probably no reason to avoid generating it, but if you expect that your "app" will be used/open for more then 12 hours (that is the "tick" time used to calculate wordpress nonces) then either you need to also have an automatic way to refresh the nonce (might be a good idea for logged in users as well) or avoid using it in the first place. |
278,109 | <p>I'm trying to exclude the latest two blog posts from a page.
I know it's possible to do this with <code>offset</code> however doing that causes a bug in which some of the blog posts are repeated on the second page so not ideal.
Currently I'm doing it manually using the post id so like this:</p>
<pre><code>$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1';
$args = array(
'posts_per_page' => 5,
'post__not_in' => array(827, 809),
'post_status' =>"publish",
'post_type' =>"post",
'orderby' =>"post_date",
'cat' =>'-1, -8, -9, -7, -6, -5, -4',
'paged' => $paged
);
$postslist = get_posts( $args );
echo '<div class="latest_new_posts main-news">';
</code></pre>
<p>Can anybody think of a better way of doing this where I don't have to adjust the post id constantly?</p>
| [
{
"answer_id": 278100,
"author": "bynicolas",
"author_id": 99217,
"author_profile": "https://wordpress.stackexchange.com/users/99217",
"pm_score": 1,
"selected": false,
"text": "<p>WordPress nonces are not real nonces, they remain valid for a period of 12 to 24 hours and will return the ... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278109",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126587/"
] | I'm trying to exclude the latest two blog posts from a page.
I know it's possible to do this with `offset` however doing that causes a bug in which some of the blog posts are repeated on the second page so not ideal.
Currently I'm doing it manually using the post id so like this:
```
$paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : '1';
$args = array(
'posts_per_page' => 5,
'post__not_in' => array(827, 809),
'post_status' =>"publish",
'post_type' =>"post",
'orderby' =>"post_date",
'cat' =>'-1, -8, -9, -7, -6, -5, -4',
'paged' => $paged
);
$postslist = get_posts( $args );
echo '<div class="latest_new_posts main-news">';
```
Can anybody think of a better way of doing this where I don't have to adjust the post id constantly? | The true reason of not using nonces for non logged in users, is that it adds a pointless burden on their usage as they need to refresh the page when the nonce expire, and the only way they will know that they need to do it is when something do not work.
There is probably no reason to avoid generating it, but if you expect that your "app" will be used/open for more then 12 hours (that is the "tick" time used to calculate wordpress nonces) then either you need to also have an automatic way to refresh the nonce (might be a good idea for logged in users as well) or avoid using it in the first place. |
278,128 | <p>I am trying to output related posts of the current post by <code>tag_ID</code>. With the current code, posts will output all posts from the <code>property</code> tag instead of specific tag.</p>
<p>How can I only return posts based on the current posts <code>tag_ID</code>?</p>
<pre><code><?php $post_tag = get_the_tags($post->ID)?>//Not sure if correct
<?php
$args = array(
'post_type' => 'property',
'tag' => $post_tag,
);
$related_posts = new WP_Query( $args );
?>
<?php while ( $related_posts -> have_posts() ) : $related_posts -> the_post(); ?>
<h2><?php echo get_the_title()?></h2>
//etc
<?php endwhile; wp_reset_query(); ?>
</code></pre>
<p><strong>Solution:</strong>
Might not be the best solution but manages to query related posts that are within <code>city</code> and the current posts tag.</p>
<pre><code>$tags = wp_get_post_terms( get_queried_object_id(), 'city', ['fields' => 'ids'] );
// Now pass the IDs to tag__in
$args = array(
'post_type' => 'property',
'post__not_in' => array( $post->ID ),
'tax_query' => array(
array(
'taxonomy' => 'city',
'terms' => $tags,
),
),
);
$related_posts = new WP_Query( $args );
</code></pre>
| [
{
"answer_id": 278130,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": true,
"text": "<p><code>get_the_tags()</code> returns an array of tags name, ID, and more. You should store only IDs in an arr... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278128",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/87036/"
] | I am trying to output related posts of the current post by `tag_ID`. With the current code, posts will output all posts from the `property` tag instead of specific tag.
How can I only return posts based on the current posts `tag_ID`?
```
<?php $post_tag = get_the_tags($post->ID)?>//Not sure if correct
<?php
$args = array(
'post_type' => 'property',
'tag' => $post_tag,
);
$related_posts = new WP_Query( $args );
?>
<?php while ( $related_posts -> have_posts() ) : $related_posts -> the_post(); ?>
<h2><?php echo get_the_title()?></h2>
//etc
<?php endwhile; wp_reset_query(); ?>
```
**Solution:**
Might not be the best solution but manages to query related posts that are within `city` and the current posts tag.
```
$tags = wp_get_post_terms( get_queried_object_id(), 'city', ['fields' => 'ids'] );
// Now pass the IDs to tag__in
$args = array(
'post_type' => 'property',
'post__not_in' => array( $post->ID ),
'tax_query' => array(
array(
'taxonomy' => 'city',
'terms' => $tags,
),
),
);
$related_posts = new WP_Query( $args );
``` | `get_the_tags()` returns an array of tags name, ID, and more. You should store only IDs in an array, and use it in your query.
```
$post_tag = get_the_tags ( $post->ID );
// Define an empty array
$ids = array();
// Check if the post has any tags
if ( $post_tag ) {
foreach ( $post_tag as $tag ) {
$ids[] = $tag->term_id;
}
}
// Now pass the IDs to tag__in
$args = array(
'post_type' => 'property',
'tag__in' => $ids,
);
// Now proceed with the rest of your query
$related_posts = new WP_Query( $args );
```
Also, use `wp_reset_postdata();` instead of `wp_reset_query();` when you are using `WP_Query();`.
UPDATE
------
As pointed out by @birgire, WordPress offers the [`wp_list_plunk()`](https://developer.wordpress.org/reference/functions/wp_list_pluck/) function to extract a certain field of each object in a row, which has the same functionality as [`array_column()`](http://php.net/manual/en/function.array-column.php) function.
So, we can change this:
```
// Define an empty array
$ids = array();
// Check if the post has any tags
if ( $post_tag ) {
foreach ( $post_tag as $tag ) {
$ids[] = $tag->term_id;
}
}
```
To this:
```
// Check if the post has any tags
if ( $post_tag ) {
$ids = wp_list_pluck( $post_tag, 'term_id' );
}
``` |
278,136 | <p>So, I have a plugin that uses Ajax to dynamically build the post content piece by piece for a custom post type. Once the user has build their page, they hit Update/Publish and Ajax sends the entire built page to a the main plugin PHP file where I am attempting to call <code>wp_insert_post()</code>.</p>
<p>Here is my relevant code (and yes the var <code>new_content</code> is set and is correct):</p>
<pre><code>jQuery.ajax({
url: ajaxurl,
method: 'POST',
data : {
update_or_create: '1',
post_content: new_content,
post_title: jQuery('#title').val(),
pid: jQuery('#post_ID').val(),
action : "update_or_save_zen_page"
} ,
success : function(data, textStatus, XMLHttpRequest) {
//alert(data);
console.log(data); // the data sent to the php file is correct
console.log(textStatus); // reads 'success'
console.log(XMLHttpRequest); // normal from what I can tell, "readyState: 4"
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An unknown error has occurred"); // this does not fire
//console.log(data);
//console.log(textStatus);
//console.log(errorThrown);
//console.log(XMLHttpRequest);
}
});
</code></pre>
<p>Here is the php code this is posting to:</p>
<pre><code>function pbfcz_save_zen_page() {
$pid = ( is_numeric($_POST['pid']) ? $_POST['pid'] : 0);
$the_content = sanitize_post_field ('post_content', $_POST['post_content'], $pid);
$the_title = sanitize_text_field ( $_POST['post_title'] );
$post_array = array (
'ID' => $pid,
'post_title' => $the_title,
'post_content' => $the_content, // at this point, $the_content is correct
'post_status' => 'publish',
'post_type' => 'zen_page'
);
$insert = wp_insert_post( $post_array, true ); // this returns the ID every time, meaning successful update, but it is not always successful
//echo $insert; // this is always the post ID, meaning success
echo $the_content; // this is still correc
wp_die();}
</code></pre>
<p>When the user selects save, I have tracked the data all the way until the argument for <code>wp_insert_post()</code>. It is ALWAYS correct. The function ALWAYS returns the post ID, meaning is was successful. I don't get a <code>WP_Error</code> returned or any HTML code errors like 404 or 500 or anything like that. </p>
<p>I don't get any errors in the chrome developer tools console either. But it updates successfully SOMETIMES - maybe every 1 in 10 tries it works.</p>
<p>I have tried using GET instead of POST</p>
<p>I have tried removing the <code>'post_status' => 'publish'</code> from the arguments.</p>
<p>I have tried converting the <code>post_content</code> to UTF8 by using <code>utf8_encode()</code>.</p>
<p>I have tried using <code>post_content_filtered</code> rather than <code>post_content</code>.</p>
<p>Nothing seems to be working, and it works randomly, and I cannot find a pattern. </p>
<p>The only other piece of information I have that may be related is that images have a hard time loading on this same page. If there is an image in the page content, I get errors such as </p>
<blockquote>
<p>"net::ERR_SPDY_PING_FAILED" or "net::ERR_CONNECTION_RESET"</p>
</blockquote>
<p>or:</p>
<blockquote>
<p>"net::ERR_CONNECTION_CLOSED"</p>
</blockquote>
<p>sometimes on page load. The server tries to load the image for over a minute then times out (but the image is already displaying on the page for that entire minute, then when it times out the image disappears).</p>
<p>Can anybody suggest why this is not working (with zero errors), but does work sometimes? Thank you all in advance and let me know if you need more code or background.</p>
| [
{
"answer_id": 278139,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all o... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278136",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/119050/"
] | So, I have a plugin that uses Ajax to dynamically build the post content piece by piece for a custom post type. Once the user has build their page, they hit Update/Publish and Ajax sends the entire built page to a the main plugin PHP file where I am attempting to call `wp_insert_post()`.
Here is my relevant code (and yes the var `new_content` is set and is correct):
```
jQuery.ajax({
url: ajaxurl,
method: 'POST',
data : {
update_or_create: '1',
post_content: new_content,
post_title: jQuery('#title').val(),
pid: jQuery('#post_ID').val(),
action : "update_or_save_zen_page"
} ,
success : function(data, textStatus, XMLHttpRequest) {
//alert(data);
console.log(data); // the data sent to the php file is correct
console.log(textStatus); // reads 'success'
console.log(XMLHttpRequest); // normal from what I can tell, "readyState: 4"
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
alert("An unknown error has occurred"); // this does not fire
//console.log(data);
//console.log(textStatus);
//console.log(errorThrown);
//console.log(XMLHttpRequest);
}
});
```
Here is the php code this is posting to:
```
function pbfcz_save_zen_page() {
$pid = ( is_numeric($_POST['pid']) ? $_POST['pid'] : 0);
$the_content = sanitize_post_field ('post_content', $_POST['post_content'], $pid);
$the_title = sanitize_text_field ( $_POST['post_title'] );
$post_array = array (
'ID' => $pid,
'post_title' => $the_title,
'post_content' => $the_content, // at this point, $the_content is correct
'post_status' => 'publish',
'post_type' => 'zen_page'
);
$insert = wp_insert_post( $post_array, true ); // this returns the ID every time, meaning successful update, but it is not always successful
//echo $insert; // this is always the post ID, meaning success
echo $the_content; // this is still correc
wp_die();}
```
When the user selects save, I have tracked the data all the way until the argument for `wp_insert_post()`. It is ALWAYS correct. The function ALWAYS returns the post ID, meaning is was successful. I don't get a `WP_Error` returned or any HTML code errors like 404 or 500 or anything like that.
I don't get any errors in the chrome developer tools console either. But it updates successfully SOMETIMES - maybe every 1 in 10 tries it works.
I have tried using GET instead of POST
I have tried removing the `'post_status' => 'publish'` from the arguments.
I have tried converting the `post_content` to UTF8 by using `utf8_encode()`.
I have tried using `post_content_filtered` rather than `post_content`.
Nothing seems to be working, and it works randomly, and I cannot find a pattern.
The only other piece of information I have that may be related is that images have a hard time loading on this same page. If there is an image in the page content, I get errors such as
>
> "net::ERR\_SPDY\_PING\_FAILED" or "net::ERR\_CONNECTION\_RESET"
>
>
>
or:
>
> "net::ERR\_CONNECTION\_CLOSED"
>
>
>
sometimes on page load. The server tries to load the image for over a minute then times out (but the image is already displaying on the page for that entire minute, then when it times out the image disappears).
Can anybody suggest why this is not working (with zero errors), but does work sometimes? Thank you all in advance and let me know if you need more code or background. | Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all of this out of the box:
```
example.com/wp-json/wp/v2/zen_page
```
So lets enqueue a helper script to give us the URL and a security token/nonce:
```
wp_enqueue_script( 'wp-api' );
```
You will **must** enable the REST API for your custom post type by adding this option when registering your post type. If you don't do this then the `zen_page` rest endpoints will not be created by core:
```
'show_in_rest' => true
```
Then adjust the JS:
```
var post_id = 1;
jQuery.ajax({
url: wpApiSettings.root + 'wp/v2/zen_page/'+post_id,
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data : {
content: 'post content goes here',
title: 'test post',
status: 'publish'
}
}).fail( function( response ) {
// failure
console.log( 'failure' );
console.log( response );
}).done( function( response ) {
// success!
console.log( 'success' );
console.log( response );
}).;
```
WP automatically includes the `wpApiSettings` object when you enqueue `wp-api`, and `data` [takes these values](https://developer.wordpress.org/rest-api/reference/posts/#schema). You'll need an active login cookie to do this. If that's not an option, you can create new rest endpoints
If you want to create a new one, send a POST request here:
```
example.com/wp-json/wp/v2/zen_page
```
If you want to update one, send a POST request here:
```
example.com/wp-json/wp/v2/zen_page/2
```
Where 2 is the post ID you want to update. Send a DELETE request to delete it. In a REST API, you don't pass post IDs or actions, instead you use URLs, the same way different urls load different pages, different endpoints do different things. You can `GET`/`POST`/`DELETE`/`PUT`, and these are all the standard HTTP request types, not a parameter passed in the request.
Follow Up Notes
---------------
### `rest_base`
This will let you modify what core uses to create the endpoint, e.g.
```
'rest_base' => 'bananas'
```
will change your endpoints URL to `wp/v2/bananas`. Note that you do not want to name this `pages` as there is already a `pages` endpoint provided by core.
### `zen_page`
This might actually be better off if you just used the `page` post type and used a custom taxonomy to differentiate the zen\_page's from normal pages.
### It doesn't work
The REST API is designed to indicate why it didn't work, e.g. if I try to visit `wp-json/wp/v2/skjlfnvlkdjfv` I'll get:
>
> `{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}`
>
>
>
and if I try to use the `wp-json/wp/v2/settings` endpoint in incognito mode:
>
> `{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":403}}`
>
>
>
Admin AJAX will return `0` in all of these scenarios, so be thankful but pay attention to failure or error messages. Here we saw I tried to make a request to an endpoint that doesn't exist, then again to an endpoint I didn't have permission for as I was logged out. |
278,148 | <p>I've just converted my local development install of wordpress to a network, and everything seems to work, except the parts of the admin panel relating to network management don't have the correct links (I have the core wordpress files in a "wordpress/" subdirectory.) The network related parts get links generated without the "wordpress/" component, but everything else continues to work correctly.</p>
<p>Is there a step I missed to get my "network" to play nice with this directory setup?</p>
| [
{
"answer_id": 278139,
"author": "Tom J Nowell",
"author_id": 736,
"author_profile": "https://wordpress.stackexchange.com/users/736",
"pm_score": 3,
"selected": true,
"text": "<p>Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all o... | 2017/08/25 | [
"https://wordpress.stackexchange.com/questions/278148",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84595/"
] | I've just converted my local development install of wordpress to a network, and everything seems to work, except the parts of the admin panel relating to network management don't have the correct links (I have the core wordpress files in a "wordpress/" subdirectory.) The network related parts get links generated without the "wordpress/" component, but everything else continues to work correctly.
Is there a step I missed to get my "network" to play nice with this directory setup? | Don't bother fixing your AJAX callback, there's already a REST API endpoint that's well tested and does all of this out of the box:
```
example.com/wp-json/wp/v2/zen_page
```
So lets enqueue a helper script to give us the URL and a security token/nonce:
```
wp_enqueue_script( 'wp-api' );
```
You will **must** enable the REST API for your custom post type by adding this option when registering your post type. If you don't do this then the `zen_page` rest endpoints will not be created by core:
```
'show_in_rest' => true
```
Then adjust the JS:
```
var post_id = 1;
jQuery.ajax({
url: wpApiSettings.root + 'wp/v2/zen_page/'+post_id,
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data : {
content: 'post content goes here',
title: 'test post',
status: 'publish'
}
}).fail( function( response ) {
// failure
console.log( 'failure' );
console.log( response );
}).done( function( response ) {
// success!
console.log( 'success' );
console.log( response );
}).;
```
WP automatically includes the `wpApiSettings` object when you enqueue `wp-api`, and `data` [takes these values](https://developer.wordpress.org/rest-api/reference/posts/#schema). You'll need an active login cookie to do this. If that's not an option, you can create new rest endpoints
If you want to create a new one, send a POST request here:
```
example.com/wp-json/wp/v2/zen_page
```
If you want to update one, send a POST request here:
```
example.com/wp-json/wp/v2/zen_page/2
```
Where 2 is the post ID you want to update. Send a DELETE request to delete it. In a REST API, you don't pass post IDs or actions, instead you use URLs, the same way different urls load different pages, different endpoints do different things. You can `GET`/`POST`/`DELETE`/`PUT`, and these are all the standard HTTP request types, not a parameter passed in the request.
Follow Up Notes
---------------
### `rest_base`
This will let you modify what core uses to create the endpoint, e.g.
```
'rest_base' => 'bananas'
```
will change your endpoints URL to `wp/v2/bananas`. Note that you do not want to name this `pages` as there is already a `pages` endpoint provided by core.
### `zen_page`
This might actually be better off if you just used the `page` post type and used a custom taxonomy to differentiate the zen\_page's from normal pages.
### It doesn't work
The REST API is designed to indicate why it didn't work, e.g. if I try to visit `wp-json/wp/v2/skjlfnvlkdjfv` I'll get:
>
> `{"code":"rest_no_route","message":"No route was found matching the URL and request method","data":{"status":404}}`
>
>
>
and if I try to use the `wp-json/wp/v2/settings` endpoint in incognito mode:
>
> `{"code":"rest_forbidden","message":"Sorry, you are not allowed to do that.","data":{"status":403}}`
>
>
>
Admin AJAX will return `0` in all of these scenarios, so be thankful but pay attention to failure or error messages. Here we saw I tried to make a request to an endpoint that doesn't exist, then again to an endpoint I didn't have permission for as I was logged out. |
278,150 | <p>I'm currently working on my first theme and am trying to allow the user to edit some text in the customizer. </p>
<p>Basically, I've got as far as getting the text the user writes in the customizer to show on the frontend, but the default text isn't showing and I'm not sure how to get it to show.</p>
<p>Below is the code I've put on the customizer.php file </p>
<pre><code>$wp_customize->add_section('home_header', array(
'title' => __('Home Header', 'sincere'),
'description' => '',
'priority' => 70,
));
$wp_customize->add_setting( 'home_header_title', array(
'capability' => 'edit_theme_options',
'default' => __('Clean. Simple. Sincere', 'sincere'),
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'home_header_title', array(
'type' => 'text',
'section' => 'home_header', // Add a default or your own section
'label' => __( 'Header Text' ),
) );
</code></pre>
<p>This is the code I've put on my front-page.php file to try and display the text.</p>
<pre><code><section class="feature-image feature-image-home feature-image-default-alt"
data-type="background" data-speed="2">
<h1 class="entry-title"><?php echo get_theme_mod('home_header_title'); ?
></h1>
</section>
</code></pre>
<p>Thanks in advance for any help!</p>
| [
{
"answer_id": 278151,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 2,
"selected": false,
"text": "<p>Setting the default when registering the setting doesn't make it the default on output, it just makes i... | 2017/08/26 | [
"https://wordpress.stackexchange.com/questions/278150",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108692/"
] | I'm currently working on my first theme and am trying to allow the user to edit some text in the customizer.
Basically, I've got as far as getting the text the user writes in the customizer to show on the frontend, but the default text isn't showing and I'm not sure how to get it to show.
Below is the code I've put on the customizer.php file
```
$wp_customize->add_section('home_header', array(
'title' => __('Home Header', 'sincere'),
'description' => '',
'priority' => 70,
));
$wp_customize->add_setting( 'home_header_title', array(
'capability' => 'edit_theme_options',
'default' => __('Clean. Simple. Sincere', 'sincere'),
'sanitize_callback' => 'sanitize_text_field',
) );
$wp_customize->add_control( 'home_header_title', array(
'type' => 'text',
'section' => 'home_header', // Add a default or your own section
'label' => __( 'Header Text' ),
) );
```
This is the code I've put on my front-page.php file to try and display the text.
```
<section class="feature-image feature-image-home feature-image-default-alt"
data-type="background" data-speed="2">
<h1 class="entry-title"><?php echo get_theme_mod('home_header_title'); ?
></h1>
</section>
```
Thanks in advance for any help! | Setting the default when registering the setting doesn't make it the default on output, it just makes it the default value when the customiser is opened. To provide a default before the customiser is opened/saved you pass it as a second argument to `get_theme_mod()`:
```
<?php echo get_theme_mod('home_header_title', __('Clean. Simple. Sincere', 'sincere') ); ?>
```
This can be annoying, since you have to have the defaults written down twice. So one thing you can do is create a function the returns defaults, and use it in both places.
The function would look like this:
```
function sincere_get_theme_default( $setting ) {
$defaults = array(
'home_header_title' => __( 'Clean. Simple. Sincere', 'sincere' ),
);
return $defaults[$setting];
}
```
Then you'd call it as the default value when registering your setting:
```
$wp_customize->add_setting( 'home_header_title', array(
'capability' => 'edit_theme_options',
'default' => sincere_get_theme_default( 'home_header_title' ),
'sanitize_callback' => 'sanitize_text_field',
) );
```
And also as the default argument for `get_theme_mod()`:
```
<?php echo get_theme_mod( 'home_header_title', sincere_get_theme_default( 'home_header_title' ) ); ?>
``` |
278,156 | <p>Not sure if my assumption is correct regarding running <code>wp-cron</code> from CLI would be slightly faster than calling it via <code>wget</code> or <code>curl</code>, so either way I'm trying this:</p>
<pre><code>/usr/bin/php /var/www/mywebsite.com/wp-cron.php?import_key=<keyhere>&import_id=1&action=processing
</code></pre>
<p>I ensured that path to PHP and the file is correct, but I keep getting this error:</p>
<blockquote>
<p>Could not open input file: wp-cron.php?import_key=</p>
</blockquote>
<p>What am I doing wrong?</p>
| [
{
"answer_id": 278158,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>the CLI PHP interpreter is not exactly the same as the one invoke by the webserver. A lot of enviroment i... | 2017/08/26 | [
"https://wordpress.stackexchange.com/questions/278156",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/16113/"
] | Not sure if my assumption is correct regarding running `wp-cron` from CLI would be slightly faster than calling it via `wget` or `curl`, so either way I'm trying this:
```
/usr/bin/php /var/www/mywebsite.com/wp-cron.php?import_key=<keyhere>&import_id=1&action=processing
```
I ensured that path to PHP and the file is correct, but I keep getting this error:
>
> Could not open input file: wp-cron.php?import\_key=
>
>
>
What am I doing wrong? | Or, you could use [WP-CLI](http://wp-cli.org/) which was developed for scenarios like these. After a short installation like this
```
$ curl -O https://raw.githubusercontent.com/wp-cli/builds/gh-pages/phar/wp-cli.phar
$ chmod +x wp-cli.phar
$ sudo mv wp-cli.phar /usr/local/bin/wp
```
You can run your scheduled tasks like so
```
$ wp cron event run --due-now --path=/var/www/mywebsite.com/
```
or via `crontab` (every 5mins)
```
*/5 * * * * wp cron event run --due-now --path=/var/www/mywebsite.com/
```
You could use a specific hook
```
$ wp cron event run myhook --due-now --path=/var/www/mywebsite.com/
```
or use the [`--url` parameter](https://developer.wordpress.org/cli/commands/cron/event/run/). |
278,190 | <p>I have a custom search query that return results correctly, but when i tried to paginate the results,it shows the content of the first page. when I click on 'next'or the number of the page the search page reloads and the link changes from
localhost/wordpress/search/?search_input=art&search=</p>
<p>to </p>
<p>localhost/wordpress/search/page/2/?search_input=art&search
while number 1 of pages remains unclickable, <a href="https://i.stack.imgur.com/cECkK.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/cECkK.png" alt="enter image description here"></a> and the content of the page remains the same.
I've tried documentation <a href="https://codex.wordpress.org/Pagination" rel="nofollow noreferrer">Codex</a>,YouTube tutorials, <a href="https://wordpress.stackexchange.com/questions/264618/pagination-not-working-for-custom-search-form-custom-result-template">StackExchange</a>, and many other.</p>
<p>I have tried modifying the 'paged' argument manually by setting it to 2 then 3 and it displayed the second and 3rd pages correctly while page 1 still unclickable.
by the way , i put the search query in a function, and i used a free HTML template for the site (i am in training). can anybody see where is my fault, please.
HERE IS THE CODE`</p>
<pre><code> <div class="col-sm-9 padding-right">
<div class="features_items">
<?php
$book ;
$search_text = get_query_var('search_input');
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$book = bbx_search($search_text,$paged);
$post_count = $book ->post_count;
echo '<h2 class="title text-center">Search Results : '.$post_count .'</h2>';
?>
<?php
while($book -> have_posts()){
$book->the_post();
$book_price = get_post_meta( get_the_ID(), 'book_price',true);
$author_name = get_post_meta( get_the_ID(), 'author_name',true);
echo '<div class="col-sm-4">';
echo '<div class="product-image-wrapper">';
echo '<div class="single-products">';
echo '<div class="productinfo text-center">';
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ),'thumbnail' ); // or the_post_thumbnail('medium');
if ($image) :
echo '<img src="'. $image[0].'" alt="" />';
endif;
echo '<h2> $'.$book_price .'</h2>';
echo '<p>'. the_title().'</p>';
echo '<a href="'.esc_url( add_query_arg( 'book_id', get_the_ID(), site_url('/cart'))).'" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
</div>
</div>
</div>';
} ?>
<nav class="prev-next-posts">
<?php
echo paginate_links(array (
'total'=> $book->max_num_pages
)); ?>
</nav>
<?php new WP_Query(); ?>
</div>
</div>
</div>
</div>
</section>
</code></pre>
<p>//-----------in functions file</p>
<pre><code>function bbx_search($search_text, $paged){
$args1 = array(
'post_type' => 'book',
'post_status'=> 'publish',
'order'=> 'DSC',
'orderby' => 'publish_date',
'posts_per_page' => 3,
'paged' => $paged,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'author_name', 'value' => $search_text,
'type' => 'text','compare' => 'like'),
array(
'key' => 'book_description','value' => $search_text,
'type' => 'text','compare' => 'like'),
array(
'key' => 'bbx_category','value' => $search_text,
'type' => 'text','compare' => 'like'),
array(
'key' => 'post_tag','value' => $search_text,
'type' => 'text','compare' => 'like'),
)
);
return new WP_Query( $args1 );
</code></pre>
<p>}</p>
| [
{
"answer_id": 278198,
"author": "inarilo",
"author_id": 17923,
"author_profile": "https://wordpress.stackexchange.com/users/17923",
"pm_score": 0,
"selected": false,
"text": "<p>You need to pass more values to <a href=\"https://codex.wordpress.org/Function_Reference/paginate_links\" rel... | 2017/08/26 | [
"https://wordpress.stackexchange.com/questions/278190",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126630/"
] | I have a custom search query that return results correctly, but when i tried to paginate the results,it shows the content of the first page. when I click on 'next'or the number of the page the search page reloads and the link changes from
localhost/wordpress/search/?search\_input=art&search=
to
localhost/wordpress/search/page/2/?search\_input=art&search
while number 1 of pages remains unclickable, [](https://i.stack.imgur.com/cECkK.png) and the content of the page remains the same.
I've tried documentation [Codex](https://codex.wordpress.org/Pagination),YouTube tutorials, [StackExchange](https://wordpress.stackexchange.com/questions/264618/pagination-not-working-for-custom-search-form-custom-result-template), and many other.
I have tried modifying the 'paged' argument manually by setting it to 2 then 3 and it displayed the second and 3rd pages correctly while page 1 still unclickable.
by the way , i put the search query in a function, and i used a free HTML template for the site (i am in training). can anybody see where is my fault, please.
HERE IS THE CODE`
```
<div class="col-sm-9 padding-right">
<div class="features_items">
<?php
$book ;
$search_text = get_query_var('search_input');
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
$book = bbx_search($search_text,$paged);
$post_count = $book ->post_count;
echo '<h2 class="title text-center">Search Results : '.$post_count .'</h2>';
?>
<?php
while($book -> have_posts()){
$book->the_post();
$book_price = get_post_meta( get_the_ID(), 'book_price',true);
$author_name = get_post_meta( get_the_ID(), 'author_name',true);
echo '<div class="col-sm-4">';
echo '<div class="product-image-wrapper">';
echo '<div class="single-products">';
echo '<div class="productinfo text-center">';
$image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ),'thumbnail' ); // or the_post_thumbnail('medium');
if ($image) :
echo '<img src="'. $image[0].'" alt="" />';
endif;
echo '<h2> $'.$book_price .'</h2>';
echo '<p>'. the_title().'</p>';
echo '<a href="'.esc_url( add_query_arg( 'book_id', get_the_ID(), site_url('/cart'))).'" class="btn btn-default add-to-cart"><i class="fa fa-shopping-cart"></i>Add to cart</a>
</div>
</div>
</div>
</div>';
} ?>
<nav class="prev-next-posts">
<?php
echo paginate_links(array (
'total'=> $book->max_num_pages
)); ?>
</nav>
<?php new WP_Query(); ?>
</div>
</div>
</div>
</div>
</section>
```
//-----------in functions file
```
function bbx_search($search_text, $paged){
$args1 = array(
'post_type' => 'book',
'post_status'=> 'publish',
'order'=> 'DSC',
'orderby' => 'publish_date',
'posts_per_page' => 3,
'paged' => $paged,
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'author_name', 'value' => $search_text,
'type' => 'text','compare' => 'like'),
array(
'key' => 'book_description','value' => $search_text,
'type' => 'text','compare' => 'like'),
array(
'key' => 'bbx_category','value' => $search_text,
'type' => 'text','compare' => 'like'),
array(
'key' => 'post_tag','value' => $search_text,
'type' => 'text','compare' => 'like'),
)
);
return new WP_Query( $args1 );
```
} | the problem was that the get\_query\_var('paged')or 'page' couldn't read the value .. I don't know why? .. but it always returns 0; and the check sets $paged to 1 each time ... so I got around it, and got the page number from the URL >>> It worked for me on localhost, but I've no clue if it works on a host... for your info: I work on WordPress 4.8.1, and use PHP server WAMP 3.0.6 X64 >>> replace
`$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;`
with
`$p = explode("/", $_SERVER['REQUEST_URI']);
$pag = (int)($p[4]*1);
if ($pag == 0 || $pag== null){$paged =1;} else {$paged=$pag;}` |
278,204 | <p>Is it possible to delete a huge number of wordpress posts through SQL query using phpmyadmin by using a permalink list of posts that I want to delete ?</p>
| [
{
"answer_id": 278368,
"author": "Milan Petrovic",
"author_id": 126702,
"author_profile": "https://wordpress.stackexchange.com/users/126702",
"pm_score": 0,
"selected": false,
"text": "<p>It depends on permalinks. Permalinks can contain more then just the post name (slug). Also, post nam... | 2017/08/26 | [
"https://wordpress.stackexchange.com/questions/278204",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/65292/"
] | Is it possible to delete a huge number of wordpress posts through SQL query using phpmyadmin by using a permalink list of posts that I want to delete ? | Yes you can.
To delete posts with inherit post meta, use following code:
```
DELETE
p,pm
FROM wp_posts p
JOIN wp_postmeta pm ON pm.post_id = p.id
WHERE p.post_name IN ('post-1', 'post-2', 'post-3')
```
Pass slugs array to WHERE clause.
If you want to delete only posts w/out postmeta (for some reason), use this code:
```
DELETE
FROM wp_posts
WHERE post_name IN ('post-1', 'post-2', 'post-3')
``` |
278,251 | <p>I'm currently trying to resize all the featured images on my theme to 1140 x 500. I've placed this code in my function.php file</p>
<pre><code> if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
// Default Post thumbnail dimensions (cropped)
set_post_thumbnail_size( 1140, 500, true );
}
</code></pre>
<p>And this code in my loop.</p>
<pre><code><?php if ( has_post_thumbnail() ) { // check for feature image ?>
<div class="post-image">
<?php the_post_thumbnail(); ?>
</div><!-- post-image -->
<?php } ?>
</code></pre>
<p>Thanks for any help.</p>
| [
{
"answer_id": 278262,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 2,
"selected": true,
"text": "<p>Setting the size itself does not crop the existing images. You need to regenerate the existing thumbnails to... | 2017/08/27 | [
"https://wordpress.stackexchange.com/questions/278251",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108692/"
] | I'm currently trying to resize all the featured images on my theme to 1140 x 500. I've placed this code in my function.php file
```
if ( function_exists( 'add_theme_support' ) ) {
add_theme_support( 'post-thumbnails' );
// Default Post thumbnail dimensions (cropped)
set_post_thumbnail_size( 1140, 500, true );
}
```
And this code in my loop.
```
<?php if ( has_post_thumbnail() ) { // check for feature image ?>
<div class="post-image">
<?php the_post_thumbnail(); ?>
</div><!-- post-image -->
<?php } ?>
```
Thanks for any help. | Setting the size itself does not crop the existing images. You need to regenerate the existing thumbnails too.
There are a couple of plugins for this, but I personally downloaded and used [Regenerate Thumbnails](https://wordpress.org/plugins/regenerate-thumbnails/). Install the plugin, and head over to `Tools > Regenerate Thumbnails`. There you can regenerate thumbnails for images that exist in your media library, replacing the old thumbnails. |
278,258 | <p>I have a multisite installation running in a sub-directory on the server - purely for the reason that it has become my MO to develop a new site for a client in a "WordPress" directory while their old site is live, and then when it is ready, I change the <code>index.php</code> and <code>.htaccess</code> files and voila, the site is live. </p>
<p>For the first time I have a multisite (sub-directory not sub-domain) in its own folder (not in the root) and now the process is different to what I was used to. </p>
<p>I have googled extensively and found info on the modifications to the <code>.htaccess</code> file - but I get <em>"Error establishing a database connection"</em> error when trying to access the root on my browser. <code>Root.com/wordpress/</code> still works perfectly. </p>
<p>I've amended the <code>.htacccess</code> file with this code - as per WordPress.org: </p>
<pre><code># BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>And I've added the name of the subdirectory into the <code>index.php</code> file as per making a single site live - but now the establishing connection with the database error.</p>
<p>Could you please help with the next step - I sense I am close!</p>
| [
{
"answer_id": 278281,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 1,
"selected": false,
"text": "<p>That's an error with your database credentials, as stored in wp-config.php . Check/fix those credentia... | 2017/08/27 | [
"https://wordpress.stackexchange.com/questions/278258",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126669/"
] | I have a multisite installation running in a sub-directory on the server - purely for the reason that it has become my MO to develop a new site for a client in a "WordPress" directory while their old site is live, and then when it is ready, I change the `index.php` and `.htaccess` files and voila, the site is live.
For the first time I have a multisite (sub-directory not sub-domain) in its own folder (not in the root) and now the process is different to what I was used to.
I have googled extensively and found info on the modifications to the `.htaccess` file - but I get *"Error establishing a database connection"* error when trying to access the root on my browser. `Root.com/wordpress/` still works perfectly.
I've amended the `.htacccess` file with this code - as per WordPress.org:
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
# add a trailing slash to /wp-admin
RewriteRule ^([_0-9a-zA-Z-]+/)?wp-admin$ $1wp-admin/ [R=301,L]
RewriteCond %{REQUEST_FILENAME} -f [OR]
RewriteCond %{REQUEST_FILENAME} -d
RewriteRule ^ - [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(wp-(content|admin|includes).*) $2 [L]
RewriteRule ^([_0-9a-zA-Z-]+/)?(.*\.php)$ $2 [L]
RewriteRule . index.php [L]
</IfModule>
# END WordPress
```
And I've added the name of the subdirectory into the `index.php` file as per making a single site live - but now the establishing connection with the database error.
Could you please help with the next step - I sense I am close! | That's an error with your database credentials, as stored in wp-config.php . Check/fix those credentials to let WP access the database. (As the googles would tell you if you searched on the error message....) |
278,286 | <p>I have a custom field for an image, and using it this way:</p>
<pre><code><?php $item_img = get_sub_field('image'); ?>
<img src="<?php echo $item_img ?>" />
</code></pre>
<p>But I want to use the thumbnail version of the image, as set to 150x150 in wordpress.</p>
<p>How do I do that with this type of setup?</p>
<p>Do I have to set a custom <code>add_image_size()</code> or does wordpress have duplicated thumbmail size images?</p>
| [
{
"answer_id": 278271,
"author": "sakarya",
"author_id": 51376,
"author_profile": "https://wordpress.stackexchange.com/users/51376",
"pm_score": -1,
"selected": false,
"text": "<p>I can't say, how do you find out how they did it, but I can say something for security.</p>\n\n<ol>\n<li>Alw... | 2017/08/28 | [
"https://wordpress.stackexchange.com/questions/278286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/123346/"
] | I have a custom field for an image, and using it this way:
```
<?php $item_img = get_sub_field('image'); ?>
<img src="<?php echo $item_img ?>" />
```
But I want to use the thumbnail version of the image, as set to 150x150 in wordpress.
How do I do that with this type of setup?
Do I have to set a custom `add_image_size()` or does wordpress have duplicated thumbmail size images? | There are many things that I do to check a possible hack on the site. Changing FTP users/passwords, reinstalling WP, reinstalling themes/plugins, changing user account passwords (especially admin level), change hosting credentials.
I wrote an entry on my own site to remind me (most of the stuff there is my own 'notes' to myself). May be helpful: <http://securitydawg.com/recovering-from-a-hacked-wordpress-site/> (Not trying to promote my site; there are many googles on how to recover from a hacked site. That link is just my personal list.) |
278,293 | <p>One of my WordPress templates is <strong>completely different</strong> and requires different css and js (but still needs needs the core JQuery as well as the bootstrap 3 css/js).</p>
<p>So, how would I go about removing the generic style.css and also a few other css files (and js files) that are site wide? I think that it is a variation of the below?</p>
<p>I'm new to WP!</p>
<pre><code> // Unique Page Template
if (is_page_template(specific-template.php')):
// Remove Site-wide CSS
wp_dequeue_style('generic styles', get_stylesheet_uri(), array(), '1.2');
// And this would enqueue the unique css
wp_enqueue_style( 'unque to this template css', get_template_directory_uri() . '/css/unique-to-this-template.css', array(), '1.0');
endif;
</code></pre>
<p>Is my logic correct here?</p>
<p>Thanks for all direction</p>
| [
{
"answer_id": 278271,
"author": "sakarya",
"author_id": 51376,
"author_profile": "https://wordpress.stackexchange.com/users/51376",
"pm_score": -1,
"selected": false,
"text": "<p>I can't say, how do you find out how they did it, but I can say something for security.</p>\n\n<ol>\n<li>Alw... | 2017/08/28 | [
"https://wordpress.stackexchange.com/questions/278293",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93691/"
] | One of my WordPress templates is **completely different** and requires different css and js (but still needs needs the core JQuery as well as the bootstrap 3 css/js).
So, how would I go about removing the generic style.css and also a few other css files (and js files) that are site wide? I think that it is a variation of the below?
I'm new to WP!
```
// Unique Page Template
if (is_page_template(specific-template.php')):
// Remove Site-wide CSS
wp_dequeue_style('generic styles', get_stylesheet_uri(), array(), '1.2');
// And this would enqueue the unique css
wp_enqueue_style( 'unque to this template css', get_template_directory_uri() . '/css/unique-to-this-template.css', array(), '1.0');
endif;
```
Is my logic correct here?
Thanks for all direction | There are many things that I do to check a possible hack on the site. Changing FTP users/passwords, reinstalling WP, reinstalling themes/plugins, changing user account passwords (especially admin level), change hosting credentials.
I wrote an entry on my own site to remind me (most of the stuff there is my own 'notes' to myself). May be helpful: <http://securitydawg.com/recovering-from-a-hacked-wordpress-site/> (Not trying to promote my site; there are many googles on how to recover from a hacked site. That link is just my personal list.) |
278,296 | <p>I'm bulk deleting posts from my WordPress site using the function <code>wp_delete_post</code> and categories using <code>wp_delete_category</code>. That are about 100.000 posts and 4.000 categories, and after a while I get a PHP Error </p>
<p><code>PHP Fatal error: Allowed memory size of ... bytes exhausted</code></p>
<p>That's what I do inside my code:</p>
<pre><code>// get all IDs from the posts and categories
$delete_categories = $wpdb->get_col("SELECT DISTINCT(j.term_id)...");
$delete_posts = $wpdb->get_col("SELECT DISTINCT(j.post_id)...");
$delete_parent_categories = $wpdb->get_col("SELECT tt.parent FROM $tbl_term_taxonomy tt ...");
// I removed the SQL statements for a better reading
foreach ($delete_posts as $dp) {
echo "deleting post ".$dp."\n";
wp_delete_post($dp, true);
unset($dp);
}
unset($delete_posts);
foreach ($delete_categories as $dc) {
echo "deleting category ".$dc."\n";
wp_delete_category($dc);
unset($dc);
}
unset($delete_categories);
foreach ($delete_parent_categories as $dc) {
echo "deleting category ".$dc."\n";
wp_delete_category($dc);
unset($dc);
}
unset($delete_parent_categories);
</code></pre>
<p>Deleting the posts works, deleting some categories also works - but at some point the memory limit is exceeded and the script is terminated. Setting the memory limit to 1024MB doesn't look like a perfect solution for me.</p>
<p>Is there a way to free up the memory that the WordPress functions allocated?</p>
| [
{
"answer_id": 278313,
"author": "Milan Petrovic",
"author_id": 126702,
"author_profile": "https://wordpress.stackexchange.com/users/126702",
"pm_score": 2,
"selected": false,
"text": "<p>The code you use also uses WordPress functions that will first load posts (and other relevant data) ... | 2017/08/28 | [
"https://wordpress.stackexchange.com/questions/278296",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126097/"
] | I'm bulk deleting posts from my WordPress site using the function `wp_delete_post` and categories using `wp_delete_category`. That are about 100.000 posts and 4.000 categories, and after a while I get a PHP Error
`PHP Fatal error: Allowed memory size of ... bytes exhausted`
That's what I do inside my code:
```
// get all IDs from the posts and categories
$delete_categories = $wpdb->get_col("SELECT DISTINCT(j.term_id)...");
$delete_posts = $wpdb->get_col("SELECT DISTINCT(j.post_id)...");
$delete_parent_categories = $wpdb->get_col("SELECT tt.parent FROM $tbl_term_taxonomy tt ...");
// I removed the SQL statements for a better reading
foreach ($delete_posts as $dp) {
echo "deleting post ".$dp."\n";
wp_delete_post($dp, true);
unset($dp);
}
unset($delete_posts);
foreach ($delete_categories as $dc) {
echo "deleting category ".$dc."\n";
wp_delete_category($dc);
unset($dc);
}
unset($delete_categories);
foreach ($delete_parent_categories as $dc) {
echo "deleting category ".$dc."\n";
wp_delete_category($dc);
unset($dc);
}
unset($delete_parent_categories);
```
Deleting the posts works, deleting some categories also works - but at some point the memory limit is exceeded and the script is terminated. Setting the memory limit to 1024MB doesn't look like a perfect solution for me.
Is there a way to free up the memory that the WordPress functions allocated? | The code you use also uses WordPress functions that will first load posts (and other relevant data) in memory first and cache them using object cache. So, to delete 100.000 posts, your code will try to load each post in memory and that can take a lot of memory. I am not sure how high PHP memory is set in your case, but, you can either limit the deletion to 1000 or 5000 posts at once or increase PHP memory. |
278,354 | <p>I have a wordpress site in a language that aligns RTL, but some pages are in English. These pages look terrible, however, because the English text is aligned with the RTL language, and punctuation, etc. appear on the wrong the side.</p>
<p>How can I set the language for a single page or several individual pages?</p>
| [
{
"answer_id": 278355,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 3,
"selected": false,
"text": "<p>The <a href=\"https://codex.wordpress.org/Plugin_API/Filter_Reference/locale\" rel=\"noreferrer\"><code>loc... | 2017/08/28 | [
"https://wordpress.stackexchange.com/questions/278354",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126536/"
] | I have a wordpress site in a language that aligns RTL, but some pages are in English. These pages look terrible, however, because the English text is aligned with the RTL language, and punctuation, etc. appear on the wrong the side.
How can I set the language for a single page or several individual pages? | The [`locale`](https://codex.wordpress.org/Plugin_API/Filter_Reference/locale) filter that allows you to set the locale specifically. You can check the current page, and alter the value based on that.
```
add_filter('locale', 'change_my_locale');
function change_my_locale( $locale ) {
if ( is_page('slug-here') ) {
return 'en_US';
}
return $locale;
}
``` |
278,385 | <p>I migrated my WordPress install and DB to another server (same domain).
And I am getting this:</p>
<p><a href="https://i.stack.imgur.com/KhPai.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/KhPai.png" alt="enter image description here"></a></p>
<p>Also everything is where it should be (including file and db permissions and other specific settings):</p>
<p><a href="https://i.stack.imgur.com/LuyrZ.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/LuyrZ.png" alt="enter image description here"></a></p>
<p>And I can not just get pass this:</p>
<p><a href="https://i.stack.imgur.com/MRq90.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/MRq90.png" alt="enter image description here"></a></p>
<p>And I can also confirm that everything works just fine with a blank new install. But I need to recover the current DB. Where should I start? What additional info should I provide to you guys?</p>
<p><strong>EDIT 1:</strong>
Errors info as requested.
<a href="https://i.stack.imgur.com/tndvy.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/tndvy.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/ZwSnb.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ZwSnb.png" alt="enter image description here"></a></p>
<p><strong>EDIT 2</strong>
Running Standard WordPress Database repair.
<a href="https://i.stack.imgur.com/lq1IO.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/lq1IO.png" alt="enter image description here"></a></p>
<p><strong>EDIT 3</strong>
More awkward bugs.</p>
<p><a href="https://i.stack.imgur.com/T2RlH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/T2RlH.png" alt="enter image description here"></a></p>
<p><a href="https://i.stack.imgur.com/okjVW.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/okjVW.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 278403,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 0,
"selected": false,
"text": "<p>I always find it easiest to use the WP Clone plugin <a href=\"https://wordpress.org/plugins/wp-clone-b... | 2017/08/28 | [
"https://wordpress.stackexchange.com/questions/278385",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126738/"
] | I migrated my WordPress install and DB to another server (same domain).
And I am getting this:
[](https://i.stack.imgur.com/KhPai.png)
Also everything is where it should be (including file and db permissions and other specific settings):
[](https://i.stack.imgur.com/LuyrZ.png)
And I can not just get pass this:
[](https://i.stack.imgur.com/MRq90.png)
And I can also confirm that everything works just fine with a blank new install. But I need to recover the current DB. Where should I start? What additional info should I provide to you guys?
**EDIT 1:**
Errors info as requested.
[](https://i.stack.imgur.com/tndvy.png)
[](https://i.stack.imgur.com/ZwSnb.png)
**EDIT 2**
Running Standard WordPress Database repair.
[](https://i.stack.imgur.com/lq1IO.png)
**EDIT 3**
More awkward bugs.
[](https://i.stack.imgur.com/T2RlH.png)
[](https://i.stack.imgur.com/okjVW.png) | You didn't mention what have you done so far to migrate your installation, but I'm going to write the full procedure.
Backing Up the Old Database
---------------------------
You need to create an exact duplicate of your database, to transfer it to your new server. There might be an encoding issue here, so to do this, login into your panel's PhpMyAdmin, and then:
1. Select the database's name from the left sidebar
2. Click the `Export` button on the top navigation menu
3. Click `Custom` under export method
4. Click `Select All` under the tables
5. Choose UTF-8 as encoding, as stated in the screenshot below
[](https://i.stack.imgur.com/PksdP.jpg)
Now you can export and save the file.
Restoring the Back-up
---------------------
To restore the backup, you should first create a database with the same name of your previous database. After you did so, choose it from the left sidebar, and click `Import` from the top navigation menu. Choose the file by clicking the browse button, and then set the encoding to UTF-8.
Click Import to finish the importing (don't forget to remove any existing tables first).
Editing `wp-config.php`
After importing the database, you need to modify the `wp-config.php` file. If you don't do this, you will be redirected to an installation page, this is why you are getting *"Table Exists"* error instead of directly being redirected to `wp-login.php`.
These 4 lines need to be modified to match your new database's configuration:
```
/** The name of the database for WordPress */
define('DB_NAME', 'database_name');
/** MySQL database username */
define('DB_USER', 'username');
/** MySQL database password */
define('DB_PASSWORD', 'password');
/** MySQL hostname */
define('DB_HOST', 'localhost');
```
If you do this properly, you will be redirected to `wp-login.php` after you try to access `/wp-admin/`.
Updating the URLs
-----------------
If you have also changed your domain's address, you need to take 2 further steps. First, you should update the core URLs for your blog's home page. To do so, open the `wp_options` table in PhpMyAdmin, and modify the `siteurl` and `home` values to match your new domain. These are the first two options.
Afterward, you have to do a full search and replace in your database to update the old URLs. Since there are serialized data in the database, you should avoid doing this by a plain text editor. Instead, use a plugin such as [Better Search Replace](https://wordpress.org/plugins/better-search-replace/).
Head over to `Tools > Better Search Replace`, and replace `old.com` with `new.com`. Pay attention to spelling and letter cases, this can matter a lot. If you are switching to HTTPS, you should replace `http://old.com` with `https://new.com`.
A Final Note
------------
I would also use the same WordPress version on the old server for migration. After migrating, you can update to the latest version in the admin panel. |
278,393 | <p>I need to enqueue a style sheet in my plugin to work on the front end of Wordpress. Here is what I have. Will someone please tell me what I am doing wrong?</p>
<pre><code>function add_my_stylesheet1() {
wp_enqueue_style( 'myStyles', plugins_url( 'css/styles.css', __FILE__ ) );
}
add_action('admin_print_styles', 'add_my_stylesheet1');
</code></pre>
| [
{
"answer_id": 278394,
"author": "Cedon",
"author_id": 80069,
"author_profile": "https://wordpress.stackexchange.com/users/80069",
"pm_score": 0,
"selected": false,
"text": "<p>You need to use the <code>admin_enqueue_scripts</code> hook. So your function would be like this...</p>\n\n<pre... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278393",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/117793/"
] | I need to enqueue a style sheet in my plugin to work on the front end of Wordpress. Here is what I have. Will someone please tell me what I am doing wrong?
```
function add_my_stylesheet1() {
wp_enqueue_style( 'myStyles', plugins_url( 'css/styles.css', __FILE__ ) );
}
add_action('admin_print_styles', 'add_my_stylesheet1');
``` | You're enquing on the **admin**\_enqueue\_scripts hook, which is why it's only showing up on admin pages
If we look at an example from the official documentation:
```
/**
* Proper way to enqueue scripts and styles
*/
function wpdocs_theme_name_scripts() {
wp_enqueue_style( 'style-name', get_stylesheet_uri() );
wp_enqueue_script( 'script-name', get_template_directory_uri() . '/js/example.js', array(), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
we see the `wp_enqueue_scripts` hook being used instead. Use that hook instead of `admin_print_styles` to print on the frontend |
278,399 | <p>How do I add a class <code>the_content();</code>?</p>
<pre><code><div class="csoporszoveg">
<h3 class="csoporcim"><?php
if ($settings['enable_link']) {
echo '<a href="' . get_permalink($post) . '">';
}
the_title();
if ($settings['enable_link']) {
echo '</a>';
}
?>
</h3>
<?php } ?>
<?php
if ( $content_source == 'excerpt' ) {
the_excerpt();
} else {
the_content();
}
?>
</div>
</code></pre>
| [
{
"answer_id": 278400,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You don't. You'll need to put an element around it:</p>\n\n<pre><code><?php if ( $content_source == ... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278399",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126748/"
] | How do I add a class `the_content();`?
```
<div class="csoporszoveg">
<h3 class="csoporcim"><?php
if ($settings['enable_link']) {
echo '<a href="' . get_permalink($post) . '">';
}
the_title();
if ($settings['enable_link']) {
echo '</a>';
}
?>
</h3>
<?php } ?>
<?php
if ( $content_source == 'excerpt' ) {
the_excerpt();
} else {
the_content();
}
?>
</div>
``` | You don't. You'll need to put an element around it:
```
<?php if ( $content_source == 'excerpt' ) { ?>
<div class="excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="content">
<?php the_content(); ?>
</div>
<?php } ?>
``` |
278,408 | <p>I'm building a website where there are some posts that will be relevant only for users from a specific country, so I would like that the user select his country so that he can view all the content minus (-) the content that is specific to other countries. </p>
<p>For example:
The user can select between Argentina, Chile, Mexico. He chooses Chile.
He will be able to see all the content except the content that is specific from Argentina and Mexico.</p>
<p>--more description--</p>
<p>I believe 80% of the content will be not country specific.</p>
<p>For example, if there is a category named "TV" which has:</p>
<ul>
<li>general TV posts -> content relevant for everybody (eg: Game of Thrones related posts)</li>
<li>TV Argentina -> content relevant only for argentinians (eg.: local soap opera)</li>
<li>TV Chile</li>
<li>TV Mexico
If the user chooses "Argentina" he must be able to see posts all posts in TV category except Chile and Mexico.</li>
</ul>
<p>I'm not sure how to accomplish this.
It would be great if the user can choose his country from a dropdown and this filter gets applied to the whole website.</p>
<p>Other info: Language is the same for all countries and there is user-generated content</p>
<p>How would you approach this?
Thank you for reading</p>
| [
{
"answer_id": 278400,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": 1,
"selected": false,
"text": "<p>You don't. You'll need to put an element around it:</p>\n\n<pre><code><?php if ( $content_source == ... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278408",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126752/"
] | I'm building a website where there are some posts that will be relevant only for users from a specific country, so I would like that the user select his country so that he can view all the content minus (-) the content that is specific to other countries.
For example:
The user can select between Argentina, Chile, Mexico. He chooses Chile.
He will be able to see all the content except the content that is specific from Argentina and Mexico.
--more description--
I believe 80% of the content will be not country specific.
For example, if there is a category named "TV" which has:
* general TV posts -> content relevant for everybody (eg: Game of Thrones related posts)
* TV Argentina -> content relevant only for argentinians (eg.: local soap opera)
* TV Chile
* TV Mexico
If the user chooses "Argentina" he must be able to see posts all posts in TV category except Chile and Mexico.
I'm not sure how to accomplish this.
It would be great if the user can choose his country from a dropdown and this filter gets applied to the whole website.
Other info: Language is the same for all countries and there is user-generated content
How would you approach this?
Thank you for reading | You don't. You'll need to put an element around it:
```
<?php if ( $content_source == 'excerpt' ) { ?>
<div class="excerpt">
<?php the_excerpt(); ?>
</div>
<?php } else { ?>
<div class="content">
<?php the_content(); ?>
</div>
<?php } ?>
``` |
278,429 | <p>I use TinyMCE Advance plugin. I've posted a question in the support forum of the the plugin but it seems that the author doesn't provide any support now. As you can see in the picture, the font size 12pt is the default font size. Every time I open the TinyMCE Advance editor, the size 12pt displays in the default state. How can I change the default size to 14pt and remove the size 8pt, 10pt,12pt?</p>
<p>I've done some research and it's was recommended that I go to:</p>
<pre><code>wp-includes/js/tinymce/skin/wordpress/wp-content.css
</code></pre>
<p>and change the size in </p>
<pre><code>body {
font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif;
font-size: 18px;
line-height: 1.5;
color: #333;
margin: 9px 10px;
max-width: 100%;
-webkit-font-smoothing: antialiased !important;
overflow-wrap: break-word;
word-wrap: break-word; /* Old syntax */
}
</code></pre>
<p>In this case, I've changed it to 18pt, but it doesn't work. The thing is that the default 12pt size is still there. It just changes only when I click inside the text editor area; it will change from the 12pt (that displays as default) to 14pt. But actually when I type a text and publish, the result is the published text still displays 12pt size, not 14pt. So that means I have to select a font size 14pt in the drop-down list anyway in order to get the size 14pt. </p>
<p><a href="https://i.stack.imgur.com/r0eYS.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r0eYS.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 295988,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278429",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/125408/"
] | I use TinyMCE Advance plugin. I've posted a question in the support forum of the the plugin but it seems that the author doesn't provide any support now. As you can see in the picture, the font size 12pt is the default font size. Every time I open the TinyMCE Advance editor, the size 12pt displays in the default state. How can I change the default size to 14pt and remove the size 8pt, 10pt,12pt?
I've done some research and it's was recommended that I go to:
```
wp-includes/js/tinymce/skin/wordpress/wp-content.css
```
and change the size in
```
body {
font-family: Georgia, "Times New Roman", "Bitstream Charter", Times, serif;
font-size: 18px;
line-height: 1.5;
color: #333;
margin: 9px 10px;
max-width: 100%;
-webkit-font-smoothing: antialiased !important;
overflow-wrap: break-word;
word-wrap: break-word; /* Old syntax */
}
```
In this case, I've changed it to 18pt, but it doesn't work. The thing is that the default 12pt size is still there. It just changes only when I click inside the text editor area; it will change from the 12pt (that displays as default) to 14pt. But actually when I type a text and publish, the result is the published text still displays 12pt size, not 14pt. So that means I have to select a font size 14pt in the drop-down list anyway in order to get the size 14pt.
[](https://i.stack.imgur.com/r0eYS.png) | This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar.
Style TinyMCE
=============
WordPress give us a neat little function called [`add_editor_style()`](https://developer.wordpress.org/reference/functions/add_editor_style/) which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest [TwentySeventeen theme](https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97). First let's create a stylesheet. The name doesn't matter but the location does.
```
body,
button,
input,
select,
textarea {
font-size: 14pt;
}
```
For simplicity we'll call this `editor-style.css` and save it in the theme:
```
/assets/css/editor-style.css
```
Next we need to tell WordPress to use our stylesheet so we'll open the themes `functions.php` file and add in:
```
/**
* Theme setup functionality
*
* @return void
*/
function prefix_theme_setup() {
// Relative path to the TinyMCE Stylesheet
add_editor_style( array( 'assets/css/editor-style.css' ) );
}
add_action( 'after_setup_theme', 'iqt_theme_setup' );
```
Some plugins could interfere with this such as page builders if they implement their own TinyMCE.
---
Modify Toolbar
==============
Next, we can use the [`tiny_mce_before_init`](https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/) [filter hook](https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init) to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your `functions.php` file:
```
/**
* Add Formats to TinyMCE
* - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/
* - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init
*
* @param array $args - Arguments used to initialize the tinyMCE
*
* @return array $args - Modified arguments
*/
function prefix_tinymce_toolbar( $args ) {
$args['fontsize_formats'] = "14pt 18pt 24pt 36pt";
return $args;
}
add_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' );
```
The `$args` array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, `px`, `em`, `rem` it doesn't matter, just that the list is separated by a space and is a valid `font-size` value. |
278,450 | <p>I want to import into the media library, all the images & videos referenced in my blog posts.</p>
<ol>
<li>Can I use <a href="https://developer.wordpress.org/reference/functions/get_attached_media/" rel="nofollow noreferrer"><code>get_attached_media()</code></a> to get the images <em>referenced</em> on a page, even if they're not formally attached?</li>
<li>Should I use <a href="https://developer.wordpress.org/reference/functions/media_handle_sideload/" rel="nofollow noreferrer"><code>media_handle_sideload()</code></a> to insert the media into the library?</li>
</ol>
<h3>Background</h3>
<p>I've moved hosts, all my blog posts are available and all my images are in <code>/wp-content/uploads/2001/08</code> etc.</p>
<p>I have around 13,000 images across ~120 subfolders (10 years of blogging ☺).</p>
<p>Here's what I've tried that hasn't worked:</p>
<ul>
<li>Import WXR - imported the posts, but wouldn't import the images which were on the same server.</li>
<li><a href="https://en-gb.wordpress.org/plugins/media-from-ftp/" rel="nofollow noreferrer">Media From FTP</a> - didn't work with the huge number of images.</li>
<li><a href="https://wordpress.org/plugins/add-from-server/" rel="nofollow noreferrer">Add from Server</a> - only works on a per-file basis. I couldn't select a whole folder and all its sub-folders.</li>
<li>Other plugins seem to suffer from the same issue - they don't deal with nested directories, and they can't cope with thousands of files.</li>
</ul>
<p>All I want is something to scan my posts, find any <code><img src="https://example.com/...</code>, then import that into the media library - leaving the media in the same location. Attachment to the post & regeneration of thumbnails would be a bonus, but not essential.</p>
| [
{
"answer_id": 295988,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278450",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81576/"
] | I want to import into the media library, all the images & videos referenced in my blog posts.
1. Can I use [`get_attached_media()`](https://developer.wordpress.org/reference/functions/get_attached_media/) to get the images *referenced* on a page, even if they're not formally attached?
2. Should I use [`media_handle_sideload()`](https://developer.wordpress.org/reference/functions/media_handle_sideload/) to insert the media into the library?
### Background
I've moved hosts, all my blog posts are available and all my images are in `/wp-content/uploads/2001/08` etc.
I have around 13,000 images across ~120 subfolders (10 years of blogging ☺).
Here's what I've tried that hasn't worked:
* Import WXR - imported the posts, but wouldn't import the images which were on the same server.
* [Media From FTP](https://en-gb.wordpress.org/plugins/media-from-ftp/) - didn't work with the huge number of images.
* [Add from Server](https://wordpress.org/plugins/add-from-server/) - only works on a per-file basis. I couldn't select a whole folder and all its sub-folders.
* Other plugins seem to suffer from the same issue - they don't deal with nested directories, and they can't cope with thousands of files.
All I want is something to scan my posts, find any `<img src="https://example.com/...`, then import that into the media library - leaving the media in the same location. Attachment to the post & regeneration of thumbnails would be a bonus, but not essential. | This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar.
Style TinyMCE
=============
WordPress give us a neat little function called [`add_editor_style()`](https://developer.wordpress.org/reference/functions/add_editor_style/) which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest [TwentySeventeen theme](https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97). First let's create a stylesheet. The name doesn't matter but the location does.
```
body,
button,
input,
select,
textarea {
font-size: 14pt;
}
```
For simplicity we'll call this `editor-style.css` and save it in the theme:
```
/assets/css/editor-style.css
```
Next we need to tell WordPress to use our stylesheet so we'll open the themes `functions.php` file and add in:
```
/**
* Theme setup functionality
*
* @return void
*/
function prefix_theme_setup() {
// Relative path to the TinyMCE Stylesheet
add_editor_style( array( 'assets/css/editor-style.css' ) );
}
add_action( 'after_setup_theme', 'iqt_theme_setup' );
```
Some plugins could interfere with this such as page builders if they implement their own TinyMCE.
---
Modify Toolbar
==============
Next, we can use the [`tiny_mce_before_init`](https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/) [filter hook](https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init) to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your `functions.php` file:
```
/**
* Add Formats to TinyMCE
* - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/
* - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init
*
* @param array $args - Arguments used to initialize the tinyMCE
*
* @return array $args - Modified arguments
*/
function prefix_tinymce_toolbar( $args ) {
$args['fontsize_formats'] = "14pt 18pt 24pt 36pt";
return $args;
}
add_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' );
```
The `$args` array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, `px`, `em`, `rem` it doesn't matter, just that the list is separated by a space and is a valid `font-size` value. |
278,452 | <p>The error is:</p>
<blockquote>
<p>Warning: Cannot modify header information - headers already sent by (output started at
C:\wamp64444\www\demoplugin\wp-includes\class.wp-styles.php:237) in
C:\wamp64444\www\demoplugin\wp-includes\pluggable.php on line 914</p>
</blockquote>
<p>code of my plugin that create form for registration and form login </p>
<pre><code><?php
/*
Plugin Name: Form test
Plugin URI: http://co.com
Description: a plugin to create a form
Version: 1.2
Author: Ghn
Author URI: http://co.com
License: GPL2
*/
function registration_form($username, $password, $email)
{
echo'<form method="post" action="' . $_SERVER['REQUEST_URI'] . '" >
UserName: <input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '"><br>
Email: <input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"><br>
Password: <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"><br>
<input type="submit" name="submit" value="Register">
</form>';
}
function registration_validation( $username, $password, $email )
{
global $reg_errors;
$reg_errors = new WP_Error;
if ( empty( $username ) || empty( $password ) || empty( $email ) )
{
$reg_errors->add('field', 'Required form field is missing');
}
if ( 4 > strlen( $username ) )
{
$reg_errors->add( 'username_length', 'Username too short. At least 4 characters is required' );
}
if ( username_exists( $username ) )
$reg_errors->add('user_name', 'Sorry, that username already exists!');
if ( ! validate_username( $username ) )
{
$reg_errors->add( 'username_invalid', 'Sorry, the username you entered is not valid' );
}
if ( 5 > strlen( $password ) )
{
$reg_errors->add( 'password', 'Password length must be greater than 5' );
}
if ( !is_email( $email ) )
{
$reg_errors->add( 'email_invalid', 'Email is not valid' );
}
if ( email_exists( $email ) )
{
$reg_errors->add( 'email', 'Email Already in use' );
}
if ( is_wp_error( $reg_errors ) )
{
foreach ( $reg_errors->get_error_messages() as $error )
{
echo '<div>';
echo '<strong>ERROR</strong>:';
echo $error . '<br/>';
echo '</div>';
}
}
}
function complete_registration()
{
global $reg_errors, $username, $password, $email;
if ( 1 > count( $reg_errors->get_error_messages() ) )
{
$userdata = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
);
$user = wp_insert_user( $userdata );
echo 'Registration complete. ';
}
}
function custom_registration_function()
{
if ( isset($_POST['submit'] ) )
{
registration_validation(
$_POST['username'],
$_POST['password'],
$_POST['email']
);
// sanitize user form input
global $username, $password, $email;
$username = sanitize_user( $_POST['username'] );
$password = esc_attr( $_POST['password'] );
$email = sanitize_email( $_POST['email'] );
// call @function complete_registration to create the user
// only when no WP_error is found
complete_registration(
$username,
$password,
$email
);
}
registration_form(
$username,
$password,
$email
);
}
add_shortcode('test', 'form_creation');
// The callback function that will replace [book]
function form_creation() {
ob_start();
custom_registration_function();
return ob_get_clean();
}
function login_form()
{
echo'<form method="post" action="' . $_SERVER['REQUEST_URI'] . '" >
Email: <input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"><br>
Password: <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"><br>
<input type="submit" name="submit" value="Register">
</form>';
}
function dlf_auth( $username, $password )
{
global $user;
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
{
echo $user->get_error_message();
}
if ( !is_wp_error($user) )
{
echo 'login success';
}
}
function dlf_process()
{
if (isset($_POST['submit']))
{
dlf_auth($_POST['email'], $_POST['password']);
}
login_form();
}
add_shortcode('testlogin', 'login_test');
// The callback function that will replace [book]
function login_test() {
ob_start();
dlf_process();
return ob_get_clean();
}
</code></pre>
<p>?> </p>
| [
{
"answer_id": 295988,
"author": "Howdy_McGee",
"author_id": 7355,
"author_profile": "https://wordpress.stackexchange.com/users/7355",
"pm_score": 2,
"selected": true,
"text": "<p>This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278452",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126783/"
] | The error is:
>
> Warning: Cannot modify header information - headers already sent by (output started at
> C:\wamp64444\www\demoplugin\wp-includes\class.wp-styles.php:237) in
> C:\wamp64444\www\demoplugin\wp-includes\pluggable.php on line 914
>
>
>
code of my plugin that create form for registration and form login
```
<?php
/*
Plugin Name: Form test
Plugin URI: http://co.com
Description: a plugin to create a form
Version: 1.2
Author: Ghn
Author URI: http://co.com
License: GPL2
*/
function registration_form($username, $password, $email)
{
echo'<form method="post" action="' . $_SERVER['REQUEST_URI'] . '" >
UserName: <input type="text" name="username" value="' . ( isset( $_POST['username'] ) ? $username : null ) . '"><br>
Email: <input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"><br>
Password: <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"><br>
<input type="submit" name="submit" value="Register">
</form>';
}
function registration_validation( $username, $password, $email )
{
global $reg_errors;
$reg_errors = new WP_Error;
if ( empty( $username ) || empty( $password ) || empty( $email ) )
{
$reg_errors->add('field', 'Required form field is missing');
}
if ( 4 > strlen( $username ) )
{
$reg_errors->add( 'username_length', 'Username too short. At least 4 characters is required' );
}
if ( username_exists( $username ) )
$reg_errors->add('user_name', 'Sorry, that username already exists!');
if ( ! validate_username( $username ) )
{
$reg_errors->add( 'username_invalid', 'Sorry, the username you entered is not valid' );
}
if ( 5 > strlen( $password ) )
{
$reg_errors->add( 'password', 'Password length must be greater than 5' );
}
if ( !is_email( $email ) )
{
$reg_errors->add( 'email_invalid', 'Email is not valid' );
}
if ( email_exists( $email ) )
{
$reg_errors->add( 'email', 'Email Already in use' );
}
if ( is_wp_error( $reg_errors ) )
{
foreach ( $reg_errors->get_error_messages() as $error )
{
echo '<div>';
echo '<strong>ERROR</strong>:';
echo $error . '<br/>';
echo '</div>';
}
}
}
function complete_registration()
{
global $reg_errors, $username, $password, $email;
if ( 1 > count( $reg_errors->get_error_messages() ) )
{
$userdata = array(
'user_login' => $username,
'user_email' => $email,
'user_pass' => $password,
);
$user = wp_insert_user( $userdata );
echo 'Registration complete. ';
}
}
function custom_registration_function()
{
if ( isset($_POST['submit'] ) )
{
registration_validation(
$_POST['username'],
$_POST['password'],
$_POST['email']
);
// sanitize user form input
global $username, $password, $email;
$username = sanitize_user( $_POST['username'] );
$password = esc_attr( $_POST['password'] );
$email = sanitize_email( $_POST['email'] );
// call @function complete_registration to create the user
// only when no WP_error is found
complete_registration(
$username,
$password,
$email
);
}
registration_form(
$username,
$password,
$email
);
}
add_shortcode('test', 'form_creation');
// The callback function that will replace [book]
function form_creation() {
ob_start();
custom_registration_function();
return ob_get_clean();
}
function login_form()
{
echo'<form method="post" action="' . $_SERVER['REQUEST_URI'] . '" >
Email: <input type="email" name="email" value="' . ( isset( $_POST['email']) ? $email : null ) . '"><br>
Password: <input type="password" name="password" value="' . ( isset( $_POST['password'] ) ? $password : null ) . '"><br>
<input type="submit" name="submit" value="Register">
</form>';
}
function dlf_auth( $username, $password )
{
global $user;
$creds = array();
$creds['user_login'] = $username;
$creds['user_password'] = $password;
$user = wp_signon( $creds, false );
if ( is_wp_error($user) )
{
echo $user->get_error_message();
}
if ( !is_wp_error($user) )
{
echo 'login success';
}
}
function dlf_process()
{
if (isset($_POST['submit']))
{
dlf_auth($_POST['email'], $_POST['password']);
}
login_form();
}
add_shortcode('testlogin', 'login_test');
// The callback function that will replace [book]
function login_test() {
ob_start();
dlf_process();
return ob_get_clean();
}
```
?> | This is kind of a 2-parter. The first half will show you how to change the style inside TinyMCE when editing. The second half will show you how to remove things from the toolbar.
Style TinyMCE
=============
WordPress give us a neat little function called [`add_editor_style()`](https://developer.wordpress.org/reference/functions/add_editor_style/) which accepts an array of stylesheets, either by URL or relative paths. WordPress default themes usually take advantage of this function and can be seen in the latest [TwentySeventeen theme](https://github.com/WordPress/twentyseventeen/blob/master/functions.php#L97). First let's create a stylesheet. The name doesn't matter but the location does.
```
body,
button,
input,
select,
textarea {
font-size: 14pt;
}
```
For simplicity we'll call this `editor-style.css` and save it in the theme:
```
/assets/css/editor-style.css
```
Next we need to tell WordPress to use our stylesheet so we'll open the themes `functions.php` file and add in:
```
/**
* Theme setup functionality
*
* @return void
*/
function prefix_theme_setup() {
// Relative path to the TinyMCE Stylesheet
add_editor_style( array( 'assets/css/editor-style.css' ) );
}
add_action( 'after_setup_theme', 'iqt_theme_setup' );
```
Some plugins could interfere with this such as page builders if they implement their own TinyMCE.
---
Modify Toolbar
==============
Next, we can use the [`tiny_mce_before_init`](https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/) [filter hook](https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init) to modify the TinyMCE. In this case, all we need to do if override the font sizes. You can add the following function into your `functions.php` file:
```
/**
* Add Formats to TinyMCE
* - https://developer.wordpress.org/reference/hooks/tiny_mce_before_init/
* - https://codex.wordpress.org/Plugin_API/Filter_Reference/tiny_mce_before_init
*
* @param array $args - Arguments used to initialize the tinyMCE
*
* @return array $args - Modified arguments
*/
function prefix_tinymce_toolbar( $args ) {
$args['fontsize_formats'] = "14pt 18pt 24pt 36pt";
return $args;
}
add_filter( 'tiny_mce_before_init', 'prefix_tinymce_toolbar' );
```
The `$args` array has an index that accepts a list of font sizes separated by spaces. You can change these to whatever you want, `px`, `em`, `rem` it doesn't matter, just that the list is separated by a space and is a valid `font-size` value. |
278,476 | <p>I am currently trying to change <strong>Woocommerce redirect url</strong> for login only when users logged from a specific page. So first I tried that way in my template page:</p>
<pre><code><?php woocommerce_login_form(array('redirect'=>$_SERVER['REQUEST_URI'])); ?>
</code></pre>
<p>Then, I saw user is still redirected to default (my-account) so I used the login hook that way:</p>
<pre><code>function share_login_redirect( $redirect ) {
if( strtr($_SERVER['REQUEST_URI'],array('/partage','/share')) ){
$redirect = get_site_url().$_SERVER['REQUEST_URI'];
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 );
</code></pre>
<p>All of thoses techniques didn't work for me. Knowing that <code>$redirect = "https://mysite/share/?param=xx"</code> what am I doing wrong there?</p>
<p>2017-08-29 EDIT : If anyone had the same problem as I did, it is possible a plugin uses the same hook than you and have an higher priority than yours meaning the redirect will not work until you move up your priority. Please see my answer below.</p>
| [
{
"answer_id": 278478,
"author": "Jeff Mattson",
"author_id": 93714,
"author_profile": "https://wordpress.stackexchange.com/users/93714",
"pm_score": 2,
"selected": false,
"text": "<p>Try changing <code>strtr</code> to <code>strpos</code>. However, you can not give it an array for needl... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278476",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96315/"
] | I am currently trying to change **Woocommerce redirect url** for login only when users logged from a specific page. So first I tried that way in my template page:
```
<?php woocommerce_login_form(array('redirect'=>$_SERVER['REQUEST_URI'])); ?>
```
Then, I saw user is still redirected to default (my-account) so I used the login hook that way:
```
function share_login_redirect( $redirect ) {
if( strtr($_SERVER['REQUEST_URI'],array('/partage','/share')) ){
$redirect = get_site_url().$_SERVER['REQUEST_URI'];
}
return $redirect;
}
add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 );
```
All of thoses techniques didn't work for me. Knowing that `$redirect = "https://mysite/share/?param=xx"` what am I doing wrong there?
2017-08-29 EDIT : If anyone had the same problem as I did, it is possible a plugin uses the same hook than you and have an higher priority than yours meaning the redirect will not work until you move up your priority. Please see my answer below. | I found what was my problem is priority. Some other plugin was using a 1000 priority, so I had to boost my priority when declaring the hook. That way:
```
add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 1100, 2 );
```
instead of
```
add_filter( 'woocommerce_login_redirect', 'share_login_redirect', 10, 2 );
``` |
278,504 | <p>Trying to run a custom script on a single page using is_page in functions.php not working at all. I have a function called load_gh_boards that would enquque a script, only on a certain page (79): </p>
<pre><code>function load_gh_boards() {
if( is_page(79) ){
wp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true );
}}
add_action('wp_enqueue_script', 'load_gh_boards');
</code></pre>
<p>This is inside a theme enqueue function that is loading all of my styles and scripts:</p>
<pre><code>function theme_enqueue() {
if ( ! is_admin() ) {
wp_register_style( 'main-style', get_bloginfo( 'template_directory' ) . '/css/style.css?' . time() );
wp_enqueue_style( 'main-style' );
wp_enqueue_script( 'jquery' );
wp_register_script( 'main-vendor', get_bloginfo( 'template_directory' ) . '/js/vendor.js', array(), '1.0', true );
///etc...
wp_enqueue_script( 'main-vendor' );
wp_enqueue_script( 'main-script' );
///load_gh_boards
}
</code></pre>
<p>No result. Any help or insight at all would be appreciated.</p>
| [
{
"answer_id": 278505,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 0,
"selected": false,
"text": "<p>First of all, there is a mistype in your code. It's <code>wp_enqueue_scripts</code>, not <code>wp_enqueue_s... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278504",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114585/"
] | Trying to run a custom script on a single page using is\_page in functions.php not working at all. I have a function called load\_gh\_boards that would enquque a script, only on a certain page (79):
```
function load_gh_boards() {
if( is_page(79) ){
wp_register_script( 'gh-jobs-board', get_bloginfo( 'template_directory' ) . '/js/gh-jobs-board.js', array(), '1.0', true );
}}
add_action('wp_enqueue_script', 'load_gh_boards');
```
This is inside a theme enqueue function that is loading all of my styles and scripts:
```
function theme_enqueue() {
if ( ! is_admin() ) {
wp_register_style( 'main-style', get_bloginfo( 'template_directory' ) . '/css/style.css?' . time() );
wp_enqueue_style( 'main-style' );
wp_enqueue_script( 'jquery' );
wp_register_script( 'main-vendor', get_bloginfo( 'template_directory' ) . '/js/vendor.js', array(), '1.0', true );
///etc...
wp_enqueue_script( 'main-vendor' );
wp_enqueue_script( 'main-script' );
///load_gh_boards
}
```
No result. Any help or insight at all would be appreciated. | `is_page(79)` is asking if the current main query is a page, specifically page 79
**But the main query hasn't happened yet**
This function has to be called inside the main loop or at the very least inside the template, but the `init` hook is way too early for this.
Instead, make sure you use the body class, and load the script on all pages. Then, check if the body tag has the css class `page-id-79`.
Other Notes
-----------
* You don't enqueue on the `init` hook, you're meant to enqueue on the `wp_enqueue_scripts` hook
* It would be simpler to return early e.g. `if ( is_admin() ) return;`
* Don't enqueue jQuery, instead add it as a dependency so WP knows how to output the scripts in the correct order
* main-style and main-vendor are very generic names, you might encounter clashes, prefix them, e.g. `pji-main-vendor`
* `theme_enqueue` is also a very generic function name, you should prefix that too
* You can register and enqueue at the same time using `wp_enqueue_script`. If you pass everything to that function there's no need to call `wp_register_script`
* Indent your code, modern code editors will do this automatically for free, zero effort. Sublime or Atom are examples of free software that will do this for you, there really are no excuses |
278,527 | <p>-I am running a woo commencers shop</p>
<p>-Users have the ability to add products using wp insert post</p>
<p>-The product gallery multiple image upload will only add the last image to the post but in media they are all attached to the correct post</p>
<p>This is my code</p>
<p>function.php</p>
<pre><code>function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ( is_numeric( $attach_id ) ) {
update_post_meta( $post_id, '_product_image_gallery', $attach_id );
}
return $attach_id;
}
</code></pre>
<p>front-end</p>
<pre><code>if ( $_FILES ) {
$files = $_FILES["my_file_upload"];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array ("my_file_upload" => $file);
$newupload = my_handle_attachment( "my_file_upload", $post_id);
}
}
}
</code></pre>
<p>input</p>
<pre><code><input type="file" name="my_file_upload[]" multiple="multiple" >
</code></pre>
<p>This will upload all images and attach them to the correct post but only the last image will show up in Products gallery image section. What am i doing wrong?</p>
| [
{
"answer_id": 330163,
"author": "Tcmxc",
"author_id": 63922,
"author_profile": "https://wordpress.stackexchange.com/users/63922",
"pm_score": 1,
"selected": true,
"text": "<pre><code>if ( ! empty( $_FILES['muti_files'] ) ) {\n $files = $_FILES['muti_files'];\n for... | 2017/08/29 | [
"https://wordpress.stackexchange.com/questions/278527",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63922/"
] | -I am running a woo commencers shop
-Users have the ability to add products using wp insert post
-The product gallery multiple image upload will only add the last image to the post but in media they are all attached to the correct post
This is my code
function.php
```
function my_handle_attachment($file_handler,$post_id,$set_thu=false) {
if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attach_id = media_handle_upload( $file_handler, $post_id );
if ( is_numeric( $attach_id ) ) {
update_post_meta( $post_id, '_product_image_gallery', $attach_id );
}
return $attach_id;
}
```
front-end
```
if ( $_FILES ) {
$files = $_FILES["my_file_upload"];
foreach ($files['name'] as $key => $value) {
if ($files['name'][$key]) {
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
$_FILES = array ("my_file_upload" => $file);
$newupload = my_handle_attachment( "my_file_upload", $post_id);
}
}
}
```
input
```
<input type="file" name="my_file_upload[]" multiple="multiple" >
```
This will upload all images and attach them to the correct post but only the last image will show up in Products gallery image section. What am i doing wrong? | ```
if ( ! empty( $_FILES['muti_files'] ) ) {
$files = $_FILES['muti_files'];
foreach ($files['name'] as $key => $value){
if ($files['name'][$key]){
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
}
$_FILES = array("muti_files" => $file);
$i=1;
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload($file, $post_id);
$vv .= $attachment_id . ",";
$i++;
}
update_post_meta($post_id, '_product_image_gallery', $vv);
}
}
``` |
278,533 | <p>When Users create custom post types, the author field does not seem to be passed back to WP posts functions.</p>
<p>As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post_type = 'job'.</p>
<p>This all LOOKS good in the database - the user, and post are inserted. The post_author is indeed the same as the ID of the user who created it.</p>
<p>But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author.</p>
<p>I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp_update_post();</p>
<p>Here's the code to create the user, and then the post:</p>
<pre><code>// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );
//login
wp_clear_auth_cookie();
wp_set_current_user ( $user_id );
wp_set_auth_cookie ( $user_id );
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
//Ready data for linked post type creation
$new_post = array(
'post_content' => $email_address,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_id,
'post_title' => $post_name,
'post_name' => $post_name,
'post_type' => $user_type
);
//Create the post
$account_link_post_id = wp_insert_post($new_post);
</code></pre>
<p>ANY suggestions here would be great. Thank you in advance.</p>
| [
{
"answer_id": 330163,
"author": "Tcmxc",
"author_id": 63922,
"author_profile": "https://wordpress.stackexchange.com/users/63922",
"pm_score": 1,
"selected": true,
"text": "<pre><code>if ( ! empty( $_FILES['muti_files'] ) ) {\n $files = $_FILES['muti_files'];\n for... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278533",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122711/"
] | When Users create custom post types, the author field does not seem to be passed back to WP posts functions.
As the title says, I'm creating a user account programatically, and having that user log-in and write a post of custom post\_type = 'job'.
This all LOOKS good in the database - the user, and post are inserted. The post\_author is indeed the same as the ID of the user who created it.
But, in the User Accounts panel, that user post count is 0, and the API data object omits the author. I've configured the API for the additional custom post type and the endpoint works to return all post data EXCEPT author.
I've tried creating a post from the CMS with these users as well, and likewise, even if I give them Administrator permissions, they have a 0 post count - the posts are attributed to their author ID. I've also tried to force and update using wp\_update\_post();
Here's the code to create the user, and then the post:
```
// Generate the password and create the user
$password = wp_generate_password( 12, false );
$user_id = wp_create_user( $email_address, $password, $email_address );
//login
wp_clear_auth_cookie();
wp_set_current_user ( $user_id );
wp_set_auth_cookie ( $user_id );
// Set the role
$user = new WP_User( $user_id );
$user->set_role( 'subscriber' );
//Ready data for linked post type creation
$new_post = array(
'post_content' => $email_address,
'post_status' => 'publish',
'post_date' => date('Y-m-d H:i:s'),
'post_author' => $user_id,
'post_title' => $post_name,
'post_name' => $post_name,
'post_type' => $user_type
);
//Create the post
$account_link_post_id = wp_insert_post($new_post);
```
ANY suggestions here would be great. Thank you in advance. | ```
if ( ! empty( $_FILES['muti_files'] ) ) {
$files = $_FILES['muti_files'];
foreach ($files['name'] as $key => $value){
if ($files['name'][$key]){
$file = array(
'name' => $files['name'][$key],
'type' => $files['type'][$key],
'tmp_name' => $files['tmp_name'][$key],
'error' => $files['error'][$key],
'size' => $files['size'][$key]
);
}
$_FILES = array("muti_files" => $file);
$i=1;
foreach ($_FILES as $file => $array) {
if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) __return_false();
require_once(ABSPATH . "wp-admin" . '/includes/image.php');
require_once(ABSPATH . "wp-admin" . '/includes/file.php');
require_once(ABSPATH . "wp-admin" . '/includes/media.php');
$attachment_id = media_handle_upload($file, $post_id);
$vv .= $attachment_id . ",";
$i++;
}
update_post_meta($post_id, '_product_image_gallery', $vv);
}
}
``` |
278,541 | <p>I use the bellow template to display the first event from an ascendent list of custom post type events, created by a third party plugin. What I want is to exclude old events, displaying only the one actual, if we have one today, or the nearest. The event start date is saved in a <code>meta_key</code> with a value in the "Y-m-d" format (ex: 2017-10-27). How to accomplish this?</p>
<pre><code><?php
wp_reset_query();
$args = array(
'post_type' => 'events',
'posts_per_page' => 1,
'meta_key' => 'event_start_date',
'order' => 'ASC'
);
$featured = new WP_Query($args);
if ($featured->have_posts()):
while($featured->have_posts()): $featured->the_post();
$featured_event_start = $post->event_start_date;
$featured_event_end = $post->event_end_date;
if (has_post_thumbnail()) : ?>
<div class="featured-event-outer">
<div class="featured-event-inner">
<figure><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium_large'); ?></a></figure>
<h3 class="featured-event-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<h3 class="featured-event-date">
<a href="<?php the_permalink(); ?>"><?php echo $featured_event_start;
if ( $featured_event_end && $featured_event_end != $featured_event_start ) { echo ' - ' . $featured_event_end; } ?>
</a>
</h3>
</div>
</div>
<?php endif; ?>
<?php endwhile;
else: ?>
<!-- Placeholder content goes here -->
<?php endif;
wp_reset_postdata();
?>
</code></pre>
| [
{
"answer_id": 278545,
"author": "Abdul Awal Uzzal",
"author_id": 31449,
"author_profile": "https://wordpress.stackexchange.com/users/31449",
"pm_score": 2,
"selected": false,
"text": "<p>You need something like the following:</p>\n\n<pre><code>$args = array(\n 'post_type' =&g... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278541",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/25187/"
] | I use the bellow template to display the first event from an ascendent list of custom post type events, created by a third party plugin. What I want is to exclude old events, displaying only the one actual, if we have one today, or the nearest. The event start date is saved in a `meta_key` with a value in the "Y-m-d" format (ex: 2017-10-27). How to accomplish this?
```
<?php
wp_reset_query();
$args = array(
'post_type' => 'events',
'posts_per_page' => 1,
'meta_key' => 'event_start_date',
'order' => 'ASC'
);
$featured = new WP_Query($args);
if ($featured->have_posts()):
while($featured->have_posts()): $featured->the_post();
$featured_event_start = $post->event_start_date;
$featured_event_end = $post->event_end_date;
if (has_post_thumbnail()) : ?>
<div class="featured-event-outer">
<div class="featured-event-inner">
<figure><a href="<?php the_permalink(); ?>"><?php the_post_thumbnail('medium_large'); ?></a></figure>
<h3 class="featured-event-title"><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></h3>
<h3 class="featured-event-date">
<a href="<?php the_permalink(); ?>"><?php echo $featured_event_start;
if ( $featured_event_end && $featured_event_end != $featured_event_start ) { echo ' - ' . $featured_event_end; } ?>
</a>
</h3>
</div>
</div>
<?php endif; ?>
<?php endwhile;
else: ?>
<!-- Placeholder content goes here -->
<?php endif;
wp_reset_postdata();
?>
``` | OK, with some help from [@jonathan-wold](https://wordpress.stackexchange.com/a/12305/25187), I figured out how to solve my problem. In my initial code I just replaced the `$args` part, accordingly to mentioned author, and this worked like a charm. This is the code:
```
$args = array(
'post_type' => 'events', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'event_start_date', // Grab the "start date" field created via "More Fields" plugin (stored in YYYY-MM-DD format)
'order' => 'ASC', // ASC is the other option
'posts_per_page' => '1', // Let's show only one / the first event.
'meta_query' => array( // WordPress has all the results, now, return only the events after today's date
array(
'key' => 'event_start_date', // Check the start date field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than or equal to today's date
'type' => 'DATE' // Let WordPress know we're working with date
)
)
);
``` |
278,555 | <p>How can I submit pull request to other's plugin, which is hosted at <strong>wordpress.org</strong>?</p>
| [
{
"answer_id": 278545,
"author": "Abdul Awal Uzzal",
"author_id": 31449,
"author_profile": "https://wordpress.stackexchange.com/users/31449",
"pm_score": 2,
"selected": false,
"text": "<p>You need something like the following:</p>\n\n<pre><code>$args = array(\n 'post_type' =&g... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278555",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33667/"
] | How can I submit pull request to other's plugin, which is hosted at **wordpress.org**? | OK, with some help from [@jonathan-wold](https://wordpress.stackexchange.com/a/12305/25187), I figured out how to solve my problem. In my initial code I just replaced the `$args` part, accordingly to mentioned author, and this worked like a charm. This is the code:
```
$args = array(
'post_type' => 'events', // Tell WordPress which post type we want
'orderby' => 'meta_value', // We want to organize the events by date
'meta_key' => 'event_start_date', // Grab the "start date" field created via "More Fields" plugin (stored in YYYY-MM-DD format)
'order' => 'ASC', // ASC is the other option
'posts_per_page' => '1', // Let's show only one / the first event.
'meta_query' => array( // WordPress has all the results, now, return only the events after today's date
array(
'key' => 'event_start_date', // Check the start date field
'value' => date("Y-m-d"), // Set today's date (note the similar format)
'compare' => '>=', // Return the ones greater than or equal to today's date
'type' => 'DATE' // Let WordPress know we're working with date
)
)
);
``` |
278,561 | <p>Should I able to change URL structure of WordPress blog? (Free WordPress hosted blog) </p>
<p>Right now I have this way: (see URL structure)</p>
<pre><code>helloworld.wordpress.com/london
</code></pre>
<p>But I want to use as this way:</p>
<pre><code>helloworld.wordpress.com/carhire/uk/london
</code></pre>
<p>Is this achievable?</p>
| [
{
"answer_id": 278562,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": true,
"text": "<p>Yes, this is achievable and quite simple to do so. Go to <strong>Settings</strong> > <strong>Permalinks</strong... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278561",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126838/"
] | Should I able to change URL structure of WordPress blog? (Free WordPress hosted blog)
Right now I have this way: (see URL structure)
```
helloworld.wordpress.com/london
```
But I want to use as this way:
```
helloworld.wordpress.com/carhire/uk/london
```
Is this achievable? | Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area.
There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/)
```
/carhire/uk/%postname%/
```
If your logic is more complex, I suggest using a plugin such as [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/).
**Edit:**
I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this. |
278,580 | <p>I can't get this line of code translation ready.</p>
<pre><code><?php
comment_form(array ('title_reply' => 'Leave a comment'));
?>
</code></pre>
<p>Thank you very much! Best wishes,
Pierre</p>
| [
{
"answer_id": 278562,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": true,
"text": "<p>Yes, this is achievable and quite simple to do so. Go to <strong>Settings</strong> > <strong>Permalinks</strong... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278580",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126835/"
] | I can't get this line of code translation ready.
```
<?php
comment_form(array ('title_reply' => 'Leave a comment'));
?>
```
Thank you very much! Best wishes,
Pierre | Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area.
There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/)
```
/carhire/uk/%postname%/
```
If your logic is more complex, I suggest using a plugin such as [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/).
**Edit:**
I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this. |
278,612 | <p>I´am creating a Plugin. For this I wrote my own templates. Now I want to have the templeates files in my Plugin directory. </p>
<p>But that doenst work fine. Since I used the Plugin directory, wordpress doesent know that are my templates are wp templeates. What is the best way to let WP know, that these files are a wordpress Templates? </p>
<p>Thanks for answer :)</p>
| [
{
"answer_id": 278562,
"author": "kero",
"author_id": 108180,
"author_profile": "https://wordpress.stackexchange.com/users/108180",
"pm_score": 2,
"selected": true,
"text": "<p>Yes, this is achievable and quite simple to do so. Go to <strong>Settings</strong> > <strong>Permalinks</strong... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278612",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126872/"
] | I´am creating a Plugin. For this I wrote my own templates. Now I want to have the templeates files in my Plugin directory.
But that doenst work fine. Since I used the Plugin directory, wordpress doesent know that are my templates are wp templeates. What is the best way to let WP know, that these files are a wordpress Templates?
Thanks for answer :) | Yes, this is achievable and quite simple to do so. Go to **Settings** > **Permalinks** in your admin area.
There you should be able to select **Custom** and use a value like (if you want all URLs to start with /carhire/uk/)
```
/carhire/uk/%postname%/
```
If your logic is more complex, I suggest using a plugin such as [Custom Permalinks](https://wordpress.org/plugins/custom-permalinks/).
**Edit:**
I just tried it myself, on the wordpress.com free plan it seems that you can't change permalinks at all (neither via settings nor via plugin). If you upgrade to the Business plan (~24$/mo), it is possible to install plugins - and the aforementioned should solve this. |
278,613 | <p>I have the following args array</p>
<pre><code>{
"ordreby":"meta_value_num",
"meta_key":"_price",
"posts_per_page":10,
"offset":0,
"post_type":"product",
"post_status":"publish",
"order":"asc",
"suppress_filters":false,
}
</code></pre>
<p>when i do </p>
<pre><code> $myposts = get_posts($args);
</code></pre>
<p>the order by <strong>_price</strong> (or other meta keys) is not working. </p>
<p>any idea?</p>
| [
{
"answer_id": 278617,
"author": "Z. Zlatev",
"author_id": 4192,
"author_profile": "https://wordpress.stackexchange.com/users/4192",
"pm_score": 1,
"selected": false,
"text": "<p><code>meta_query</code> should be an array of arrays like:</p>\n\n<pre><code>...\n'meta_query' => [\n [... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278613",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/122895/"
] | I have the following args array
```
{
"ordreby":"meta_value_num",
"meta_key":"_price",
"posts_per_page":10,
"offset":0,
"post_type":"product",
"post_status":"publish",
"order":"asc",
"suppress_filters":false,
}
```
when i do
```
$myposts = get_posts($args);
```
the order by **\_price** (or other meta keys) is not working.
any idea? | Change
`"ordreby":"meta_value_num"`
for
```
"orderby":"meta_value_num"
```
a dyslexic error xD |
278,628 | <p>I have created the <strong>Read more</strong> in my posts, but when I add the php tag </p>
<pre><code><?php the_content(); ?>
</code></pre>
<p>...it shows the post content with <strong>read more</strong> button. I only want to display the button, with no post content.</p>
<p>Here is a picture of my design .<img src="https://i.stack.imgur.com/8UYN9.png" alt="Desired design"></p>
<p>In the picture, I only display the button without text from the post.
How can i do that with WordPress php code?</p>
| [
{
"answer_id": 278638,
"author": "Osama Elzero",
"author_id": 126781,
"author_profile": "https://wordpress.stackexchange.com/users/126781",
"pm_score": 2,
"selected": false,
"text": "<p>You can achieve this with many ways. First thing you need to use </p>\n\n<pre><code>the_excerpt() \n</... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278628",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126889/"
] | I have created the **Read more** in my posts, but when I add the php tag
```
<?php the_content(); ?>
```
...it shows the post content with **read more** button. I only want to display the button, with no post content.
Here is a picture of my design .
In the picture, I only display the button without text from the post.
How can i do that with WordPress php code? | You can achieve this with many ways. First thing you need to use
```
the_excerpt()
```
instead of
```
the_content()
```
and in your functions.php file you can add this function to return 0 text from post text.
```
function custom_excerpt_length($length) {
if (is_home()) {
return 0;
}
}
add_filter('excerpt_length', 'custom_excerpt_length');
```
This code check if this is homepage you can change the condition to met your needs. |
278,631 | <p>I am trying to get a child theme to work. At first it didn't load because it didn't recognise it as a child theme. Now it does work but when I activate it, it loads a version of my page seemingly without any css or something. There's only text and images there, but no styling. Is it that it isn't using the parent theme fully or something?</p>
<p>I am just starting with Wordpress so I'm sorry if I'm not very clear or using the right terminology. Thanks in advance.</p>
<p>This is my functions.php file:</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = ‘twenty seventeen-style’;
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
</code></pre>
| [
{
"answer_id": 278638,
"author": "Osama Elzero",
"author_id": 126781,
"author_profile": "https://wordpress.stackexchange.com/users/126781",
"pm_score": 2,
"selected": false,
"text": "<p>You can achieve this with many ways. First thing you need to use </p>\n\n<pre><code>the_excerpt() \n</... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278631",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126890/"
] | I am trying to get a child theme to work. At first it didn't load because it didn't recognise it as a child theme. Now it does work but when I activate it, it loads a version of my page seemingly without any css or something. There's only text and images there, but no styling. Is it that it isn't using the parent theme fully or something?
I am just starting with Wordpress so I'm sorry if I'm not very clear or using the right terminology. Thanks in advance.
This is my functions.php file:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = ‘twenty seventeen-style’;
wp_enqueue_style( $parent_style, get_template_directory_uri() . '/style.css' );
wp_enqueue_style( 'child-style',
get_stylesheet_directory_uri() . '/style.css',
array( $parent_style ),
wp_get_theme()->get('Version')
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
``` | You can achieve this with many ways. First thing you need to use
```
the_excerpt()
```
instead of
```
the_content()
```
and in your functions.php file you can add this function to return 0 text from post text.
```
function custom_excerpt_length($length) {
if (is_home()) {
return 0;
}
}
add_filter('excerpt_length', 'custom_excerpt_length');
```
This code check if this is homepage you can change the condition to met your needs. |
278,647 | <p>I have tried adding this to <code>style.css</code>:</p>
<pre><code>.sidebar, .widget-area, .secondary {
position: absolute
margin-left: 120px;
max-width: 250px;
}
</code></pre>
<p>But it won't move. If I remove <code>position:absolute</code>, it is pushed down, getting under all the other content.</p>
| [
{
"answer_id": 279137,
"author": "rudtek",
"author_id": 77767,
"author_profile": "https://wordpress.stackexchange.com/users/77767",
"pm_score": 0,
"selected": false,
"text": "<p>there are 2 pieces of code in the css:</p>\n\n<pre><code>.has-sidebar #secondary {\n float: right;\n pad... | 2017/08/30 | [
"https://wordpress.stackexchange.com/questions/278647",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126901/"
] | I have tried adding this to `style.css`:
```
.sidebar, .widget-area, .secondary {
position: absolute
margin-left: 120px;
max-width: 250px;
}
```
But it won't move. If I remove `position:absolute`, it is pushed down, getting under all the other content. | You have 2 options:
**Option 1.**
Just add negative margin to the sidebar CSS like this:
```
@media screen and (min-width: 48em){
#secondary{
margin-right:-150px;
}
}
```
**Option 2.**
Add more max-width to the wrapper:
```
@media screen and (min-width: 48em){
.wrap{
max-width: 1340px;//the default is 1000
padding-left: 348px;//you have to add padding left so the left side doesnt move, the amount needs to be proportional to the amount of max-width you are incrementing
}
}
```
i added the media query, its needed so this CSS doesnt affect the mobile view. |
278,655 | <p>HTML:</p>
<pre><code><header>
<!-- I want to add html code here -->
</header>
</code></pre>
<p>Function:</p>
<pre><code> function add_html_to_header {
<b> Hello World </b>
}
add_action('','add_html_to_header')
</code></pre>
<p>Expected Html results:</p>
<pre><code><header id="header">
<b> Hello World </b>
</header>
</code></pre>
<p><strong>EDIT:</strong> Is it possible without using <code>Javascript</code>? </p>
| [
{
"answer_id": 278656,
"author": "Monkey Puzzle",
"author_id": 48568,
"author_profile": "https://wordpress.stackexchange.com/users/48568",
"pm_score": 2,
"selected": false,
"text": "<p>You can add html to the site head using this function:</p>\n\n<pre><code>// Add scripts to wp_head()\nf... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278655",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/96537/"
] | HTML:
```
<header>
<!-- I want to add html code here -->
</header>
```
Function:
```
function add_html_to_header {
<b> Hello World </b>
}
add_action('','add_html_to_header')
```
Expected Html results:
```
<header id="header">
<b> Hello World </b>
</header>
```
**EDIT:** Is it possible without using `Javascript`? | You can add html to the site head using this function:
```
// Add scripts to wp_head()
function add_head_html() { ?>
<!-- html goes here -->
<?php }
add_action( 'wp_head', 'add_head_html' );
```
But if you're talking about the html element `<header>` (as it sounds like from your edits) it sounds like overcomplicating things, but you might want to look at injecting it with jquery into the right spot using a solution such as this:
<https://stackoverflow.com/a/9866637/3387817> |
278,662 | <p>I'm trying to enqueue a JavaScript file in the header of my website.</p>
<p>If I add the following in my main plugin file the JS is included in the header:</p>
<pre><code>function wpdocs_theme_name_scripts() {
wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');
wp_enqueue_script('googlesearch');
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
</code></pre>
<p>But I want to include the JS for a specific shortcode only, I add the following in the main plugin file:</p>
<pre><code>function wpdocs_theme_name_scripts() {
wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
</code></pre>
<p>And the following in the shortcode:</p>
<pre><code>wp_enqueue_script('googlesearch');
</code></pre>
<p>Now the JS file is included in the footer of the website.</p>
<p>I've tried manually specifying that the JS should be loaded in the header like so but it still loads it in the footer:</p>
<pre><code>wp_enqueue_script( 'googlesearch', 'https://maps.googleapis.com/maps/api/js', array(), '1.0.0', false );
</code></pre>
<p>Does anyone have any idea why this is happening? Appreciated any help!</p>
| [
{
"answer_id": 278666,
"author": "KAGG Design",
"author_id": 108721,
"author_profile": "https://wordpress.stackexchange.com/users/108721",
"pm_score": 2,
"selected": false,
"text": "<p>Page is created and output in the following order: header, content, footer. Shorcode is executed during... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81594/"
] | I'm trying to enqueue a JavaScript file in the header of my website.
If I add the following in my main plugin file the JS is included in the header:
```
function wpdocs_theme_name_scripts() {
wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');
wp_enqueue_script('googlesearch');
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
But I want to include the JS for a specific shortcode only, I add the following in the main plugin file:
```
function wpdocs_theme_name_scripts() {
wp_register_script('googlesearch', 'https://maps.googleapis.com/maps/api/js');
}
add_action( 'wp_enqueue_scripts', 'wpdocs_theme_name_scripts' );
```
And the following in the shortcode:
```
wp_enqueue_script('googlesearch');
```
Now the JS file is included in the footer of the website.
I've tried manually specifying that the JS should be loaded in the header like so but it still loads it in the footer:
```
wp_enqueue_script( 'googlesearch', 'https://maps.googleapis.com/maps/api/js', array(), '1.0.0', false );
```
Does anyone have any idea why this is happening? Appreciated any help! | Page is created and output in the following order: header, content, footer. Shorcode is executed during the construction of the page content, when header is already output on the page. So, it is impossible to add any script to header on this stage: it is too late. |
278,696 | <p>I've been trying to change the title in a dynamic page without any luck.</p>
<p>What I did is I created two page-templates from where I load items (occasions) from an external database.
In one page-template I load the single-page occasion:</p>
<pre><code><?php include 'Occasions-files/single.php';?>
</code></pre>
<p>And the second page-template I load an overview of the occasions:</p>
<pre><code><?php include 'Occasions-files/file.php';?>
</code></pre>
<p>Now the title is default from the SEO plugin. I've tried All-in-One SEO as well as Yoast SEO but can't seem to overwrite the title.
What I want is to change the title from single.php into the occasion name but leave all the other pages to the SEO plugin.</p>
<p>I'm not quite experienced with this and I'm not sure where to start.
For testing purpose I've tried to put test manually before the get_header, then it shows the manually added title, but my header is messed up.
When I put the title after the get_header, it loads the header ok but the title isn't shown and is still default</p>
<pre><code><title>test</title>
<?php get_header(); ?>
</code></pre>
<p>Also, I've tried to add a filter (to the functions.php) but this was also without any results or maybe I have no clue on how to insert it..?</p>
<pre><code>function custom_title_function($custom_title) {
$custom_title['title'] = "Test Title";
return $custom_title; }
add_filter( 'document_title_parts', 'custom_title_function' );
</code></pre>
<p>Anyone has an idea on how to resolve this?
Many thanks in advanced!</p>
| [
{
"answer_id": 278724,
"author": "James",
"author_id": 34484,
"author_profile": "https://wordpress.stackexchange.com/users/34484",
"pm_score": 1,
"selected": false,
"text": "<p>Just to make sure, does the title tag in your <code><head></code> area (presumably in header.php) look li... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126415/"
] | I've been trying to change the title in a dynamic page without any luck.
What I did is I created two page-templates from where I load items (occasions) from an external database.
In one page-template I load the single-page occasion:
```
<?php include 'Occasions-files/single.php';?>
```
And the second page-template I load an overview of the occasions:
```
<?php include 'Occasions-files/file.php';?>
```
Now the title is default from the SEO plugin. I've tried All-in-One SEO as well as Yoast SEO but can't seem to overwrite the title.
What I want is to change the title from single.php into the occasion name but leave all the other pages to the SEO plugin.
I'm not quite experienced with this and I'm not sure where to start.
For testing purpose I've tried to put test manually before the get\_header, then it shows the manually added title, but my header is messed up.
When I put the title after the get\_header, it loads the header ok but the title isn't shown and is still default
```
<title>test</title>
<?php get_header(); ?>
```
Also, I've tried to add a filter (to the functions.php) but this was also without any results or maybe I have no clue on how to insert it..?
```
function custom_title_function($custom_title) {
$custom_title['title'] = "Test Title";
return $custom_title; }
add_filter( 'document_title_parts', 'custom_title_function' );
```
Anyone has an idea on how to resolve this?
Many thanks in advanced! | Just to make sure, does the title tag in your `<head>` area (presumably in header.php) look like this?
```
<title><?php wp_title(); ?></title>
```
It has to be like that for Yoast to work with it, and be able to override titles.
Anyway if you add this to your single.php (or at least before `get_header()` is run for that page) you should be able to modify the page title:
```
function custom_page_title( $title ){
$return = $title;
// You can check what the current post is via $wp_query->post
global $wp_query;
if( isset($wp_query->post) ){
$id = $wp_query->post->ID;
$post_title = $wp_query->post->post_title;
// etc
$return = $post_title;
}
// Or just outright change the title
$return = 'test';
return $return;
}
add_filter('wp_title', 'custom_page_title', 20);
```
Another thing to note here is that if you're using Yoast, you have to make sure that this function runs after Yoast modifies the title, otherwise Yoast will overwrite whatever changes you make. This is where the `20` comes in, as the third parameter in `add_filter()`. I think Yoast runs its filter at 15, so running yours at 20 (or any number higher than 15) will make sure your filter runs after Yoast's filter. |
278,701 | <p>this is my jscript</p>
<pre><code> <script>
jQuery(document).ready(function($){
$("button").on('click', function(event) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: $("#button").offset().top
}, 1000);
});
});
</script>
</code></pre>
<p>this is my custom button </p>
<pre><code> <button name="button" style="margin: 9px 0 20px 0;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" >HAVE A QUESTIONS</button>
</code></pre>
<p>and this is scroll bottom location (to scroll top button to this location)</p>
<pre><code><!-- Have Question -->
<div class="content-teaser container text-center">
<h3 class="text-red center-block text-center" id="button" >Have Questions?</h3>
<p>Talk with someone on the team We're here
to answer question</p>
</code></pre>
<p>all is work well but console put this error</p>
<p>TypeError: $(...).offset(...) is undefined</p>
<p>what is this error i can't understand plz solved this error because this error conflict to other script and my page doesn't work</p>
| [
{
"answer_id": 278724,
"author": "James",
"author_id": 34484,
"author_profile": "https://wordpress.stackexchange.com/users/34484",
"pm_score": 1,
"selected": false,
"text": "<p>Just to make sure, does the title tag in your <code><head></code> area (presumably in header.php) look li... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278701",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124829/"
] | this is my jscript
```
<script>
jQuery(document).ready(function($){
$("button").on('click', function(event) {
event.preventDefault();
$('html, body').stop().animate({
scrollTop: $("#button").offset().top
}, 1000);
});
});
</script>
```
this is my custom button
```
<button name="button" style="margin: 9px 0 20px 0;padding: 3px 25px; background-color: red;color: white;font-weight: bold;" value="OK" type="button" >HAVE A QUESTIONS</button>
```
and this is scroll bottom location (to scroll top button to this location)
```
<!-- Have Question -->
<div class="content-teaser container text-center">
<h3 class="text-red center-block text-center" id="button" >Have Questions?</h3>
<p>Talk with someone on the team We're here
to answer question</p>
```
all is work well but console put this error
TypeError: $(...).offset(...) is undefined
what is this error i can't understand plz solved this error because this error conflict to other script and my page doesn't work | Just to make sure, does the title tag in your `<head>` area (presumably in header.php) look like this?
```
<title><?php wp_title(); ?></title>
```
It has to be like that for Yoast to work with it, and be able to override titles.
Anyway if you add this to your single.php (or at least before `get_header()` is run for that page) you should be able to modify the page title:
```
function custom_page_title( $title ){
$return = $title;
// You can check what the current post is via $wp_query->post
global $wp_query;
if( isset($wp_query->post) ){
$id = $wp_query->post->ID;
$post_title = $wp_query->post->post_title;
// etc
$return = $post_title;
}
// Or just outright change the title
$return = 'test';
return $return;
}
add_filter('wp_title', 'custom_page_title', 20);
```
Another thing to note here is that if you're using Yoast, you have to make sure that this function runs after Yoast modifies the title, otherwise Yoast will overwrite whatever changes you make. This is where the `20` comes in, as the third parameter in `add_filter()`. I think Yoast runs its filter at 15, so running yours at 20 (or any number higher than 15) will make sure your filter runs after Yoast's filter. |
278,706 | <p>I wanted to set value of <strong>WP option</strong> (more specifically - 'admin_email') by using plugin, <strong>its option</strong> (plugin option) and update_option().</p>
<p>I tried using lines like below, but when plugin code contains them - it gets disabled. Any ideas why?</p>
<pre><code>$helper = (get_option('plugin-option');
update_option('admin_email', $helper );
</code></pre>
<p><strong>EDIT</strong> </p>
<pre><code>$helper = get_option('plugin-option');
update_option('admin_email', $helper );
</code></pre>
<p>Now it's not disabling (due to bracket), but it still doesn't change option value</p>
| [
{
"answer_id": 278707,
"author": "Jacob Peattie",
"author_id": 39152,
"author_profile": "https://wordpress.stackexchange.com/users/39152",
"pm_score": -1,
"selected": false,
"text": "<p>You've got an extra bracket:</p>\n\n<pre><code>$helper = (get_option('plugin-option');\n</code></pre>\... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278706",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126863/"
] | I wanted to set value of **WP option** (more specifically - 'admin\_email') by using plugin, **its option** (plugin option) and update\_option().
I tried using lines like below, but when plugin code contains them - it gets disabled. Any ideas why?
```
$helper = (get_option('plugin-option');
update_option('admin_email', $helper );
```
**EDIT**
```
$helper = get_option('plugin-option');
update_option('admin_email', $helper );
```
Now it's not disabling (due to bracket), but it still doesn't change option value | That option is special in that WordPress has code to intercept your call for security reasons:
<https://codex.wordpress.org/Function_Reference/update_option_new_admin_email>
>
> This function intercepts changes to the administrator's email address. It keeps the address from being updated and instead sends the user a confirmation email, with a link to confirm the change.
>
>
>
What you're trying to do could be easily abused, and any change of the administrators email should trigger notices as a basic security measure.
Luckily the documentation for that function also includes an example on how to bypass it |
278,714 | <p>I add my custom fields in genearal settings page. One of them using Wordpress Editor - there i insert my HTML content. I creeated it using simple snippet: </p>
<pre><code>add_action( 'admin_init', 'register_settings_wpse_57647' );
function register_settings_wpse_57647()
{
register_setting(
'general',
'opisproduktyseop',
'esc_html'
);
add_settings_section(
'site-guide',
'Publishing Guidelines',
'__return_false',
'general'
);
add_settings_field(
'opisproduktyseop',
'Enter custom message',
'print_text_editor_wpse_57647',
'general',
'site-guide'
);
}
function print_text_editor_wpse_57647()
{
$the_guides = html_entity_decode( get_option( 'opisproduktyseop' ) );
echo wp_editor(
$the_guides,
'sitepublishingguidelines',
array( 'textarea_name' => 'opisproduktyseop' )
);
}
</code></pre>
<p><a href="https://i.stack.imgur.com/L1xfq.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/L1xfq.png" alt="enter image description here"></a></p>
<p>The problem starts when i try display content from this field in my theme. HTML don't works: </p>
<p><a href="https://i.stack.imgur.com/nsjzu.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nsjzu.png" alt="enter image description here"></a></p>
<p>I display it using: </p>
<pre><code>echo get_option( 'produktyseoopis' );
</code></pre>
| [
{
"answer_id": 278715,
"author": "Patryk Patryk",
"author_id": 120726,
"author_profile": "https://wordpress.stackexchange.com/users/120726",
"pm_score": -1,
"selected": false,
"text": "<p>Ok. i was solved it right now! When i display it i put it wit html_entity_decode()</p>\n\n<pre><code... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278714",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/120726/"
] | I add my custom fields in genearal settings page. One of them using Wordpress Editor - there i insert my HTML content. I creeated it using simple snippet:
```
add_action( 'admin_init', 'register_settings_wpse_57647' );
function register_settings_wpse_57647()
{
register_setting(
'general',
'opisproduktyseop',
'esc_html'
);
add_settings_section(
'site-guide',
'Publishing Guidelines',
'__return_false',
'general'
);
add_settings_field(
'opisproduktyseop',
'Enter custom message',
'print_text_editor_wpse_57647',
'general',
'site-guide'
);
}
function print_text_editor_wpse_57647()
{
$the_guides = html_entity_decode( get_option( 'opisproduktyseop' ) );
echo wp_editor(
$the_guides,
'sitepublishingguidelines',
array( 'textarea_name' => 'opisproduktyseop' )
);
}
```
[](https://i.stack.imgur.com/L1xfq.png)
The problem starts when i try display content from this field in my theme. HTML don't works:
[](https://i.stack.imgur.com/nsjzu.png)
I display it using:
```
echo get_option( 'produktyseoopis' );
``` | It's because you're using `esc_html` to sanitize the setting, which converts all the `<`,`>` etc. into HTML entities, like `>`, which *render* as `<` but aren't treated as those characters in terms of HTML, which is why tags aren't rendering correctly. `esc_html` is supposed to be use for outputting HTML so that the markup is visible to the reader.
If you want to sanitize HTML, use `wp_kses_post` as the sanitization callback.
EDIT: Suggest `wp_kses_post`, rather than `wp_kses`, as per Tom's comment. |
278,754 | <p>I wrote some custom code which I've stuck into the media upload panel using a filter. It does a couple of things. First, it changes the text for the "submit" button for users who add things through the uploader. Second, it makes it so that the contents of the File URL field automatically enters the image upload input for a form I created when an image for it is uploaded through the media uploader. (that's the JQuery). Finally, there's CSS to hide elements of the media uploader that users don't need to see.</p>
<p>When this function is in the functions.php file, it causes the media library to stall in loading up the images. It just hangs on the spinning grey ball. But it also works.</p>
<p>How can I integrate this code into the site in a way that doesn't keep the media uploader from working?</p>
<pre><code>add_filter('attachment_fields_to_edit', 'my_plugin_action_button', 20, 2);
function my_plugin_action_button($form_fields, $post) {
$send = "<input type='submit' class='button' name='send[$post->ID]' value='" . esc_attr__( 'Use Photo' ) . "' />";
$form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send</td></tr>\n");
?>
<script>
jQuery('.savesend input[type=submit]').click(function(){
var url = jQuery(this).parents('.describe').find('.urlfile').data('link-url');
var field = jQuery(this).parents('.describe').find('.urlfield');
field.val(url);
});
</script>
<style>
#media-head-125, #imgedit-response-125, .savebutton.ml-submit, .image-size, .align, .post_content, .post_excerpt, .image_alt, .post_title.form-required, .media-types.media-types-required-info, .url {
display: none !important;
}
</style>
<?php
return $form_fields;
}
</code></pre>
| [
{
"answer_id": 278725,
"author": "Abhilash Narayan",
"author_id": 123210,
"author_profile": "https://wordpress.stackexchange.com/users/123210",
"pm_score": -1,
"selected": false,
"text": "<p>I fixed this by changing the permission of uploads folder to 745 and its working.</p>\n"
},
{... | 2017/08/31 | [
"https://wordpress.stackexchange.com/questions/278754",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114210/"
] | I wrote some custom code which I've stuck into the media upload panel using a filter. It does a couple of things. First, it changes the text for the "submit" button for users who add things through the uploader. Second, it makes it so that the contents of the File URL field automatically enters the image upload input for a form I created when an image for it is uploaded through the media uploader. (that's the JQuery). Finally, there's CSS to hide elements of the media uploader that users don't need to see.
When this function is in the functions.php file, it causes the media library to stall in loading up the images. It just hangs on the spinning grey ball. But it also works.
How can I integrate this code into the site in a way that doesn't keep the media uploader from working?
```
add_filter('attachment_fields_to_edit', 'my_plugin_action_button', 20, 2);
function my_plugin_action_button($form_fields, $post) {
$send = "<input type='submit' class='button' name='send[$post->ID]' value='" . esc_attr__( 'Use Photo' ) . "' />";
$form_fields['buttons'] = array('tr' => "\t\t<tr class='submit'><td></td><td class='savesend'>$send</td></tr>\n");
?>
<script>
jQuery('.savesend input[type=submit]').click(function(){
var url = jQuery(this).parents('.describe').find('.urlfile').data('link-url');
var field = jQuery(this).parents('.describe').find('.urlfield');
field.val(url);
});
</script>
<style>
#media-head-125, #imgedit-response-125, .savebutton.ml-submit, .image-size, .align, .post_content, .post_excerpt, .image_alt, .post_title.form-required, .media-types.media-types-required-info, .url {
display: none !important;
}
</style>
<?php
return $form_fields;
}
``` | For the permission please read this
<https://codex.wordpress.org/Changing_File_Permissions>
>
> All directories should be 755 or 750.
>
>
> |
278,772 | <p>I do not have coding experience only what I've learned to be able to modify my WP themes. I am stuck on the following issue. I'd like to add text and a call to action button to the featured image on my static homepage. </p>
<p>I'm fine using the page title as the text but I need to be able to add the call to action button button below the text.</p>
<p>Is this achievable by simply adding code to my custom CSS and/or one of the php files? If yes, please let me know what code I could use. </p>
<p>Thank you in advance for any assistance or feedback.</p>
| [
{
"answer_id": 278784,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 1,
"selected": false,
"text": "<p>If your theme allow you to edit the text displayed on your home page, when you just need to add a a link.<... | 2017/09/01 | [
"https://wordpress.stackexchange.com/questions/278772",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/126986/"
] | I do not have coding experience only what I've learned to be able to modify my WP themes. I am stuck on the following issue. I'd like to add text and a call to action button to the featured image on my static homepage.
I'm fine using the page title as the text but I need to be able to add the call to action button button below the text.
Is this achievable by simply adding code to my custom CSS and/or one of the php files? If yes, please let me know what code I could use.
Thank you in advance for any assistance or feedback. | If your theme allow you to edit the text displayed on your home page, when you just need to add a a link.
A click to call link is a simple HTML link, except that the value of the `href` attribute needs to refer to the "tel" protocol:
```
<a href="tel:XXXXXXXXXXXXX">Call Us</a>
```
Where "XXXXXXXXXXXXX" is your phone number.
If you only use the graphic interface, simply write "Call Us", highlight it and click on the button to add a link, and put "tel:XXXXXXXXXX" as the url. |
278,780 | <p>I have a custom post type functionality defined on my website for a certain action. In order to achieve a specific type of url structure. I removed the constant slug from it and replaced it with category and brand name. </p>
<p>The previous url was</p>
<p>www.website.com/product/name</p>
<p>The new url is</p>
<p>www.website.com/category/brand/name</p>
<p>You see, I have totally removed the slug. Here is the code for that. Now the issue is that these urls are not working and I am geting a 404 page in return. I have tried flushing the permailinks as well but it is not helping. </p>
<p>According to my understanding because of removing the slug, the query is searching in 'Post' not the 'Custom Post Type' but I don't know how to correct it. You response will be highly appreciated.</p>
<pre><code>// Register our Custom Post type as aps-products
public static function register_cpt_aps_products() {
$permalinks = get_aps_settings('permalinks');
$slug = (isset($permalinks['product-slug'])) ? $permalinks['product-slug'] : '';
// labels text for our post type aps-products
$labels = array(
// post type general name
'name' => __( 'APS Products', 'aps-text' ),
// post type singular name
'singular_name' => __( 'APS Product', 'aps-text' ),
'name_admin_bar' => __( 'APS Product', 'aps-text' ),
'menu_name' => __( 'APS Products', 'aps-text' ),
'add_new' => __( 'Add New APS Product', 'aps-text' ),
'add_new_item' => __( 'Add New APS Product', 'aps-text' ),
'edit_item' => __( 'Edit APS Product', 'aps-text' ),
'new_item' => __( 'New APS Product', 'aps-text' ),
'view_item' => __( 'View APS Product', 'aps-text' ),
'archives' => __( 'APS Products Archives', 'aps-text' ),
'search_items' => __( 'Search APS Products', 'aps-text' ),
'insert_into_item' => __( 'Insert into APS Product', 'aps-text' ),
'featured_image' => __( 'APS Product Image', 'aps-text' ),
'set_featured_image' => __( 'Set APS Product Image', 'aps-text' ),
'remove_featured_image' => __( 'Remove APS Product Image', 'aps-text' ),
'use_featured_image' => __( 'Use as APS Product image', 'aps-text' ),
'not_found' => __( 'No APS Products found', 'aps-text' ),
'not_found_in_trash' => __( 'No APS Products found in Trash', 'aps-text' )
);
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'query_var' => true,
'publicly_queryable' => true,
'show_in_nav_menus' => false,
'menu_icon' => 'dashicons-products',
'capability_type' => 'aps-products',
'capabilities' => array(
'read_post' => 'read_aps_product',
'edit_post' => 'edit_aps_product',
'edit_posts' => 'edit_aps_products',
'delete_posts' => 'delete_aps_products',
'create_posts' => 'create_aps_products',
'publish_posts' => 'publish_aps_products',
'edit_published_posts' => 'edit_published_aps_products',
'delete_published_posts' => 'delete_published_aps_products',
'edit_others_posts' => 'edit_others_aps_products',
'delete_others_posts' => 'delete_others_aps_products',
'read_private_posts' => 'read_private_aps_products',
'edit_private_posts' => 'edit_private_aps_products',
'delete_private_posts' => 'delete_private_aps_products'
),
'map_meta_cap' => true,
'hierarchical' => true,
'taxonomies' => array('post_tag','aps-cats', 'aps-brands', 'aps-attributes', 'aps-filters', 'aps-rating-bars'),
'has_archive' => true,
'show_in_menu' => 'aps-products',
'supports' => array( 'publicize','title', 'editor', 'thumbnail', 'comments', 'author', 'excerpt' ),
'register_meta_box_cb' => array(__CLASS__, 'add_aps_products_metabox'),
'rewrite' => array('slug' => '/%aps-cats%/%aps-brands%/', 'with_front' => false)
);
</code></pre>
| [
{
"answer_id": 278784,
"author": "Dexter0015",
"author_id": 62134,
"author_profile": "https://wordpress.stackexchange.com/users/62134",
"pm_score": 1,
"selected": false,
"text": "<p>If your theme allow you to edit the text displayed on your home page, when you just need to add a a link.<... | 2017/09/01 | [
"https://wordpress.stackexchange.com/questions/278780",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/24020/"
] | I have a custom post type functionality defined on my website for a certain action. In order to achieve a specific type of url structure. I removed the constant slug from it and replaced it with category and brand name.
The previous url was
www.website.com/product/name
The new url is
www.website.com/category/brand/name
You see, I have totally removed the slug. Here is the code for that. Now the issue is that these urls are not working and I am geting a 404 page in return. I have tried flushing the permailinks as well but it is not helping.
According to my understanding because of removing the slug, the query is searching in 'Post' not the 'Custom Post Type' but I don't know how to correct it. You response will be highly appreciated.
```
// Register our Custom Post type as aps-products
public static function register_cpt_aps_products() {
$permalinks = get_aps_settings('permalinks');
$slug = (isset($permalinks['product-slug'])) ? $permalinks['product-slug'] : '';
// labels text for our post type aps-products
$labels = array(
// post type general name
'name' => __( 'APS Products', 'aps-text' ),
// post type singular name
'singular_name' => __( 'APS Product', 'aps-text' ),
'name_admin_bar' => __( 'APS Product', 'aps-text' ),
'menu_name' => __( 'APS Products', 'aps-text' ),
'add_new' => __( 'Add New APS Product', 'aps-text' ),
'add_new_item' => __( 'Add New APS Product', 'aps-text' ),
'edit_item' => __( 'Edit APS Product', 'aps-text' ),
'new_item' => __( 'New APS Product', 'aps-text' ),
'view_item' => __( 'View APS Product', 'aps-text' ),
'archives' => __( 'APS Products Archives', 'aps-text' ),
'search_items' => __( 'Search APS Products', 'aps-text' ),
'insert_into_item' => __( 'Insert into APS Product', 'aps-text' ),
'featured_image' => __( 'APS Product Image', 'aps-text' ),
'set_featured_image' => __( 'Set APS Product Image', 'aps-text' ),
'remove_featured_image' => __( 'Remove APS Product Image', 'aps-text' ),
'use_featured_image' => __( 'Use as APS Product image', 'aps-text' ),
'not_found' => __( 'No APS Products found', 'aps-text' ),
'not_found_in_trash' => __( 'No APS Products found in Trash', 'aps-text' )
);
$args = array(
'labels' => $labels,
'public' => true,
'show_ui' => true,
'query_var' => true,
'publicly_queryable' => true,
'show_in_nav_menus' => false,
'menu_icon' => 'dashicons-products',
'capability_type' => 'aps-products',
'capabilities' => array(
'read_post' => 'read_aps_product',
'edit_post' => 'edit_aps_product',
'edit_posts' => 'edit_aps_products',
'delete_posts' => 'delete_aps_products',
'create_posts' => 'create_aps_products',
'publish_posts' => 'publish_aps_products',
'edit_published_posts' => 'edit_published_aps_products',
'delete_published_posts' => 'delete_published_aps_products',
'edit_others_posts' => 'edit_others_aps_products',
'delete_others_posts' => 'delete_others_aps_products',
'read_private_posts' => 'read_private_aps_products',
'edit_private_posts' => 'edit_private_aps_products',
'delete_private_posts' => 'delete_private_aps_products'
),
'map_meta_cap' => true,
'hierarchical' => true,
'taxonomies' => array('post_tag','aps-cats', 'aps-brands', 'aps-attributes', 'aps-filters', 'aps-rating-bars'),
'has_archive' => true,
'show_in_menu' => 'aps-products',
'supports' => array( 'publicize','title', 'editor', 'thumbnail', 'comments', 'author', 'excerpt' ),
'register_meta_box_cb' => array(__CLASS__, 'add_aps_products_metabox'),
'rewrite' => array('slug' => '/%aps-cats%/%aps-brands%/', 'with_front' => false)
);
``` | If your theme allow you to edit the text displayed on your home page, when you just need to add a a link.
A click to call link is a simple HTML link, except that the value of the `href` attribute needs to refer to the "tel" protocol:
```
<a href="tel:XXXXXXXXXXXXX">Call Us</a>
```
Where "XXXXXXXXXXXXX" is your phone number.
If you only use the graphic interface, simply write "Call Us", highlight it and click on the button to add a link, and put "tel:XXXXXXXXXX" as the url. |
278,813 | <p>i have in all of my posts an additional custom field (acf user field) in case the post has a co-author. </p>
<p>All users have their own author-page where all their posts are displayed. No problem so far.</p>
<p>But what i now want is a query where i get all posts where the author is the actual author and all posts where he/she is just the co-author in the custom field.</p>
<p>My code is pretty simple so far, but did not actually work. I guess the 'relation' parameter is only for comparing meta query-subarrays.</p>
<pre><code>$args = array(
'post_type' => array( 'post' ),
'posts_per_page' => 20,
'relation' => 'OR',
array(
'author' => $author_ID,
),
array(
'meta_key' => 'authorfeld',
'meta_value' => $showme[ID], // This is the authors id from the custom field
)
);
</code></pre>
<p>Thank you</p>
| [
{
"answer_id": 278842,
"author": "James",
"author_id": 34484,
"author_profile": "https://wordpress.stackexchange.com/users/34484",
"pm_score": 0,
"selected": false,
"text": "<p>Real quick, are you sure you spelled the name of the meta_key correctly? It says \"authorfeld\" in your example... | 2017/09/01 | [
"https://wordpress.stackexchange.com/questions/278813",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/92874/"
] | i have in all of my posts an additional custom field (acf user field) in case the post has a co-author.
All users have their own author-page where all their posts are displayed. No problem so far.
But what i now want is a query where i get all posts where the author is the actual author and all posts where he/she is just the co-author in the custom field.
My code is pretty simple so far, but did not actually work. I guess the 'relation' parameter is only for comparing meta query-subarrays.
```
$args = array(
'post_type' => array( 'post' ),
'posts_per_page' => 20,
'relation' => 'OR',
array(
'author' => $author_ID,
),
array(
'meta_key' => 'authorfeld',
'meta_value' => $showme[ID], // This is the authors id from the custom field
)
);
```
Thank you | I found some hints here: [Can i merge 2 new WP\_Query($variable) 's?](https://wordpress.stackexchange.com/questions/55519/can-i-merge-2-new-wp-queryvariable-s)
So i created two separate queries and merged them into a new array:
```
$wp_query = new WP_Query();
$wp_query->posts = array_merge( $query1->posts, $query2->posts );
foreach($wp_query->posts as $post) :
setup_postdata( $post );
```
And then the usual stuff. |
278,882 | <p>How can I get the email adress from the users by using the REST API?
I'm authenticating with nonce, and it seems to be working since I can do POST requests and change stuff. Do I have to add something to make it return all the user info?</p>
<p>This is my JS:</p>
<pre><code>(function($) {
var nonce = WPsettings.nonce;
var rest_url = WPsettings.rest_url;
$.ajax( {
url: rest_url + 'users/',
dataType: "json",
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', nonce );
}
} )
.done( function ( response ) {
console.log( response );
} );
})(jQuery);
</code></pre>
| [
{
"answer_id": 278883,
"author": "Mostafa Soufi",
"author_id": 106877,
"author_profile": "https://wordpress.stackexchange.com/users/106877",
"pm_score": 4,
"selected": true,
"text": "<p>To add the user's email address in the REST API response, register an additional field to the <code>us... | 2017/09/02 | [
"https://wordpress.stackexchange.com/questions/278882",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5079/"
] | How can I get the email adress from the users by using the REST API?
I'm authenticating with nonce, and it seems to be working since I can do POST requests and change stuff. Do I have to add something to make it return all the user info?
This is my JS:
```
(function($) {
var nonce = WPsettings.nonce;
var rest_url = WPsettings.rest_url;
$.ajax( {
url: rest_url + 'users/',
dataType: "json",
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', nonce );
}
} )
.done( function ( response ) {
console.log( response );
} );
})(jQuery);
``` | To add the user's email address in the REST API response, register an additional field to the `user` object and add the email address:
```
register_rest_field(
'user',
'user_email',
[
'get_callback' => static function (array $user): string {
return get_userdata($user['id'])->user_email;
},
]
);
```
Please note, however, that this is *strongly* discouraged because anyone can then see the email addresses if the code is running on a publicly accessible website. |
278,954 | <p>I'm currently trying to download a blob archive file saved in the database</p>
<pre><code>$fid = $_GET['fid'];
$sel = $wpdb->get_results( "SELECT * FROM uploads WHERE id = $fid" );
foreach( $sel as $head )
{
$name = $head->name;
$type = $head->type;
$size = $head->size;
$content = $head->content;
header("Content-length: $size");
header("Content-type: $type");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
</code></pre>
<p>every time I redirect to <code>/download?id=</code> with int value assigned to <code>id</code> it loads the file. However, instead of the browser prompting for file download location, the page reads the binary contents of the blob and displays it all as a string.</p>
<p>any other way of downloading a blob on wordpress?</p>
| [
{
"answer_id": 278993,
"author": "Sebastian Kurzynowski",
"author_id": 108925,
"author_profile": "https://wordpress.stackexchange.com/users/108925",
"pm_score": 2,
"selected": false,
"text": "<p>There are some security issues. \nPlease sanitize your input because someone can download fro... | 2017/09/03 | [
"https://wordpress.stackexchange.com/questions/278954",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127113/"
] | I'm currently trying to download a blob archive file saved in the database
```
$fid = $_GET['fid'];
$sel = $wpdb->get_results( "SELECT * FROM uploads WHERE id = $fid" );
foreach( $sel as $head )
{
$name = $head->name;
$type = $head->type;
$size = $head->size;
$content = $head->content;
header("Content-length: $size");
header("Content-type: $type");
header("Content-Transfer-Encoding: Binary");
header("Content-Disposition: attachment; filename=$name");
echo $content;
exit;
}
```
every time I redirect to `/download?id=` with int value assigned to `id` it loads the file. However, instead of the browser prompting for file download location, the page reads the binary contents of the blob and displays it all as a string.
any other way of downloading a blob on wordpress? | There are some security issues.
Please sanitize your input because someone can download from Your database something different than archive, or simply drop Your database.
`$fid = sanitize_text_field( $_GET['fid'] );` |
278,986 | <p>I am trying to get the updated value of a piece of meta when a post is saved (custom post type) but when I try to grab the updated data on the save_post hook, I get the previous data instead. I tried a separate function with a higher priority, but no luck that way either (below)</p>
<p>How do I get the updated meta value right after I save the post?</p>
<p>Code:</p>
<pre><code>add_action('save_post_space', 'tps_save_space_slots', 20, 3);
function tps_save_space_slots($post_id, $post, $updated) {
//Don't fire on auto-drafts
if (isset($post->post_status) && 'auto-draft' == $post->post_status) {
return;
}
//The new slots being saved
$allSlots = tps_generate_space_slots($post_id);
//Update the meta
$updateSlots = update_post_meta($post_id, 'allSlots', $allSlots);
}
add_action( 'save_post_space', 'tps_initiate_resend', 30, 3 );
function tps_initiate_resend($post_id, $post, $updated) {
tps_resend_code_after_change($post_id);//<----this sends the new meta value in an email, but it's the OLD value
}
</code></pre>
| [
{
"answer_id": 278988,
"author": "Eckstein",
"author_id": 23492,
"author_profile": "https://wordpress.stackexchange.com/users/23492",
"pm_score": 3,
"selected": true,
"text": "<p>Apparently in order to get the meta value right after saving the post, you have to either get the $_REQUEST['... | 2017/09/04 | [
"https://wordpress.stackexchange.com/questions/278986",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/23492/"
] | I am trying to get the updated value of a piece of meta when a post is saved (custom post type) but when I try to grab the updated data on the save\_post hook, I get the previous data instead. I tried a separate function with a higher priority, but no luck that way either (below)
How do I get the updated meta value right after I save the post?
Code:
```
add_action('save_post_space', 'tps_save_space_slots', 20, 3);
function tps_save_space_slots($post_id, $post, $updated) {
//Don't fire on auto-drafts
if (isset($post->post_status) && 'auto-draft' == $post->post_status) {
return;
}
//The new slots being saved
$allSlots = tps_generate_space_slots($post_id);
//Update the meta
$updateSlots = update_post_meta($post_id, 'allSlots', $allSlots);
}
add_action( 'save_post_space', 'tps_initiate_resend', 30, 3 );
function tps_initiate_resend($post_id, $post, $updated) {
tps_resend_code_after_change($post_id);//<----this sends the new meta value in an email, but it's the OLD value
}
``` | Apparently in order to get the meta value right after saving the post, you have to either get the $\_REQUEST['my\_meta\_value'] directly, or, if you need to update the database right away, you have to use update\_post\_meta() in your save\_post action. |
279,035 | <p>I am new to woo-commerce, can anyone please let me know where the cart items are stored in Database. which tables have cart details?</p>
| [
{
"answer_id": 279036,
"author": "DHL17",
"author_id": 125227,
"author_profile": "https://wordpress.stackexchange.com/users/125227",
"pm_score": 2,
"selected": false,
"text": "<p>Various information about cart are stored by woocmmerce by two ways:</p>\n\n<ol>\n<li>In $woocommerce object(... | 2017/09/04 | [
"https://wordpress.stackexchange.com/questions/279035",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127183/"
] | I am new to woo-commerce, can anyone please let me know where the cart items are stored in Database. which tables have cart details? | Various information about cart are stored by woocmmerce by two ways:
1. In $woocommerce object( About session , cart info, subtotal etc)
2. In database table named persistent\_cart which is dynamic ... it will get destroyed as soon as checkout is done.
So , now how to access all this info ...
For the 1st kind just declare global $woocommerce object and use below code to see all details
```
global $woocommerce;
echo "<pre>";
print_r($woocommerce);
exit;
```
For the 2nd kind you have to fetch data from table.. therefore first declare $wpdb wordpress object and write sql query to get result
one thing to note here is... data is stored in serialize manner in `woocommerce_persistent_cart` table so you have to unserialize it before using it
only then you can use it. Below is code to get cart information from table
```
global $wpdb;
$array = $wpdb->get_results("select meta_value from ".$wpdb->prefix."usermeta where meta_key='_woocommerce_persistent_cart'");
//print_r($array);
$data =$array[0]->meta_value;
$de=unserialize($data);
``` |
279,204 | <p>The stock statuses from my woocommerce installation were uploaded by another plugin (square) and so all goods are in stock even if they have quantity 0. Is there a way to get the statuses to reset somehow, so that products with 0 stock, have the stock status "out of stock". </p>
<p>I have looked for this and found the following <a href="https://gist.github.com/codearachnid/5943589" rel="nofollow noreferrer">function</a></p>
<pre><code>function jolie_theme_child_reset_stock_status(){
global $wpdb;
// set all status for products with 0 or less stocked quantity
$sql = "UPDATE $wpdb->postmeta stock, (SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock' AND meta_value < 1 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';";
// set all status for products with stock.
$sql .= "UPDATE $wpdb->postmeta stock, (SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock' AND meta_value > 0 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';";
// run queries
$wpdb->query( $sql );
}
</code></pre>
<p>But if I run this it causes a server 500 error. What is a simple way to reset the stock statuses with or without using the above code?</p>
| [
{
"answer_id": 279212,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 1,
"selected": false,
"text": "<p>You can add the following sql command in your database using PHP my admin or anyother DB editor</p>\n\n<... | 2017/09/06 | [
"https://wordpress.stackexchange.com/questions/279204",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127261/"
] | The stock statuses from my woocommerce installation were uploaded by another plugin (square) and so all goods are in stock even if they have quantity 0. Is there a way to get the statuses to reset somehow, so that products with 0 stock, have the stock status "out of stock".
I have looked for this and found the following [function](https://gist.github.com/codearachnid/5943589)
```
function jolie_theme_child_reset_stock_status(){
global $wpdb;
// set all status for products with 0 or less stocked quantity
$sql = "UPDATE $wpdb->postmeta stock, (SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock' AND meta_value < 1 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';";
// set all status for products with stock.
$sql .= "UPDATE $wpdb->postmeta stock, (SELECT DISTINCT post_id FROM $wpdb->postmeta WHERE meta_key = '_stock' AND meta_value > 0 ) id SET stock.meta_value = 'outofstock' WHERE stock.post_id = id.post_id AND stock.meta_key = '_stock_status';";
// run queries
$wpdb->query( $sql );
}
```
But if I run this it causes a server 500 error. What is a simple way to reset the stock statuses with or without using the above code? | You can add the following sql command in your database using PHP my admin or anyother DB editor
```
Update wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status'
``` |
279,215 | <p>I've created a custom field and selected "Filter by role" to "Subscriber" and assigned the custom field to the post type. Now when I add a new post and assigned the subscriber (ie: created a Test Post and assigned the subscriber to "grade 1") after I click on the update again I changed the subscriber "grade 1" to "grade 2", after that when I viewed the page by login as grade 1 that particular post is viewed. This Happens only if I edit the post and change the subscriber again. </p>
<pre><code>$args_events = array(
'post_type' => 'parents_login',
'post_status' => 'publish',
'paged' => $page_num,
'posts_per_page' => CUSTOM_ROWS_PER_PAGE,
'cat' => get_cat_id( single_cat_title("",false) ),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'select_grade',
'value' => $current_user->ID,
'compare' => 'LIKE',
),
),
);
</code></pre>
| [
{
"answer_id": 279212,
"author": "Pratik bhatt",
"author_id": 60922,
"author_profile": "https://wordpress.stackexchange.com/users/60922",
"pm_score": 1,
"selected": false,
"text": "<p>You can add the following sql command in your database using PHP my admin or anyother DB editor</p>\n\n<... | 2017/09/06 | [
"https://wordpress.stackexchange.com/questions/279215",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80578/"
] | I've created a custom field and selected "Filter by role" to "Subscriber" and assigned the custom field to the post type. Now when I add a new post and assigned the subscriber (ie: created a Test Post and assigned the subscriber to "grade 1") after I click on the update again I changed the subscriber "grade 1" to "grade 2", after that when I viewed the page by login as grade 1 that particular post is viewed. This Happens only if I edit the post and change the subscriber again.
```
$args_events = array(
'post_type' => 'parents_login',
'post_status' => 'publish',
'paged' => $page_num,
'posts_per_page' => CUSTOM_ROWS_PER_PAGE,
'cat' => get_cat_id( single_cat_title("",false) ),
'meta_query' => array(
'relation' => 'OR',
array(
'key' => 'select_grade',
'value' => $current_user->ID,
'compare' => 'LIKE',
),
),
);
``` | You can add the following sql command in your database using PHP my admin or anyother DB editor
```
Update wp_postmeta Set meta_value = 'instock' Where meta_value = 'outofstock' And meta_key = '_stock_status'
``` |
279,230 | <p>I am trying to understand how <code>add_theme_support()</code> function works, but at the section of Html5 i tried to use it with gallery and i noticed that the markup has changed for it,and here is what i did</p>
<pre><code>add_theme_support( 'html5', array('gallery') );
</code></pre>
<p>but for the others like search-form or comment-form for example</p>
<pre><code>add_theme_support( 'html5', array( 'comment-form','search-form','gallery', 'caption' ) );
</code></pre>
<p>i didn't notice any change in the output, so Am i missing some thing? or how it works?</p>
| [
{
"answer_id": 279232,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 2,
"selected": false,
"text": "<p>According to the documentation, you must pass an array of items where you want to enable HTML5 markup:</p>\n\n<... | 2017/09/06 | [
"https://wordpress.stackexchange.com/questions/279230",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/102224/"
] | I am trying to understand how `add_theme_support()` function works, but at the section of Html5 i tried to use it with gallery and i noticed that the markup has changed for it,and here is what i did
```
add_theme_support( 'html5', array('gallery') );
```
but for the others like search-form or comment-form for example
```
add_theme_support( 'html5', array( 'comment-form','search-form','gallery', 'caption' ) );
```
i didn't notice any change in the output, so Am i missing some thing? or how it works? | I have figured out why no changes happens, and the problem was that i am calling a custom search form file `searchform.php` and the function `add_theme_support()` affects the built in features only. So if you want to use the default search form by calling `get_search_form()` without having the `searchform.php` file, then you can use
```
add_theme_support( 'html5', array( 'search-form' ) );
```
and this will apply an html5 markup to the form. The following are the before and after `add_theme_support()`(Contains Arabic Text):
Before:
```
<form role="search" method="get" id="searchform" class="searchform" action="http://localhost/TB/">
<div>
<label class="screen-reader-text" for="s">البحث عن:</label>
<input value="" name="s" id="s" type="text">
<input id="searchsubmit" value="بحث" type="submit">
</div>
</form>
```
After:
```
<form role="search" method="get" class="search-form" action="http://localhost/TB/">
<label>
<span class="screen-reader-text">البحث عن:</span>
<input class="search-field" placeholder="بحث …" value="" name="s" type="search">
</label>
<input class="search-submit" value="بحث" type="submit">
</form>
``` |
279,247 | <p>I am using twenty seventeen theme. The theme allows to have different sections on homepage based on site pages. I was wondering how I can add make it so only logged out users see a certain page in one of the sections? Basically I have a new user registration page i want to have as one of my sections but I don't want logged in users to see that section, only logged out users. </p>
<p>My page is <a href="http://jonathanmusiclessons.com" rel="nofollow noreferrer">jonathanmusiclessons.com</a></p>
| [
{
"answer_id": 279255,
"author": "Rafael Cavalcante",
"author_id": 68359,
"author_profile": "https://wordpress.stackexchange.com/users/68359",
"pm_score": 0,
"selected": false,
"text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/referenc... | 2017/09/06 | [
"https://wordpress.stackexchange.com/questions/279247",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127363/"
] | I am using twenty seventeen theme. The theme allows to have different sections on homepage based on site pages. I was wondering how I can add make it so only logged out users see a certain page in one of the sections? Basically I have a new user registration page i want to have as one of my sections but I don't want logged in users to see that section, only logged out users.
My page is [jonathanmusiclessons.com](http://jonathanmusiclessons.com) | You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.
For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;
```
.logged_in .menu-class-here{display:none;}
```
That is to hide a menu item.
Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;
```
if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
```
If you want to allow access to the page but hide a certain section from logged in users, you can do something like;
```
if ( is_page('slug') && ! is_user_logged_in() ) {
//add the code here that you want to show to non-logged-in users
}
```
**UPDATE**
Add this to functions.php. You need to create a function to redirect and add it
```
function notallowed() {
global $post;
if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
}
add_action( 'template_redirect', 'notallowed' );
``` |
279,279 | <p>I'm a newby and don't have much knowledge of programming. My website is <a href="https://www.laraellisphotography.com" rel="nofollow noreferrer">https://www.laraellisphotography.com</a> I'm using the Divina theme and I can't figure out how to remove the search bar. I tried to see if it's a widget but it appears to be hardcoded into the theme. It shows up under the menu I put in. Can somebody explain to me in very specific terms how to fix this? I'm using a plugin called advanced code editor but I really don't know what I'm doing. I tried putting in a show: none phrase in around where I thought the programming was for the search in the css styles sheet but it didn't change anything. Thanks for any help you can give me. :)</p>
| [
{
"answer_id": 279255,
"author": "Rafael Cavalcante",
"author_id": 68359,
"author_profile": "https://wordpress.stackexchange.com/users/68359",
"pm_score": 0,
"selected": false,
"text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/referenc... | 2017/09/06 | [
"https://wordpress.stackexchange.com/questions/279279",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127381/"
] | I'm a newby and don't have much knowledge of programming. My website is <https://www.laraellisphotography.com> I'm using the Divina theme and I can't figure out how to remove the search bar. I tried to see if it's a widget but it appears to be hardcoded into the theme. It shows up under the menu I put in. Can somebody explain to me in very specific terms how to fix this? I'm using a plugin called advanced code editor but I really don't know what I'm doing. I tried putting in a show: none phrase in around where I thought the programming was for the search in the css styles sheet but it didn't change anything. Thanks for any help you can give me. :) | You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.
For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;
```
.logged_in .menu-class-here{display:none;}
```
That is to hide a menu item.
Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;
```
if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
```
If you want to allow access to the page but hide a certain section from logged in users, you can do something like;
```
if ( is_page('slug') && ! is_user_logged_in() ) {
//add the code here that you want to show to non-logged-in users
}
```
**UPDATE**
Add this to functions.php. You need to create a function to redirect and add it
```
function notallowed() {
global $post;
if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
}
add_action( 'template_redirect', 'notallowed' );
``` |
279,280 | <p>I have a few questions and I don't think the outcome I want is possible without adding a custom taxonomy and redoing a bunch of work.</p>
<p>I have registered a custom post type - gallery - with taxonomies set to post_tag and category.</p>
<p>I have the permalink structure set to /blog/%postname%/ so Posts can have the /blog/ base set using the default Posts section within WordPress.</p>
<p>When I use get_category_link() for a category on the gallery custom post type, it links to /blog/ceremonies/ instead of /gallery/ceremonies/ which is what I'd like for anything on the gallery archive or single gallery page. For the blog, it would need to be /blog/category_name/ as it currently is.</p>
<p>I know I can do the work from <a href="https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post">this question</a>, but I have a lot of work done already that I do not want to back track on. </p>
<p><strong>My questions:</strong></p>
<p>Is there a way have /blog/ceremonies/ and /gallery/ceremonies/ load the same categories, and I can filter them with what the /blog/ or /gallery/ is set to in the URL with $_SERVER['REQUEST_URI'] (or something similar) without creating a custom taxonomy?</p>
<p>If not (I don't think there is), is there a way I can strip out the /blog/ out of the custom permalink so it just shows /ceremonies/ and still have /blog/ at the beginning of anything posted in the "Posts" section?</p>
<p>Any help is appreciated. Thank you!</p>
| [
{
"answer_id": 279255,
"author": "Rafael Cavalcante",
"author_id": 68359,
"author_profile": "https://wordpress.stackexchange.com/users/68359",
"pm_score": 0,
"selected": false,
"text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/referenc... | 2017/09/06 | [
"https://wordpress.stackexchange.com/questions/279280",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127382/"
] | I have a few questions and I don't think the outcome I want is possible without adding a custom taxonomy and redoing a bunch of work.
I have registered a custom post type - gallery - with taxonomies set to post\_tag and category.
I have the permalink structure set to /blog/%postname%/ so Posts can have the /blog/ base set using the default Posts section within WordPress.
When I use get\_category\_link() for a category on the gallery custom post type, it links to /blog/ceremonies/ instead of /gallery/ceremonies/ which is what I'd like for anything on the gallery archive or single gallery page. For the blog, it would need to be /blog/category\_name/ as it currently is.
I know I can do the work from [this question](https://wordpress.stackexchange.com/questions/108642/permalinks-custom-post-type-custom-taxonomy-post), but I have a lot of work done already that I do not want to back track on.
**My questions:**
Is there a way have /blog/ceremonies/ and /gallery/ceremonies/ load the same categories, and I can filter them with what the /blog/ or /gallery/ is set to in the URL with $\_SERVER['REQUEST\_URI'] (or something similar) without creating a custom taxonomy?
If not (I don't think there is), is there a way I can strip out the /blog/ out of the custom permalink so it just shows /ceremonies/ and still have /blog/ at the beginning of anything posted in the "Posts" section?
Any help is appreciated. Thank you! | You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.
For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;
```
.logged_in .menu-class-here{display:none;}
```
That is to hide a menu item.
Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;
```
if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
```
If you want to allow access to the page but hide a certain section from logged in users, you can do something like;
```
if ( is_page('slug') && ! is_user_logged_in() ) {
//add the code here that you want to show to non-logged-in users
}
```
**UPDATE**
Add this to functions.php. You need to create a function to redirect and add it
```
function notallowed() {
global $post;
if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
}
add_action( 'template_redirect', 'notallowed' );
``` |
279,294 | <p>I created an image size:</p>
<pre><code>add_image_size('slider', 1920, 1080, true);
</code></pre>
<p>Now, i thought hard cropping meant that WordPress would zoom into the picture until it obtains that size and proportion no matter what. </p>
<p>Well, if User enters a vertical image, say 784x1200, What WordPress is doing is getting me an 784x1080 image, so it ignores the asked width because it matches height first?? </p>
| [
{
"answer_id": 279255,
"author": "Rafael Cavalcante",
"author_id": 68359,
"author_profile": "https://wordpress.stackexchange.com/users/68359",
"pm_score": 0,
"selected": false,
"text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/referenc... | 2017/09/07 | [
"https://wordpress.stackexchange.com/questions/279294",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/124731/"
] | I created an image size:
```
add_image_size('slider', 1920, 1080, true);
```
Now, i thought hard cropping meant that WordPress would zoom into the picture until it obtains that size and proportion no matter what.
Well, if User enters a vertical image, say 784x1200, What WordPress is doing is getting me an 784x1080 image, so it ignores the asked width because it matches height first?? | You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.
For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;
```
.logged_in .menu-class-here{display:none;}
```
That is to hide a menu item.
Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;
```
if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
```
If you want to allow access to the page but hide a certain section from logged in users, you can do something like;
```
if ( is_page('slug') && ! is_user_logged_in() ) {
//add the code here that you want to show to non-logged-in users
}
```
**UPDATE**
Add this to functions.php. You need to create a function to redirect and add it
```
function notallowed() {
global $post;
if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
}
add_action( 'template_redirect', 'notallowed' );
``` |
279,321 | <p>For my client site, I am planning to enable link post image to post a link on blog list page, the site uses custom WordPress theme developed by the previous developer.</p>
<p>For blog post list page he created as content.php and for the single post he created <code>content-page.php</code> </p>
<p>Even if I add the featured image I can't able to see that featured image, only the image inside of the post is showing.</p>
<p>How to achieve this? </p>
<p>Here is the code for content.php</p>
<pre><code><?php
/**
* Template part for displaying posts
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Blog
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php
if ( is_single() ) :
the_title( '<h1 class="entry-title">', '</h1>' );
else :
the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark" >', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) : ?>
<h4 class="meta text-muted">
<?php bfablog_posted_on(); ?>
</h4><!-- .entry-meta -->
<?php
endif; ?>
<!-- AddThis Button BEGIN -->
<div class="addthis_inline_share_toolbox_mzc3" style="margin-bottom:20px;" data-title="<?php the_title() ?>" data-url="<?php the_permalink(); ?>" </div>
<!-- AddThis Button END -->
</header><!-- .entry-header -->
<div class="entry-content">
<?php
the_content( sprintf (
/* translators: %s: Name of current post. */
wp_kses(__( 'Read more', 'bfablog' ), array( 'span' => array( 'class' =>
array() ) ) ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
wp_link_pages( array(
'before' => '<div class= "page-links">'. esc_html__('Pages:', 'bfablog'
),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php bfablog_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
<hr>
<script type="text/javascript">
var addthis_config = {
ui_language: "{{ site.lang }}"
};
var addthis_share =
{
// ... members go here
}
</script>
<!-- Go to www.addthis.com/dashboard to customize your tools -->
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-586c401922d76d24"></script>
</code></pre>
<p>Here is the code for content-page.php</p>
<pre><code><?php
/**
* Template part for displaying page content in page.php
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package BfA_Blog
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<div class="entry-content"><hr>
<?php
the_content();
wp_link_pages(array(
'before' => '<div class="page-links">' . esc_html__('Pages:','bfablog'),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<?php if ( get_edit_post_link() ) : ?>
<footer class="entry-footer">
<?php
edit_post_link(
sprintf(
/* translators: %s: Name of current post */
esc_html__( 'Edit %s', 'bfablog' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
),
'<span class="edit-link">',
'</span>'
);
?>
</footer><!-- .entry-footer -->
<?php endif; ?>
</article><!-- #post-## -->
</code></pre>
| [
{
"answer_id": 279255,
"author": "Rafael Cavalcante",
"author_id": 68359,
"author_profile": "https://wordpress.stackexchange.com/users/68359",
"pm_score": 0,
"selected": false,
"text": "<p>You can solve your problem by using the built-in <a href=\"https://developer.wordpress.org/referenc... | 2017/09/07 | [
"https://wordpress.stackexchange.com/questions/279321",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/127412/"
] | For my client site, I am planning to enable link post image to post a link on blog list page, the site uses custom WordPress theme developed by the previous developer.
For blog post list page he created as content.php and for the single post he created `content-page.php`
Even if I add the featured image I can't able to see that featured image, only the image inside of the post is showing.
How to achieve this?
Here is the code for content.php
```
<?php
/**
* Template part for displaying posts
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package Blog
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php
if ( is_single() ) :
the_title( '<h1 class="entry-title">', '</h1>' );
else :
the_title( '<h2 class="entry-title"><a href="' . esc_url( get_permalink() ) . '" rel="bookmark" >', '</a></h2>' );
endif;
if ( 'post' === get_post_type() ) : ?>
<h4 class="meta text-muted">
<?php bfablog_posted_on(); ?>
</h4><!-- .entry-meta -->
<?php
endif; ?>
<!-- AddThis Button BEGIN -->
<div class="addthis_inline_share_toolbox_mzc3" style="margin-bottom:20px;" data-title="<?php the_title() ?>" data-url="<?php the_permalink(); ?>" </div>
<!-- AddThis Button END -->
</header><!-- .entry-header -->
<div class="entry-content">
<?php
the_content( sprintf (
/* translators: %s: Name of current post. */
wp_kses(__( 'Read more', 'bfablog' ), array( 'span' => array( 'class' =>
array() ) ) ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
) );
wp_link_pages( array(
'before' => '<div class= "page-links">'. esc_html__('Pages:', 'bfablog'
),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<footer class="entry-footer">
<?php bfablog_entry_footer(); ?>
</footer><!-- .entry-footer -->
</article><!-- #post-## -->
<hr>
<script type="text/javascript">
var addthis_config = {
ui_language: "{{ site.lang }}"
};
var addthis_share =
{
// ... members go here
}
</script>
<!-- Go to www.addthis.com/dashboard to customize your tools -->
<script type="text/javascript" src="//s7.addthis.com/js/300/addthis_widget.js#pubid=ra-586c401922d76d24"></script>
```
Here is the code for content-page.php
```
<?php
/**
* Template part for displaying page content in page.php
*
* @link https://codex.wordpress.org/Template_Hierarchy
*
* @package BfA_Blog
*/
?>
<article id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
<header class="entry-header">
<?php the_title( '<h1 class="entry-title">', '</h1>' ); ?>
</header><!-- .entry-header -->
<div class="entry-content"><hr>
<?php
the_content();
wp_link_pages(array(
'before' => '<div class="page-links">' . esc_html__('Pages:','bfablog'),
'after' => '</div>',
) );
?>
</div><!-- .entry-content -->
<?php if ( get_edit_post_link() ) : ?>
<footer class="entry-footer">
<?php
edit_post_link(
sprintf(
/* translators: %s: Name of current post */
esc_html__( 'Edit %s', 'bfablog' ),
the_title( '<span class="screen-reader-text">"', '"</span>', false )
),
'<span class="edit-link">',
'</span>'
);
?>
</footer><!-- .entry-footer -->
<?php endif; ?>
</article><!-- #post-## -->
``` | You can do this by checking if the user is logged in as stated in the first answer. You simply need to do it the other way.
For example, if you have a link in the menu that should be hidden in case the user is logged in, just add a custom css;
```
.logged_in .menu-class-here{display:none;}
```
That is to hide a menu item.
Now, if you want to restrict the access to a page if the user is logged in, you can simply do a redirect. Here's an example;
```
if ( is_page('slug') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
```
If you want to allow access to the page but hide a certain section from logged in users, you can do something like;
```
if ( is_page('slug') && ! is_user_logged_in() ) {
//add the code here that you want to show to non-logged-in users
}
```
**UPDATE**
Add this to functions.php. You need to create a function to redirect and add it
```
function notallowed() {
global $post;
if ( is_page('hire-the-freelancer') && is_user_logged_in() ) { // where slug is the name or slug of the custom page that you want to restrict from logged in users
wp_redirect( 'http://www.example.com/desired-page/', 301 );
exit;
}
}
add_action( 'template_redirect', 'notallowed' );
``` |
279,344 | <p>I am customizing the Woocommerce Storefront theme.
In the product-list pages (category page, shop page), I would like to display the available sizes of the product when the user hover with its mouse on the image of a product.
So I need to add html/php code that will display this on hover:</p>
<p><strong>Available sizes:</strong></p>
<p><strong>S, M, L, XL</strong></p>
<p>or </p>
<p><strong>Sold out</strong></p>
<p><strong>Notify me when the product is in stock</strong></p>
<p>I would like to do this in the functions.php of my child theme.</p>
<p>Should I use this hook to add html ?</p>
<pre><code>woocommerce_before_shop_loop_item_title
</code></pre>
<p>I have started to code this, but I need help to go </p>
<pre><code>remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
/**
* WooCommerce Loop Product Thumbs
**/
if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
function woocommerce_template_loop_product_thumbnail() {
echo woocommerce_get_product_thumbnail();
}
}
/**
* WooCommerce Product Thumbnail
**/
if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) {
function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) {
global $post, $woocommerce;
$output = '<div class="imagewrapper">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( $post->ID, $size );
} else {
$output .= '<img src="'. woocommerce_placeholder_img_src() .'" alt="Placeholder" width="' . $placeholder_width . '" height="' . $placeholder_height . '" />';
}
//$product .= wc_get_product($post->ID ) ;
//$name .= $product->get_name();
$output .= '<div class="sizeAvailHover">';
//$output .= $name;
$output .= '</div>';
$output .= '</div>';
return $output;
}
}
</code></pre>
| [
{
"answer_id": 279349,
"author": "finitesource",
"author_id": 127371,
"author_profile": "https://wordpress.stackexchange.com/users/127371",
"pm_score": 0,
"selected": false,
"text": "<p>Yes. The <code>woocommerce_template_loop_product_thumbnail</code> is hooked into the <code>woocommerc... | 2017/09/07 | [
"https://wordpress.stackexchange.com/questions/279344",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/121787/"
] | I am customizing the Woocommerce Storefront theme.
In the product-list pages (category page, shop page), I would like to display the available sizes of the product when the user hover with its mouse on the image of a product.
So I need to add html/php code that will display this on hover:
**Available sizes:**
**S, M, L, XL**
or
**Sold out**
**Notify me when the product is in stock**
I would like to do this in the functions.php of my child theme.
Should I use this hook to add html ?
```
woocommerce_before_shop_loop_item_title
```
I have started to code this, but I need help to go
```
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
/**
* WooCommerce Loop Product Thumbs
**/
if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
function woocommerce_template_loop_product_thumbnail() {
echo woocommerce_get_product_thumbnail();
}
}
/**
* WooCommerce Product Thumbnail
**/
if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) {
function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) {
global $post, $woocommerce;
$output = '<div class="imagewrapper">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( $post->ID, $size );
} else {
$output .= '<img src="'. woocommerce_placeholder_img_src() .'" alt="Placeholder" width="' . $placeholder_width . '" height="' . $placeholder_height . '" />';
}
//$product .= wc_get_product($post->ID ) ;
//$name .= $product->get_name();
$output .= '<div class="sizeAvailHover">';
//$output .= $name;
$output .= '</div>';
$output .= '</div>';
return $output;
}
}
``` | Here's the code I finally used for those interested:
```
/* This snippet removes the action that inserts thumbnails to products in the loop
* and re-adds the function customized with our wrapper in it.
* It applies to all archives with products.
*
* @original plugin: WooCommerce
* @author of snippet: Brian Krogsard
*/
remove_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
add_action( 'woocommerce_before_shop_loop_item_title', 'woocommerce_template_loop_product_thumbnail', 10);
/**
* WooCommerce Loop Product Thumbs
**/
if ( ! function_exists( 'woocommerce_template_loop_product_thumbnail' ) ) {
function woocommerce_template_loop_product_thumbnail() {
echo woocommerce_get_product_thumbnail();
}
}
/**
* WooCommerce Product Thumbnail
**/
if ( ! function_exists( 'woocommerce_get_product_thumbnail' ) ) {
function woocommerce_get_product_thumbnail( $size = 'shop_catalog', $placeholder_width = 0, $placeholder_height = 0 ) {
global $post, $wp_query, $woocommerce, $attributes;
// if ( ! $placeholder_width ) {
// $placeholder_width = $woocommerce->get_image_size( 'shop_catalog_image_width' );
// }
// if ( ! $placeholder_height ){
// $placeholder_height = $woocommerce->get_image_size( 'shop_catalog_image_height' );
// }
$output = '<div class="imagewrapper">';
if ( has_post_thumbnail() ) {
$output .= get_the_post_thumbnail( $post->ID, $size );
} else {
$output .= '<img src="'. woocommerce_placeholder_img_src() .'" alt="Placeholder" width="' . $placeholder_width . '" height="' . $placeholder_height . '" />';
}
//$product .= wc_get_product($post->ID ) ;
//$name .= $product->get_name();
$output .= '<div class="sizeAvailHover">';
//$output .= $name;
//$product .= wc_get_product($post->ID ) ;
$product = wc_get_product( $wp_query->post );
//echo get_post_format();
// echo 'total stock : ';
// echo $product->is_in_stock();
if ( $product->is_type( 'variable' ) ) {
// $attributes .= $product->list_attributes();
// echo print_r($attributes);
// $attributes = $product->get_attributes();
// echo print_r($attributes);
// $attributes .= $product->wc_display_product_attributes();
// echo print_r($attributes);
// $attributes .= $product->get_variation_attributes();
// echo print_r($attributes);
if($product->is_in_stock()) {
$output .= ' Available sizes: <br/>';
$variations = $product->get_available_variations();
$i = 0;
foreach($variations as $variation){
$variation_id = $variation['variation_id'];
$variation_obj = new WC_Product_variation($variation_id);
$stock = $variation_obj->get_stock_quantity();
//echo $stock;
// echo '--';
//echo $variation_obj->get_sku();
//echo print_r($variation_obj->get_variation_attributes());
$dummy = $variation_obj->get_variation_attributes();
//echo gettype($stock);
if ((is_int($stock) || ctype_digit($stock)) && (int)$stock > 0 ) { // int }
//if ($stock > 0 ) {
//echo $variation_obj->get_attributes();
//echo 'yesssss';
// echo print_r($dummy['attribute_pa_size']);
$output .= '<span class="availSize">' . strtoupper($dummy['attribute_pa_size']) . '</span>';
} else {
// echo print_r($dummy['attribute_pa_size']);
$output .= '<span class="unavailSize">' . strtoupper($dummy['attribute_pa_size']) . '</span>';
}
if(++$i !== count($variations)) {
$output .= ', ';
}
//echo '<br/>';
}
} else {
$output .= ' Sold out<br/>Notify me when the product is back in stock';
}
// if ( ! $attributes ) {
// echo "No attributes";
// }
// foreach ( $attributes as $attribute ) {
// echo $attribute['name'] . ": ";
// $product_attributes = array();
// $product_attributes = explode('|',$attribute['value']);
// $attributes_dropdown = '<select>';
// foreach ( $product_attributes as $pa ) {
// $attributes_dropdown .= '<option value="' . $pa . '">' . $pa . '</option>';
// }
// $attributes_dropdown .= '</select>';
// echo $attributes_dropdown;
// }
}
$output .= '</div>';
$output .= '</div>';
return $output;
}
}
``` |
279,353 | <p>I'm trying to organize my search results page based on an ACF subfield value of a repeater field. I would like a LIKE result rather than =.</p>
<p>So far, I got the following (modified with help below, but still not working):</p>
<pre><code>// Modify meta key to allow wildcard
function add_wildcard_to_meta_key_filter( $where ) {
$where = str_replace("meta_key = 'test_repeater_%", "meta_key LIKE 'test_repeater_%", $where);
return $where;
}
add_filter('posts_where', 'add_wildcard_to_meta_key_filter');
//Modify search query
function alter_search_query($query) {
if ( !$query->is_search )
return $query;
$search = $query->query;
$query->set('post_type' ,'page');
$query->set('meta_query', array(
array(
'meta_key' => 'test_repeater_%_test_sub_field',
'meta_value' => '%'.$search.'%',
'compare' => 'LIKE',
),
));
$query->set('s', '');
}
add_action('pre_get_posts','alter_search_query');
</code></pre>
<p>It works fine if I add the exact value, i.e. "beef tenderloin", but if I enter "beef" it fails. How do I get the search to be more generic?</p>
<p>I installed the Query Monitor plugin and noticed I got the following SQL</p>
<pre><code>SELECT SQL_CALC_FOUND_ROWS wpfb_posts.ID
FROM wpfb_posts
INNER JOIN wpfb_postmeta
ON ( wpfb_posts.ID = wpfb_postmeta.post_id )
WHERE 1=1
AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field'
AND wpfb_postmeta.meta_value IN ('beef') ) )
AND wpfb_posts.post_type = 'page'
AND (wpfb_posts.post_status = 'publish'
OR wpfb_posts.post_status = 'acf-disabled'
OR wpfb_posts.post_status = 'private')
GROUP BY wpfb_posts.ID
ORDER BY wpfb_posts.post_date DESC
LIMIT 0, 10
</code></pre>
<p>If I change this:</p>
<pre><code>AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field'
AND wpfb_postmeta.meta_value IN ('beef') ) )
</code></pre>
<p>To this:</p>
<pre><code>AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field'
AND wpfb_postmeta.meta_value LIKE '%beef%' ) )
</code></pre>
<p>And run that in phpMyAdmin's SQL, I get the desired row. The question is, how can I change the query to look like that using WordPress functions?</p>
| [
{
"answer_id": 279355,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>You need to add Wildcards to your meta_value.</p>\n\n<p>Change </p>\n\n<pre><code>$query->set('met... | 2017/09/07 | [
"https://wordpress.stackexchange.com/questions/279353",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94213/"
] | I'm trying to organize my search results page based on an ACF subfield value of a repeater field. I would like a LIKE result rather than =.
So far, I got the following (modified with help below, but still not working):
```
// Modify meta key to allow wildcard
function add_wildcard_to_meta_key_filter( $where ) {
$where = str_replace("meta_key = 'test_repeater_%", "meta_key LIKE 'test_repeater_%", $where);
return $where;
}
add_filter('posts_where', 'add_wildcard_to_meta_key_filter');
//Modify search query
function alter_search_query($query) {
if ( !$query->is_search )
return $query;
$search = $query->query;
$query->set('post_type' ,'page');
$query->set('meta_query', array(
array(
'meta_key' => 'test_repeater_%_test_sub_field',
'meta_value' => '%'.$search.'%',
'compare' => 'LIKE',
),
));
$query->set('s', '');
}
add_action('pre_get_posts','alter_search_query');
```
It works fine if I add the exact value, i.e. "beef tenderloin", but if I enter "beef" it fails. How do I get the search to be more generic?
I installed the Query Monitor plugin and noticed I got the following SQL
```
SELECT SQL_CALC_FOUND_ROWS wpfb_posts.ID
FROM wpfb_posts
INNER JOIN wpfb_postmeta
ON ( wpfb_posts.ID = wpfb_postmeta.post_id )
WHERE 1=1
AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field'
AND wpfb_postmeta.meta_value IN ('beef') ) )
AND wpfb_posts.post_type = 'page'
AND (wpfb_posts.post_status = 'publish'
OR wpfb_posts.post_status = 'acf-disabled'
OR wpfb_posts.post_status = 'private')
GROUP BY wpfb_posts.ID
ORDER BY wpfb_posts.post_date DESC
LIMIT 0, 10
```
If I change this:
```
AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field'
AND wpfb_postmeta.meta_value IN ('beef') ) )
```
To this:
```
AND ( ( wpfb_postmeta.meta_key LIKE 'test_repeater_%_test_sub_field'
AND wpfb_postmeta.meta_value LIKE '%beef%' ) )
```
And run that in phpMyAdmin's SQL, I get the desired row. The question is, how can I change the query to look like that using WordPress functions? | You need to add Wildcards to your meta\_value.
Change
```
$query->set('meta_query', array(
array(
'meta_key' => 'test_repeater_%_test_sub_field',
'meta_value' => $search,
'compare' => 'LIKE',
),
));
```
To
```
$query->set('meta_query', array(
array(
'meta_key' => 'test_repeater_%_test_sub_field',
'meta_value' => '%'.$search.'%',
'compare' => 'LIKE',
),
));
``` |
279,380 | <p>Have a custom post type, where each post is a gallery, and each has an Advanced Custom Fields Gallery field that has say 5-20 images each. Also have a custom post type post template as seen below (stripped out most of the code to focus on parts that are relevant to this.) The comments in the code explain which each part does. Overall it appears to all work, however no matter what post I'm on in this custom post type, such as example.com/gallery/gallery-1, example.com/gallery/gallery-2, example.com/gallery/gallery-3, etc. It shows the same featured image and same thumbnails on each page. It appears to be pulling the first gallery from the first post, rather than on each page checking to pull in the gallery items associated with that page.</p>
<p>I'm sure it's simple such as a matter of needing to flush/reset a loop or such, but struggling to find the right way to describe it to find the answer on Google. Had it working originally, but once I had to add loops inside of loops the issue started. If anyone has any idea would great. Will keep researching in the meantime.</p>
<pre><code><?php get_header(); ?>
<div id="main">
<?php
//Checks gallery custom post type and finds the current pages entry
$args = array( 'post_type' => 'customers_gallery', 'posts_per_page' => 1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div>
<?php
//Looks up the advanced custom field gallery associated with this post
$hero = get_field('gallery_images'); ?>
<!-- //Show the first image in that gallery -->
<img src="<?php echo $hero[0]['url']; ?>" class="main-image" style="width: 484px;">
<!-- //Shows title of this page -->
<h3><?php the_title(); ?></h3>
<?php
//Looks up the advanced custom field gallery associated with this post
$images = get_field('gallery_images');
//Loops through all the gallery image showing a thumbnail for each and each is linked to its full size
if( $images ): ?>
<ul>
<?php foreach( $images as $image ): ?>
<li>
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['gallery-landscape-thb']; ?>" alt="<?php echo $image['alt']; ?>" />
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<div>
<ul>
<?php
//Looks up all the pages in this custom post type and lists the titles of the first 12 and linked to respective pages
$custom_query = new WP_Query(
array(
'post_type' => 'customers_gallery',
'posts_per_page' => 12
)
);
if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
</div>
</div>
<?php endwhile; ?>
</div>
<!-- /#main -->
<?php get_footer(); ?>
</code></pre>
<p>UPDATE</p>
<p>Some have noted to add a reset, but I'm still thinking the issue is something else. Since I can remove nearly all the code in template and get it down just to the following and it still echos the same title no mater which post im viewing in the gallery custom post type (it shows the first title in the list of posts in the gallery custom post type, where is it should pull in the title for that particular page. The title in the tab is correct.</p>
<pre><code><?php get_header(); ?>
<?php
$args = array( 'post_type' => 'customers_gallery', 'posts_per_page' => 1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php echo the_title(); ?>
<?php endwhile; ?>
<?php get_footer(); ?>
</code></pre>
<p>UPDATE 2</p>
<p>Returned to the original code that I posted in this message and simply removed the code noted in my second post aka, that $args = array( 'post_type' => 'customers_gallery'... and all works. So seems the issue was I was trying to create a loop for the custom post type but looks like that is not needed when using a single-[custom-post-type-name].php. </p>
| [
{
"answer_id": 279355,
"author": "HU is Sebastian",
"author_id": 56587,
"author_profile": "https://wordpress.stackexchange.com/users/56587",
"pm_score": 2,
"selected": false,
"text": "<p>You need to add Wildcards to your meta_value.</p>\n\n<p>Change </p>\n\n<pre><code>$query->set('met... | 2017/09/07 | [
"https://wordpress.stackexchange.com/questions/279380",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5465/"
] | Have a custom post type, where each post is a gallery, and each has an Advanced Custom Fields Gallery field that has say 5-20 images each. Also have a custom post type post template as seen below (stripped out most of the code to focus on parts that are relevant to this.) The comments in the code explain which each part does. Overall it appears to all work, however no matter what post I'm on in this custom post type, such as example.com/gallery/gallery-1, example.com/gallery/gallery-2, example.com/gallery/gallery-3, etc. It shows the same featured image and same thumbnails on each page. It appears to be pulling the first gallery from the first post, rather than on each page checking to pull in the gallery items associated with that page.
I'm sure it's simple such as a matter of needing to flush/reset a loop or such, but struggling to find the right way to describe it to find the answer on Google. Had it working originally, but once I had to add loops inside of loops the issue started. If anyone has any idea would great. Will keep researching in the meantime.
```
<?php get_header(); ?>
<div id="main">
<?php
//Checks gallery custom post type and finds the current pages entry
$args = array( 'post_type' => 'customers_gallery', 'posts_per_page' => 1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<div>
<?php
//Looks up the advanced custom field gallery associated with this post
$hero = get_field('gallery_images'); ?>
<!-- //Show the first image in that gallery -->
<img src="<?php echo $hero[0]['url']; ?>" class="main-image" style="width: 484px;">
<!-- //Shows title of this page -->
<h3><?php the_title(); ?></h3>
<?php
//Looks up the advanced custom field gallery associated with this post
$images = get_field('gallery_images');
//Loops through all the gallery image showing a thumbnail for each and each is linked to its full size
if( $images ): ?>
<ul>
<?php foreach( $images as $image ): ?>
<li>
<a href="<?php echo $image['url']; ?>">
<img src="<?php echo $image['sizes']['gallery-landscape-thb']; ?>" alt="<?php echo $image['alt']; ?>" />
</a>
</li>
<?php endforeach; ?>
</ul>
<?php endif; ?>
<div>
<ul>
<?php
//Looks up all the pages in this custom post type and lists the titles of the first 12 and linked to respective pages
$custom_query = new WP_Query(
array(
'post_type' => 'customers_gallery',
'posts_per_page' => 12
)
);
if ( $custom_query->have_posts() ) : while ( $custom_query->have_posts() ) : $custom_query->the_post(); ?>
<li><a href="<?php the_permalink(); ?>"><?php the_title(); ?></a></li>
<?php endwhile; endif; wp_reset_query(); ?>
</ul>
</div>
</div>
<?php endwhile; ?>
</div>
<!-- /#main -->
<?php get_footer(); ?>
```
UPDATE
Some have noted to add a reset, but I'm still thinking the issue is something else. Since I can remove nearly all the code in template and get it down just to the following and it still echos the same title no mater which post im viewing in the gallery custom post type (it shows the first title in the list of posts in the gallery custom post type, where is it should pull in the title for that particular page. The title in the tab is correct.
```
<?php get_header(); ?>
<?php
$args = array( 'post_type' => 'customers_gallery', 'posts_per_page' => 1 );
$loop = new WP_Query( $args );
while ( $loop->have_posts() ) : $loop->the_post(); ?>
<?php echo the_title(); ?>
<?php endwhile; ?>
<?php get_footer(); ?>
```
UPDATE 2
Returned to the original code that I posted in this message and simply removed the code noted in my second post aka, that $args = array( 'post\_type' => 'customers\_gallery'... and all works. So seems the issue was I was trying to create a loop for the custom post type but looks like that is not needed when using a single-[custom-post-type-name].php. | You need to add Wildcards to your meta\_value.
Change
```
$query->set('meta_query', array(
array(
'meta_key' => 'test_repeater_%_test_sub_field',
'meta_value' => $search,
'compare' => 'LIKE',
),
));
```
To
```
$query->set('meta_query', array(
array(
'meta_key' => 'test_repeater_%_test_sub_field',
'meta_value' => '%'.$search.'%',
'compare' => 'LIKE',
),
));
``` |