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 |
|---|---|---|---|---|---|---|
256,669 | <p>I am registering the stylesheet and scripts but It is not working please help me. What I am doing wrong </p>
<pre><code>function theme_styles_and_scripts() {
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
</code></pre>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are add... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256669",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108146/"
] | I am registering the stylesheet and scripts but It is not working please help me. What I am doing wrong
```
function theme_styles_and_scripts() {
wp_enqueue_style('bootstrap', get_template_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
``` | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,682 | <p>I want to display dates in <strong>Hindi</strong> format like</p>
<pre><code>jan 10
</code></pre>
<p>using <code>get_the_date()</code> function. What I have tried so far:</p>
<pre><code>echo get_the_date(_e('F j'));
</code></pre>
<p>which outputs:</p>
<pre><code>F jJanuary 10, 2017.
</code></pre>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are add... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256682",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112924/"
] | I want to display dates in **Hindi** format like
```
jan 10
```
using `get_the_date()` function. What I have tried so far:
```
echo get_the_date(_e('F j'));
```
which outputs:
```
F jJanuary 10, 2017.
``` | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,702 | <p>How can I query only those pages that <strong>DO NOT HAVE</strong> child pages?</p>
<p>E.g.:</p>
<ul>
<li>Parent page 1
<ul>
<li>Child page 1</li>
<li>Child page 2</li>
</ul></li>
<li>Parent page 2</li>
<li>Parent page 3
<ul>
<li>Child page 1</li>
<li>Child page 2</li>
</ul></li>
<li>Parent page 4</li>
</ul>
<p>I would like to show </p>
<ul>
<li>Parent page 2</li>
<li>Parent page 4</li>
</ul>
<p><pre><code>
$newQuery = new WP_Query( array (
'posts_per_page' => -1,
'post_type' => 'page',
// Solution?
) );
</pre></code> </p>
<p>Thanks</p>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are add... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33745/"
] | How can I query only those pages that **DO NOT HAVE** child pages?
E.g.:
* Parent page 1
+ Child page 1
+ Child page 2
* Parent page 2
* Parent page 3
+ Child page 1
+ Child page 2
* Parent page 4
I would like to show
* Parent page 2
* Parent page 4
```
$newQuery = new WP_Query( array (
'posts_per_page' => -1,
'post_type' => 'page',
// Solution?
) );
```
Thanks | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,705 | <p>I am new for wordpress and i am using Ubuntu OS on my computer I want to run a downloded theme on localhost how can i do that?</p>
| [
{
"answer_id": 256672,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": true,
"text": "<p>There can be multiple reasons why it may not be working.</p>\n\n<p><strong>Possibility-1:</strong> You are add... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113280/"
] | I am new for wordpress and i am using Ubuntu OS on my computer I want to run a downloded theme on localhost how can i do that? | There can be multiple reasons why it may not be working.
**Possibility-1:** You are adding the CSS file in a child theme. In that case, use the following CODE instead:
```
function theme_styles_and_scripts() {
wp_enqueue_style( 'bootstrap', get_stylesheet_directory_uri() . '/css/bootstrap.min.css', array(), '3.3.6', 'all' );
}
add_action( 'wp_enqueue_scripts', 'theme_styles_and_scripts' );
```
[`get_stylesheet_directory_uri()`](https://developer.wordpress.org/reference/functions/get_stylesheet_directory_uri/) returns the URL of your current theme (whether it is a child theme or not). On the other hand, [`get_template_directory_uri()`](https://developer.wordpress.org/reference/functions/get_template_directory_uri/) returns the parent theme URL if you are using a child theme & the current theme URL only if the active theme is not a child theme of another theme.
**Possibility-2:** You are not calling `wp_head()` anywhere in your theme's template files (usually `header.php`). However, if you are modifying any standard theme, then this is not the likely case, as any standard theme will not make this mistake.
**Other Possibilities:**
However, if you view HTML source & see that you are finding `bootstrap` in it, then perhaps another call to `wp_enqueue_style` with the same name is overriding it ([as suggested by this answer](https://wordpress.stackexchange.com/a/256674/110572)) or perhaps your CSS is being added, but some other CSS is overriding your CSS rules.
**How to Debug:**
An easy way to debug this issue is to create a simple CSS file with the following CSS CODE:
```
body {
background-color: red !important;
}
```
Then save the CSS file in your theme's `css` folder with the name `wpse256672-style.css`.
Then use the following CODE in your theme's `functions.php` file:
```
function wpse256672_css_enqueue() {
wp_enqueue_style( 'wpse256672_css', get_stylesheet_directory_uri() . '/css/wpse256672-style.css', array(), '1.0.0', 'all' );
}
add_action( 'wp_enqueue_scripts', 'wpse256672_css_enqueue' );
```
Now if you reload the page after saving the above, you should see red background in your page. That means you don't have `Possibility-2` above, but perhaps `Possibility-1` or something else. Change CSS file name, `$handle` from `bootstrap` to something else, change version number, check if the file exists etc.
>
> Note: If you have cache plugin activated, clear cache first & then clear browser cache before doing the above tests.
>
>
> |
256,707 | <p>I'm displaying a gallery image but I also want display the caption for image. I can get the info that we insert when us upload a image in WordPress Dashboard like "Title/Caption/ALT/Description". I want get anyone and display.</p>
<pre><code><?php
$gallery = get_post_gallery_images( $post );
foreach( $gallery as $image_url ) :
?>
<div class="item" style="background-image: url('<?php echo $image_url ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_url->"DESCRIPTION/TITLE/ALT"; ?> </h2>
</div>
</div>
</code></pre>
<p>Reading at the docs of <a href="https://codex.wordpress.org/Function_Reference/get_post_gallery_images" rel="nofollow noreferrer">get_post_gallery_images</a> I didn't find a solution for my issue. <br>
I also found <a href="https://wordpress.stackexchange.com/questions/125554/get-image-description">this answer</a> but I don't know if it works and I've erros to implement in my code.</p>
<p>Anyway, how can I solve this?</p>
| [
{
"answer_id": 256715,
"author": "Kyon147",
"author_id": 102156,
"author_profile": "https://wordpress.stackexchange.com/users/102156",
"pm_score": 2,
"selected": false,
"text": "<p>The caption for an image is actually meta_data attached to the image and the <a href=\"https://developer.wo... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256707",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94215/"
] | I'm displaying a gallery image but I also want display the caption for image. I can get the info that we insert when us upload a image in WordPress Dashboard like "Title/Caption/ALT/Description". I want get anyone and display.
```
<?php
$gallery = get_post_gallery_images( $post );
foreach( $gallery as $image_url ) :
?>
<div class="item" style="background-image: url('<?php echo $image_url ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_url->"DESCRIPTION/TITLE/ALT"; ?> </h2>
</div>
</div>
```
Reading at the docs of [get\_post\_gallery\_images](https://codex.wordpress.org/Function_Reference/get_post_gallery_images) I didn't find a solution for my issue.
I also found [this answer](https://wordpress.stackexchange.com/questions/125554/get-image-description) but I don't know if it works and I've erros to implement in my code.
Anyway, how can I solve this? | You need to get the `metadata` of each image, add this to your `functions.php` file:
```
function get_post_gallery_images_with_info($postvar = NULL) {
if(!isset($postvar)){
global $post;
$postvar = $post;//if the param wasnt sent
}
$post_content = $postvar->post_content;
preg_match('/\[gallery.*ids=.(.*).\]/', $post_content, $ids);
$images_id = explode(",", $ids[1]); //we get the list of IDs of the gallery as an Array
$image_gallery_with_info = array();
//we get the info for each ID
foreach ($images_id as $image_id) {
$attachment = get_post($image_id);
array_push($image_gallery_with_info, array(
'alt' => get_post_meta($attachment->ID, '_wp_attachment_image_alt', true),
'caption' => $attachment->post_excerpt,
'description' => $attachment->post_content,
'href' => get_permalink($attachment->ID),
'src' => $attachment->guid,
'title' => $attachment->post_title
)
);
}
return $image_gallery_with_info;
}
```
use it in your logic like this:
```
<?php
$gallery = get_post_gallery_images_with_info($post); //you can use it without params too
foreach( $gallery as $image_obj ) :
?>
<div class="item" style="background-image: url('<?php echo $image_obj['src'] ?>'); background-size: cover">
<div class="caption">
<!-- Here I want display the Title/Caption/ALT/Description of image -->
<h2><?php echo $image_obj['title']." ". $image_obj['caption']." ".$image_obj['description']; ?> </h2>
</div>
</div>
<?php
endforeach;
?>
```
it will output like this:
[](https://i.stack.imgur.com/2sZ2N.png)
each image returned by the function is an array like this:
```
Array
(
[alt] => Alt Coffe
[caption] => Caption coffe
[description] => Description coffe
[href] => http://yoursite/2017/02/14/hello-world/coffee/
[src] => http://yoursite/wp-content/uploads/sites/4/2017/02/coffee.jpg
[title] => coffee
)
```
notice `href` and `src` are different, one is the permalink and the other the direct `URL`. |
256,717 | <p>I'm trying to change the logo url of the site to "mywebsite.com/side2", but it is not working, can anyone tell me where is the error in the code below?</p>
<pre><code>add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
return home_url( 'side2' );
}
</code></pre>
| [
{
"answer_id": 256718,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the <strong>get_page_by_path</strong> as follows:</p>\n\n<pre><code>add_filter( 'login_head... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256717",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113413/"
] | I'm trying to change the logo url of the site to "mywebsite.com/side2", but it is not working, can anyone tell me where is the error in the code below?
```
add_filter( 'login_headerurl', 'custom_loginlogo_url' );
function custom_loginlogo_url($url) {
return home_url( 'side2' );
}
``` | The `login_headerurl` filter is for changing the logo url of login page, according to the [Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_headerurl).
To change the logo URL of your homepage, you will have to look into your theme's `header.php` file. You logo and it's link are included there. Depending on your theme, they way that your URL is generated may be different.
Access your `header.php` file from `Appearance > Edit` in the admin panel, and search for the line containing the logo. There, you can change it to whatever you want. |
256,724 | <p>I'm using a child theme based on 'Twenty Seventeen' and have created a custom post type ('review').</p>
<p>I want to make two Pages, one which lists 'reviews' and the other which lists a mixture of 'posts' and 'reviews' (ordered by recency).</p>
<p>For the first of those I've made a copy of Twenty Seventeen's <code>index.php</code>, as <code>page-reviews.php</code>, and added code like this at the start:</p>
<pre><code>$args = array(
'post_type' => 'review',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 10,
);
$the_query = new WP_Query( $args );
</code></pre>
<p>Then, further down, replaced <code>have_posts()</code> and <code>the_post()</code> with <code>$the_query->have_posts()</code> and <code>$the_query->the_post()</code> respectively.</p>
<p>If I choose to use that template for a Page then it works in that the 'reviews' are listed, <em>but</em> the layout is all messed up. There are a lot of classes in the <code><body></code> which mess up the layout.</p>
<p>For example, the standard blog front page, using <code>index.php</code>, has these classes in its <code><body></code> and looks fine:</p>
<pre><code>blog logged-in admin-bar hfeed has-header-image has-sidebar colors-light customize-support
</code></pre>
<p>While my custom page has these:</p>
<pre><code>page-template page-template-page-postslist page-template-page-postslist-php page page-id-15071 logged-in admin-bar has-header-image page-two-column colors-light customize-support
</code></pre>
<p>How can I make a custom template that acts more like <code>index.php</code> in terms of the classes it adds?</p>
| [
{
"answer_id": 256718,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": -1,
"selected": false,
"text": "<p>You can use the <strong>get_page_by_path</strong> as follows:</p>\n\n<pre><code>add_filter( 'login_head... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256724",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/57920/"
] | I'm using a child theme based on 'Twenty Seventeen' and have created a custom post type ('review').
I want to make two Pages, one which lists 'reviews' and the other which lists a mixture of 'posts' and 'reviews' (ordered by recency).
For the first of those I've made a copy of Twenty Seventeen's `index.php`, as `page-reviews.php`, and added code like this at the start:
```
$args = array(
'post_type' => 'review',
'orderby' => 'date',
'order' => 'DESC',
'posts_per_page' => 10,
);
$the_query = new WP_Query( $args );
```
Then, further down, replaced `have_posts()` and `the_post()` with `$the_query->have_posts()` and `$the_query->the_post()` respectively.
If I choose to use that template for a Page then it works in that the 'reviews' are listed, *but* the layout is all messed up. There are a lot of classes in the `<body>` which mess up the layout.
For example, the standard blog front page, using `index.php`, has these classes in its `<body>` and looks fine:
```
blog logged-in admin-bar hfeed has-header-image has-sidebar colors-light customize-support
```
While my custom page has these:
```
page-template page-template-page-postslist page-template-page-postslist-php page page-id-15071 logged-in admin-bar has-header-image page-two-column colors-light customize-support
```
How can I make a custom template that acts more like `index.php` in terms of the classes it adds? | The `login_headerurl` filter is for changing the logo url of login page, according to the [Codex](https://codex.wordpress.org/Plugin_API/Filter_Reference/login_headerurl).
To change the logo URL of your homepage, you will have to look into your theme's `header.php` file. You logo and it's link are included there. Depending on your theme, they way that your URL is generated may be different.
Access your `header.php` file from `Appearance > Edit` in the admin panel, and search for the line containing the logo. There, you can change it to whatever you want. |
256,726 | <ol>
<li>I have Zend framework 2 application (PHP), via which I want to use WP-CLI functionality. near Zend project I have WordPress project, which I want to maintain from Zend via WP-CLI. </li>
<li>I see in the docs that WP-CLI also written on PHP. I dreamed that I install WP-CLI via composer in root of my project and can use its classes there.</li>
<li>After installing via composer in WP-CLI's sources I see functions from WordPress (like as is_multisite and etc) and I little disappointed :).</li>
</ol>
<p>main question:
Can I in some way use WP-CLI sources directly from my Zend-project without calling commands via terminal?
for example (in abstract programming language):</p>
<pre><code>$command = new WP_CLI::command('command_name subcommand_name', $params, $assoc_params, .....);
$result = $command->execute();
</code></pre>
<p>Or WP-CLI was made only as part of the WordPress project as way for extending it's commands and it is unable to use them as I am trying?</p>
| [
{
"answer_id": 291803,
"author": "swissspidy",
"author_id": 12404,
"author_profile": "https://wordpress.stackexchange.com/users/12404",
"pm_score": 0,
"selected": false,
"text": "<p>The <code>WP_CLI</code> class has a <code>runcommand</code> method that launches a new child process to ru... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256726",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113499/"
] | 1. I have Zend framework 2 application (PHP), via which I want to use WP-CLI functionality. near Zend project I have WordPress project, which I want to maintain from Zend via WP-CLI.
2. I see in the docs that WP-CLI also written on PHP. I dreamed that I install WP-CLI via composer in root of my project and can use its classes there.
3. After installing via composer in WP-CLI's sources I see functions from WordPress (like as is\_multisite and etc) and I little disappointed :).
main question:
Can I in some way use WP-CLI sources directly from my Zend-project without calling commands via terminal?
for example (in abstract programming language):
```
$command = new WP_CLI::command('command_name subcommand_name', $params, $assoc_params, .....);
$result = $command->execute();
```
Or WP-CLI was made only as part of the WordPress project as way for extending it's commands and it is unable to use them as I am trying? | This is probably unwise. WP-CLI is developed as a command line utility and might not maintain internal structure between releases.
Since everything has to run as root in any case, there is no real difference between executing a WP-CLI command via a shell (A.K.A `exec` and its family of functions), or by calling whatever API. |
256,733 | <p>Failing miserably at adding a custom column</p>
<pre><code>add_action('manage_edit-pricing_columns', 'manage_pricing_columns');
add_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');
function manage_pricing_columns($_columns) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = _x('Pricing Item', 'column name');
$new_columns['categories'] = _x('Type', 'column name');
$new_columns['date'] = _x('Created', 'column name');
return $new_columns;
}
function manage_pricing_custom_columns($column, $post_id){
global $post;
switch($_columns) {
case 'categories':
$pt = get_the_terms( $post_id, 'pricing_type' );
echo $pt[0]->name;
break;
default:
break;
}
}
</code></pre>
<p><code>Type</code> column only ever shows <code>--</code> Yes, I have verified <code>$pt[0]->name</code> <code>var_dumps</code> what it actually should be.</p>
<p>So, what am I doing wrong here? I need the <code>Type</code> column to show my <code>pricing_type</code> value.</p>
<p><code>pricing</code> is a custom post type, while <code>pricing_type</code> is a custom taxonomy of the <code>pricing</code> post type.</p>
| [
{
"answer_id": 256734,
"author": "codiiv",
"author_id": 91561,
"author_profile": "https://wordpress.stackexchange.com/users/91561",
"pm_score": 2,
"selected": true,
"text": "<pre><code>add_action('manage_edit-pricing_columns', 'manage_pricing_columns');\nadd_action('manage_pricing_posts_... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256733",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/84711/"
] | Failing miserably at adding a custom column
```
add_action('manage_edit-pricing_columns', 'manage_pricing_columns');
add_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');
function manage_pricing_columns($_columns) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = _x('Pricing Item', 'column name');
$new_columns['categories'] = _x('Type', 'column name');
$new_columns['date'] = _x('Created', 'column name');
return $new_columns;
}
function manage_pricing_custom_columns($column, $post_id){
global $post;
switch($_columns) {
case 'categories':
$pt = get_the_terms( $post_id, 'pricing_type' );
echo $pt[0]->name;
break;
default:
break;
}
}
```
`Type` column only ever shows `--` Yes, I have verified `$pt[0]->name` `var_dumps` what it actually should be.
So, what am I doing wrong here? I need the `Type` column to show my `pricing_type` value.
`pricing` is a custom post type, while `pricing_type` is a custom taxonomy of the `pricing` post type. | ```
add_action('manage_edit-pricing_columns', 'manage_pricing_columns');
add_action('manage_pricing_posts_custom_column', 'manage_pricing_custom_columns');
function manage_pricing_columns($_columns) {
$new_columns['cb'] = '<input type="checkbox" />';
$new_columns['title'] = _x('Pricing Item', 'wp');
$new_columns['categories'] = _x('Type', 'wp');
$new_columns['date'] = _x('Created', 'wp');
return $new_columns;
}
function manage_pricing_custom_columns($column, $post_id){
global $post;
switch($_columns) {
case 'pricing_type':
$pt = get_the_terms( $post_id, 'pricing_type' );
echo $pt[0]->name;
break;
default:
break;
}
}
``` |
256,751 | <p>I have a custom post type <code>event</code> in WordPress, and I need to query upcoming <code>event</code> <code>posts</code> comparing <code>$current_date</code>.</p>
<p>Query conditions are :</p>
<ul>
<li><code>start_date</code> is a valid <code>date</code> always</li>
<li><code>end_date</code> can be a valid <code>date</code> or <code>null</code> or <code>empty</code> string.</li>
<li>IF <code>end_date</code> is a valid <code>date</code> in db record then compare <code>end_date >= $current_date</code></li>
<li>ELSE IF <code>end_date</code> is <code>null</code> or <code>empty</code> then compare <code>start_date >=$current_date</code>.</li>
</ul>
<p>Now If <code>end_date</code> was not optional , I could use below code to get desired results.</p>
<pre><code>$args= array();
$args['post_type'] = "event";
$args['meta_query'] = array(
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date("Ymd",$current_date),
)
);
$post_query = new WP_Query();
$posts_list = $post_query->query($args);
</code></pre>
<p>My problem is, how do I handle optional <code>end_date</code> in above code.</p>
<p>Thanks in advance.</p>
<p>Edit:
Reformatted code and text above to make it more clear</p>
| [
{
"answer_id": 256753,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// $startday, $endday - format YYYY-MM-DD and field format: YYYY-MM-DD \n $args= array... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256751",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/73154/"
] | I have a custom post type `event` in WordPress, and I need to query upcoming `event` `posts` comparing `$current_date`.
Query conditions are :
* `start_date` is a valid `date` always
* `end_date` can be a valid `date` or `null` or `empty` string.
* IF `end_date` is a valid `date` in db record then compare `end_date >= $current_date`
* ELSE IF `end_date` is `null` or `empty` then compare `start_date >=$current_date`.
Now If `end_date` was not optional , I could use below code to get desired results.
```
$args= array();
$args['post_type'] = "event";
$args['meta_query'] = array(
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date("Ymd",$current_date),
)
);
$post_query = new WP_Query();
$posts_list = $post_query->query($args);
```
My problem is, how do I handle optional `end_date` in above code.
Thanks in advance.
Edit:
Reformatted code and text above to make it more clear | There is no need to craft a custom SQL query in order to achieve this. Since version 4.1, WordPress's query classes have [supported complex/nested meta queries](https://core.trac.wordpress.org/ticket/29642). So you can craft a query like this:
```
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
// OR!
array(
// A nested set of conditions for when the above condition is false.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
),
);
```
I have tested this, and it works perfectly. My PHPUnit testcase:
```
/**
* Tests something.
*/
class My_Plugin_Test extends WP_UnitTestCase {
public function test_wpse() {
$current_time = current_time( 'timestamp' );
$current_date = date( 'Ymd', $current_time );
$yesterday_date = date( 'Ymd', strtotime( 'yesterday' ) );
$post_ids = $this->factory->post->create_many( 6 );
$post_with_end_past = $post_ids[0];
$post_with_end_now = $post_ids[1];
$post_empty_end_past = $post_ids[2];
$post_empty_end_now = $post_ids[3];
$post_null_end_past = $post_ids[4];
$post_null_end_now = $post_ids[5];
// This post has an end date in the past.
update_post_meta( $post_with_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_past, 'end_date', $yesterday_date );
// This post has an end date in the present.
update_post_meta( $post_with_end_now, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_now, 'end_date', $current_date );
// This post has no end date, but a start date in the past.
update_post_meta( $post_empty_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_empty_end_past, 'end_date', '' );
// This post has an empty end date, but the start date is now.
update_post_meta( $post_empty_end_now, 'start_date', $current_date );
update_post_meta( $post_empty_end_now, 'end_date', '' );
// This post has no end date set at all, and the start date is past.
update_post_meta( $post_null_end_past, 'start_date', $yesterday_date );
// This post has no end date set at all, but the start date is now.
update_post_meta( $post_null_end_now, 'start_date', $current_date );
$args = array();
$args['fields'] = 'ids';
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $current_date,
),
// OR!
array(
// If an end_date does not exist.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => $current_date,
),
),
);
$post_query = new WP_Query();
$posts_list = $post_query->query( $args );
// Only the "now" posts should be returned.
$this->assertSame(
array( $post_with_end_now, $post_empty_end_now, $post_null_end_now )
, $posts_list
);
}
}
``` |
256,754 | <p>I am trying to edit theme editor to edit files on wordpress, but I get the error about, the file is not writable. So now I want to give the account write permissions on the file, but I don't know which user account wordpress runs as on the website when editing files. Does anyone know?</p>
<p>Thanks</p>
| [
{
"answer_id": 256753,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 0,
"selected": false,
"text": "<pre><code>// $startday, $endday - format YYYY-MM-DD and field format: YYYY-MM-DD \n $args= array... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256754",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113339/"
] | I am trying to edit theme editor to edit files on wordpress, but I get the error about, the file is not writable. So now I want to give the account write permissions on the file, but I don't know which user account wordpress runs as on the website when editing files. Does anyone know?
Thanks | There is no need to craft a custom SQL query in order to achieve this. Since version 4.1, WordPress's query classes have [supported complex/nested meta queries](https://core.trac.wordpress.org/ticket/29642). So you can craft a query like this:
```
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
// OR!
array(
// A nested set of conditions for when the above condition is false.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => date( 'Ymd', $current_date ),
),
),
);
```
I have tested this, and it works perfectly. My PHPUnit testcase:
```
/**
* Tests something.
*/
class My_Plugin_Test extends WP_UnitTestCase {
public function test_wpse() {
$current_time = current_time( 'timestamp' );
$current_date = date( 'Ymd', $current_time );
$yesterday_date = date( 'Ymd', strtotime( 'yesterday' ) );
$post_ids = $this->factory->post->create_many( 6 );
$post_with_end_past = $post_ids[0];
$post_with_end_now = $post_ids[1];
$post_empty_end_past = $post_ids[2];
$post_empty_end_now = $post_ids[3];
$post_null_end_past = $post_ids[4];
$post_null_end_now = $post_ids[5];
// This post has an end date in the past.
update_post_meta( $post_with_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_past, 'end_date', $yesterday_date );
// This post has an end date in the present.
update_post_meta( $post_with_end_now, 'start_date', $yesterday_date );
update_post_meta( $post_with_end_now, 'end_date', $current_date );
// This post has no end date, but a start date in the past.
update_post_meta( $post_empty_end_past, 'start_date', $yesterday_date );
update_post_meta( $post_empty_end_past, 'end_date', '' );
// This post has an empty end date, but the start date is now.
update_post_meta( $post_empty_end_now, 'start_date', $current_date );
update_post_meta( $post_empty_end_now, 'end_date', '' );
// This post has no end date set at all, and the start date is past.
update_post_meta( $post_null_end_past, 'start_date', $yesterday_date );
// This post has no end date set at all, but the start date is now.
update_post_meta( $post_null_end_now, 'start_date', $current_date );
$args = array();
$args['fields'] = 'ids';
$args['meta_query'] = array(
// Use an OR relationship between the query in this array and the one in
// the next array. (AND is the default.)
'relation' => 'OR',
// If an end_date exists, check that it is upcoming.
array(
'key' => 'end_date',
'compare' => '>=',
'value' => $current_date,
),
// OR!
array(
// If an end_date does not exist.
array(
// We use another, nested set of conditions, for if the end_date
// value is empty, OR if it is null/not set at all.
'relation' => 'OR',
array(
'key' => 'end_date',
'compare' => '=',
'value' => '',
),
array(
'key' => 'end_date',
'compare' => 'NOT EXISTS',
),
),
// AND, if the start date is upcoming.
array(
'key' => 'start_date',
'compare' => '>=',
'value' => $current_date,
),
),
);
$post_query = new WP_Query();
$posts_list = $post_query->query( $args );
// Only the "now" posts should be returned.
$this->assertSame(
array( $post_with_end_now, $post_empty_end_now, $post_null_end_now )
, $posts_list
);
}
}
``` |
256,760 | <p>I have a custom taxonomy, called albums.</p>
<p>I need to be able to text search the taxonomy term title, obviously this isn't default WP Search. Just wondering how I'd best tackle this? </p>
<p>Say there is an album called 'Football Hits',</p>
<p>I start typing foot and search that, all I need it to appear is the album title and the permalink.</p>
<p>Thanks!</p>
| [
{
"answer_id": 256764,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>So you can definitely search posts by taxonomy title - custom or otherwise. The answer will be in the \"<a h... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256760",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113513/"
] | I have a custom taxonomy, called albums.
I need to be able to text search the taxonomy term title, obviously this isn't default WP Search. Just wondering how I'd best tackle this?
Say there is an album called 'Football Hits',
I start typing foot and search that, all I need it to appear is the album title and the permalink.
Thanks! | ```
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');
``` |
256,777 | <pre><code><?php
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order'=> 'DESC', // sort descending
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();
printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title());
}
}
// Restore original post data.
wp_reset_postdata();
?>
</code></pre>
<p>This is the first time i've worked with wpquery.</p>
<p>Two questions</p>
<ol>
<li>how do i add a comma each item but the last?</li>
<li>How could i've written this better?</li>
</ol>
| [
{
"answer_id": 256764,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>So you can definitely search posts by taxonomy title - custom or otherwise. The answer will be in the \"<a h... | 2017/02/16 | [
"https://wordpress.stackexchange.com/questions/256777",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113103/"
] | ```
<?php
$args = array(
'post_type' => 'product',
'post_status' => 'publish',
'meta_key' => 'views',
'orderby' => 'meta_value_num',
'order'=> 'DESC', // sort descending
);
// Custom query.
$query = new WP_Query( $args );
// Check that we have query results.
if ( $query->have_posts() ) {
// Start looping over the query results.
while ( $query->have_posts() ) {
$query->the_post();
printf( '<a href="%s" class="link">%s</a>', get_permalink(), get_the_title());
}
}
// Restore original post data.
wp_reset_postdata();
?>
```
This is the first time i've worked with wpquery.
Two questions
1. how do i add a comma each item but the last?
2. How could i've written this better? | ```
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');
``` |
256,804 | <p>I'm using WP API to get posts in my application and I'm trying to exclude some posts from query using <code>filter[post__not_in]</code>.
after removing <code>filter</code> in WP <strong>4.7</strong>, I'm using <code>WP REST API filter parameter</code> plugin to get it back. and it works for all parameters but for <code>post__not_in</code> it's not effecting at all, I still get all posts.</p>
<p>I saw some closed issues about this on WP API repo on github, they said that <code>post__not_in</code> are not allowed for unauthenticated requests, I also found merged PR claimed that they fixed it, but I tried to use this function</p>
<pre><code>add_filter( 'query_vars', function( $vars ){
$vars[] = 'post__in';
$vars[] = 'post__not_in';
return $vars;
});
</code></pre>
<p>but now whatever I pass to <code>post__not_in</code> I get empty response</p>
<p>any ideas how to exclude post in WP API?</p>
| [
{
"answer_id": 256764,
"author": "nibnut",
"author_id": 111316,
"author_profile": "https://wordpress.stackexchange.com/users/111316",
"pm_score": 2,
"selected": false,
"text": "<p>So you can definitely search posts by taxonomy title - custom or otherwise. The answer will be in the \"<a h... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/52831/"
] | I'm using WP API to get posts in my application and I'm trying to exclude some posts from query using `filter[post__not_in]`.
after removing `filter` in WP **4.7**, I'm using `WP REST API filter parameter` plugin to get it back. and it works for all parameters but for `post__not_in` it's not effecting at all, I still get all posts.
I saw some closed issues about this on WP API repo on github, they said that `post__not_in` are not allowed for unauthenticated requests, I also found merged PR claimed that they fixed it, but I tried to use this function
```
add_filter( 'query_vars', function( $vars ){
$vars[] = 'post__in';
$vars[] = 'post__not_in';
return $vars;
});
```
but now whatever I pass to `post__not_in` I get empty response
any ideas how to exclude post in WP API? | ```
// We get a list taxonomies on the search box
function get_tax_by_search($search_text){
$args = array(
'taxonomy' => array( 'my_tax' ), // taxonomy name
'orderby' => 'id',
'order' => 'ASC',
'hide_empty' => true,
'fields' => 'all',
'name__like' => $search_text
);
$terms = get_terms( $args );
$count = count($terms);
if($count > 0){
echo "<ul>";
foreach ($terms as $term) {
echo "<li><a href='".get_term_link( $term )."'>".$term->name."</a></li>";
}
echo "</ul>";
}
}
// sample
get_tax_by_search('Foo');
``` |
256,819 | <p>So I have a css file :<br>
<a href="https://i.stack.imgur.com/eHgBm.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/eHgBm.png" alt="CSS File" /></a></p>
<p>I also have enqueued it, :
<a href="https://i.stack.imgur.com/dB2fV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/dB2fV.png" alt="Functions.php" /></a>
When I activate the theme, and try to view my page, no css is on it, Foundation is working, normalize is working, but not my css file, when I inspect element it's empty, and I don't know what I have to do.. ( The global.css source file in Inspect Element is empty, Foundation & normalize is not. )</p>
<p>Not allowed to post a 3rd link, but don't really think I need to show you a google chrome inspect element thing anyways..</p>
<p>Would really appriciate any help!</p>
| [
{
"answer_id": 256820,
"author": "Pedro Coitinho",
"author_id": 111122,
"author_profile": "https://wordpress.stackexchange.com/users/111122",
"pm_score": 2,
"selected": false,
"text": "<p>it looks like your forgot a slash before <code>css/global.css</code>. The others are fine.</p>\n\n<... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256819",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113551/"
] | So I have a css file :
[](https://i.stack.imgur.com/eHgBm.png)
I also have enqueued it, :
[](https://i.stack.imgur.com/dB2fV.png)
When I activate the theme, and try to view my page, no css is on it, Foundation is working, normalize is working, but not my css file, when I inspect element it's empty, and I don't know what I have to do.. ( The global.css source file in Inspect Element is empty, Foundation & normalize is not. )
Not allowed to post a 3rd link, but don't really think I need to show you a google chrome inspect element thing anyways..
Would really appriciate any help! | In a quick view, the arguments you use in [`wp_enqueue_style()`](https://developer.wordpress.org/reference/functions/wp_enqueue_style/) are not correct for global.css. The third parameter is used to declare the dependencies and you have set that parameter to the string `'false'` but it should be an array. If the CSS does not depend on another CSS, use an empty array.
In your case, I guess that the global.css depends on the other css you are lodaing (foundation, normalize, etc), so you should declare those dependencies.
You are using the fourth parameter incorrectly too. The fourth parameter is used to specified the version. `'all'` seems not a version. If you don't want to declare a version, use `null`, but I think it is good to declare the version in all the CSS files you are loading. For example, if you use some browser cache and update the foundation CSS, the upade won't be sent to the users that have the CSS already cached in their browsers. If you declare the version, the URL will change after the update and the users will get the new CSS version.
There is also a missing `/` in the URL (noted by Pedro in his answer).
```
wp_enqueue_style( 'venix_css', get_template_directory_uri() . '/css/global.css', array( 'normalize_css', 'foundation_css', 'googlefont_css' ), '1.0' );
```
Also, since WordPress 4.7, it is better if you use [`get_theme_file_uri()`](https://developer.wordpress.org/reference/functions/get_theme_file_uri/) instead of `get_template_directory_uri()`. The new function is more flexible and allows child themes to override parent theme files easily.
```
wp_enqueue_style( 'venix_css', get_theme_file_uri( 'css/global.css' ) , array( 'normalize_css', 'foundation_css', 'googlefont_css' ), '1.0' );
``` |
256,830 | <p>I am trying to programmatically add multiple images to media library, I uploaded the images to <code>wp-content/uploads</code>, now I try to use <code>wp_insert_attachement</code>.</p>
<p>Here's the code, however it's not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.</p>
<pre><code>$filename_array = array(
'article1.jpg',
'article2.jpg',
);
// The ID of the post this attachment is for.
$parent_post_id = 0;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach ($filename_array as $filename) {
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
</code></pre>
| [
{
"answer_id": 256834,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 6,
"selected": true,
"text": "<pre><code>$image_url = 'adress img';\n\n$upload_dir = wp_upload_dir();\n\n$image_data = file_get_contents( $im... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256830",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113564/"
] | I am trying to programmatically add multiple images to media library, I uploaded the images to `wp-content/uploads`, now I try to use `wp_insert_attachement`.
Here's the code, however it's not working as expected, I think metadata is not properly generated, I can see the files in media library, but without a thumbnail, also if I edit the image I get an error saying to re-upload the image.
```
$filename_array = array(
'article1.jpg',
'article2.jpg',
);
// The ID of the post this attachment is for.
$parent_post_id = 0;
// Get the path to the upload directory.
$wp_upload_dir = wp_upload_dir();
foreach ($filename_array as $filename) {
// Check the type of file. We'll use this as the 'post_mime_type'.
$filetype = wp_check_filetype( basename( $filename ), null );
// Prepare an array of post data for the attachment.
$attachment = array(
'guid' => $wp_upload_dir['url'] . '/' . basename( $filename ),
'post_mime_type' => $filetype['type'],
'post_title' => preg_replace( '/\.[^.]+$/', '', basename( $filename ) ),
'post_content' => '',
'post_status' => 'inherit'
);
// Insert the attachment.
$attach_id = wp_insert_attachment( $attachment, $filename, $parent_post_id );
// Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
require_once( ABSPATH . 'wp-admin/includes/image.php' );
// Generate the metadata for the attachment, and update the database record.
$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
wp_update_attachment_metadata( $attach_id, $attach_data );
}
``` | ```
$image_url = 'adress img';
$upload_dir = wp_upload_dir();
$image_data = file_get_contents( $image_url );
$filename = basename( $image_url );
if ( wp_mkdir_p( $upload_dir['path'] ) ) {
$file = $upload_dir['path'] . '/' . $filename;
}
else {
$file = $upload_dir['basedir'] . '/' . $filename;
}
file_put_contents( $file, $image_data );
$wp_filetype = wp_check_filetype( $filename, null );
$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_title' => sanitize_file_name( $filename ),
'post_content' => '',
'post_status' => 'inherit'
);
$attach_id = wp_insert_attachment( $attachment, $file );
require_once( ABSPATH . 'wp-admin/includes/image.php' );
$attach_data = wp_generate_attachment_metadata( $attach_id, $file );
wp_update_attachment_metadata( $attach_id, $attach_data );
``` |
256,833 | <p>What is the benefit of using (advantage/disadvantage) </p>
<pre><code>Organize my uploads into month- and year-based folders
</code></pre>
<p>option? Why would I want to organize my folder structure like this ? Is there SEO advantages ?</p>
<p>Thank you</p>
| [
{
"answer_id": 256835,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 2,
"selected": false,
"text": "<p>OMG, is there nothing else in the world except for SEO this days?</p>\n\n<p>Each OS has limitations and/o... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256833",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112778/"
] | What is the benefit of using (advantage/disadvantage)
```
Organize my uploads into month- and year-based folders
```
option? Why would I want to organize my folder structure like this ? Is there SEO advantages ?
Thank you | This is one of the many optional features in WordPress.There is no real benefit in using any of these 2 structures, but here is some details for you:
**Organization:**
When you are building a website which will have a lot of uploads, it is always a good option to go for the year / month structure. You might end up with 100,000 uploads in a single folder if you don't.
As you can imagine, sorting, reading and listing these files will get a long time. There was a time when old file systems used to support limited files in a single folder ( They still do now, but it's way more than before), so you had to make more folders to be able to save the images.
A website with 50K images and 5 thumbnail sizes will end up having 300k images in a single folder!
**SEO benefits**
There is no actual benefit of having a year / month structure on your files when it comes to SEO. Search engines have other tools to understand your contents, such as [Structured data](http://schema.org/) or HTML5 structure, which let's the search engine understand different parts of a page without using a MicroData structure.
**Custom templates - Security**
Some users (such as me) prefer to have their website deeply customized, including default folder names. I myself have changed the name all `wp-content`, `wp-admin`, `uploads` and `wp-includes` folder. Some directly, some through rewriting.
So the first moment a visitor visits the website, it's not easy to understand whether this website is powered by WordPress or not. It also makes it a bit more difficult for a newbie hacker to determine the CMS of the website.
However, with the year / month structure turned to ON, it needs one second to realize that this website is using WordPress to power up.
Although there are several ways to go around this, but still, some do prefer it.
There can be many other things added to this list, their all optional, such as the above list.
I hope this helps you decide what to choose about this. |
256,842 | <p>I added/enqueue a style inside shortcode, it works fine but loaded in footer (before starting the .js files) rather than header. I did the same way like this solution:</p>
<p><a href="https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present">Enqueue Scripts / Styles when shortcode is present</a></p>
<p>Is it normal in WP or how can I load style in header ?</p>
<p>Sample Code Here:</p>
<pre><code>class Cbwsppb_Related {
public function __construct()
{
add_shortcode('cbwsppb_related', array($this, 'shortcode_func'));
}
public function shortcode_func($atts, $content = null)
{
$atts = shortcode_atts( array(
'style' => '',
'display_style' => '',
'show' => '',
'orderby' => ''
), $atts );
if ($atts['display_style'] === 'carousel') {
wp_enqueue_style('flexslider-style');
}
$show = (!empty($atts['show'])) ? $atts['show'] : 2;
$orderby = (!empty($atts['orderby'])) ? $atts['orderby'] : 'rand';
$output = '';
ob_start();
if ($atts['style'] === 'custom') {
$output .= woocommerce_get_template( 'single-product/related.php', array(
'posts_per_page' => $show,
'orderby' => $orderby,
)
);
} else {
$output .= woocommerce_get_template( 'single-product/related.php');
}
$output .= ob_get_clean();
return $output;
}
}
</code></pre>
| [
{
"answer_id": 256845,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>Why it is added in the footer:</h1>\n<p>This is the expected behaviour.</p>\n<p>Since you have enqueued the ... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256842",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113570/"
] | I added/enqueue a style inside shortcode, it works fine but loaded in footer (before starting the .js files) rather than header. I did the same way like this solution:
[Enqueue Scripts / Styles when shortcode is present](https://wordpress.stackexchange.com/questions/165754/enqueue-scripts-styles-when-shortcode-is-present)
Is it normal in WP or how can I load style in header ?
Sample Code Here:
```
class Cbwsppb_Related {
public function __construct()
{
add_shortcode('cbwsppb_related', array($this, 'shortcode_func'));
}
public function shortcode_func($atts, $content = null)
{
$atts = shortcode_atts( array(
'style' => '',
'display_style' => '',
'show' => '',
'orderby' => ''
), $atts );
if ($atts['display_style'] === 'carousel') {
wp_enqueue_style('flexslider-style');
}
$show = (!empty($atts['show'])) ? $atts['show'] : 2;
$orderby = (!empty($atts['orderby'])) ? $atts['orderby'] : 'rand';
$output = '';
ob_start();
if ($atts['style'] === 'custom') {
$output .= woocommerce_get_template( 'single-product/related.php', array(
'posts_per_page' => $show,
'orderby' => $orderby,
)
);
} else {
$output .= woocommerce_get_template( 'single-product/related.php');
}
$output .= ob_get_clean();
return $output;
}
}
``` | Why it is added in the footer:
==============================
This is the expected behaviour.
Since you have enqueued the style ***within your Shortcode hook function***, by the time it executes, WordPress is already done generating the `<head>` section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.
So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.
How to add it in the header:
============================
If you want to output it in `<head>` section, you must enqueue it using:
```
function enqueue_your_styles() {
// the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function
wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );
```
>
> Note: this will add the style even if you don't have the shortcode in the page.
>
>
> Note-2: [One of the answers in the question you've mentioned](https://wordpress.stackexchange.com/a/165759/110572) already have a detailed explanation on alternatives and pros & cons.
>
>
> |
256,858 | <p>I'm using the following to show a menu</p>
<pre><code>if ( has_nav_menu( 'topheader' ) ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => 'topheader',
'menu_class' => 'topMenu', /* bootstrap ul */
'walker' => new My_Walker_Nav_Menu(), /* changes to a bootstrap class */
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'menu_id' => 'topMenu'
) );
}
</code></pre>
<p>If there are no links in the menu, nothing shows in the front-end. Is it possible to display a link to add a menu? Which takes the user to the menu location in dashboard.</p>
| [
{
"answer_id": 256845,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 2,
"selected": false,
"text": "<h1>Why it is added in the footer:</h1>\n<p>This is the expected behaviour.</p>\n<p>Since you have enqueued the ... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256858",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111086/"
] | I'm using the following to show a menu
```
if ( has_nav_menu( 'topheader' ) ) {
// User has assigned menu to this location;
// output it
wp_nav_menu( array(
'theme_location' => 'topheader',
'menu_class' => 'topMenu', /* bootstrap ul */
'walker' => new My_Walker_Nav_Menu(), /* changes to a bootstrap class */
'items_wrap' => '<ul id="%1$s" class="%2$s">%3$s</ul>',
'menu_id' => 'topMenu'
) );
}
```
If there are no links in the menu, nothing shows in the front-end. Is it possible to display a link to add a menu? Which takes the user to the menu location in dashboard. | Why it is added in the footer:
==============================
This is the expected behaviour.
Since you have enqueued the style ***within your Shortcode hook function***, by the time it executes, WordPress is already done generating the `<head>` section of your page, since WordPress will only execute your shortcode function once it has found the shortcode in your content.
So it has no other way than to place your style in the footer section if you enqueue style within the shortcode hook function.
How to add it in the header:
============================
If you want to output it in `<head>` section, you must enqueue it using:
```
function enqueue_your_styles() {
// the following line is just a sample, use the wp_enqueue_style line you've been using in the shortcode function
wp_enqueue_style( 'style-name', get_stylesheet_directory_uri() . '/css/your-style.css' );
}
add_action( 'wp_enqueue_scripts', 'enqueue_your_styles' );
```
>
> Note: this will add the style even if you don't have the shortcode in the page.
>
>
> Note-2: [One of the answers in the question you've mentioned](https://wordpress.stackexchange.com/a/165759/110572) already have a detailed explanation on alternatives and pros & cons.
>
>
> |
256,859 | <p>I want to query/list all the terms (from all the custom taxonomies) within a custom post type with their custom post count. This is what I have so far...</p>
<pre><code>$the_query = new WP_Query( array(
'post_type' => 'teacher',
'tax_query' => array(
array(
'taxonomy' => 'ALL CUSTOM TAXONOMIES',
'field' => 'id',
'terms' => 'ALL TERMS'
)
)
) );
$count = $the_query->found_posts;
$term_name = $the_query->get_term;
echo $term_name;
echo ' - ';
echo $count;
</code></pre>
| [
{
"answer_id": 256865,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>There is the built-in function to count the posts – <code>wp_count_posts()</code>. You can use it to count ... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256859",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37346/"
] | I want to query/list all the terms (from all the custom taxonomies) within a custom post type with their custom post count. This is what I have so far...
```
$the_query = new WP_Query( array(
'post_type' => 'teacher',
'tax_query' => array(
array(
'taxonomy' => 'ALL CUSTOM TAXONOMIES',
'field' => 'id',
'terms' => 'ALL TERMS'
)
)
) );
$count = $the_query->found_posts;
$term_name = $the_query->get_term;
echo $term_name;
echo ' - ';
echo $count;
``` | If the taxonomies in question are used ONLY in the post\_type in question, then the following simple function will do what you need:
```
function
count_term_use ($post_type)
{
$args = array (
'taxonomy' => get_object_taxonomies ($post_type, 'names'),
) ;
foreach (get_terms ($args) as $term) {
echo "$term->name - $term->count\n" ;
}
return ;
}
```
However, if a taxonomy is shared by multiple post\_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code. |
256,864 | <p>I'm trying to eliminate "mixed content" on my website and have done so with every area of the site except for one.</p>
<p>Any image uploaded via the Theme Customizer is not protocol relative nor https, all images uploaded via the customizer come up "http://". </p>
<p>The Customizer uses the Media Gallery uploader but doesn't seem to act in the same manner. If I upload an image to the media gallery (no customizer), place it into a page, WP knows whether or not to switch between http and https, although, when the same is attempted via the theme customizer function:</p>
<pre><code>$wp_customize->add_setting('slide_img_upload_one');
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'slide_img_upload_one', array(
'label' => __('Upload first image:', 'example_theme'),
'section' => 'carousel_slide_section',
'settings' => 'slide_img_upload_one',
'description' => 'Upload your first slider image here.'
)));
</code></pre>
<p>I can not get the <code>WP_Customize_Image_Control();</code> to output either "https" or a (best case scenario) protocol relative <code>//</code> url to the image for SSL compliance.</p>
<p>Some things to note. I'm not going to force SSL on my website so in Settings -> General; I'm not changing the url away from the http protocol.</p>
<p>I am also not looking for a way to use .htaccess to force this action. </p>
<p>Bottom line, there MUST be a way for images uploaded via the theme customizer to be protocol relative, I need some help figuring this one out though. I am currently running WP 4.6 (yes I know I'm a little behind).</p>
<p>Hopefully someone else has encountered this as hours of R&D have proved useless in trying to address something as specific as WordPress theme customizer func's.</p>
<p>Thanks in advance for any help, ideas, brainstorming... all ideas are welcome!</p>
<p>I am calling in the customizer function on the page using:</p>
<pre><code><a href="<?php echo esc_url(get_theme_mod('slide_one_link')); ?>"><img src="<?php echo esc_url( get_theme_mod( 'slide_img_upload_one' ) ); ?>" alt="<?php echo get_theme_mod( 'slide_title_1' ); ?>" /></a>
</code></pre>
<p>FYI: I have tried the solution here to no avail: <a href="https://wordpress.stackexchange.com/questions/79958/how-to-make-wordpress-use-protocol-indepentent-upload-files">Failed Attempt</a></p>
| [
{
"answer_id": 256865,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 0,
"selected": false,
"text": "<p>There is the built-in function to count the posts – <code>wp_count_posts()</code>. You can use it to count ... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256864",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/86752/"
] | I'm trying to eliminate "mixed content" on my website and have done so with every area of the site except for one.
Any image uploaded via the Theme Customizer is not protocol relative nor https, all images uploaded via the customizer come up "http://".
The Customizer uses the Media Gallery uploader but doesn't seem to act in the same manner. If I upload an image to the media gallery (no customizer), place it into a page, WP knows whether or not to switch between http and https, although, when the same is attempted via the theme customizer function:
```
$wp_customize->add_setting('slide_img_upload_one');
$wp_customize->add_control(new WP_Customize_Image_Control($wp_customize, 'slide_img_upload_one', array(
'label' => __('Upload first image:', 'example_theme'),
'section' => 'carousel_slide_section',
'settings' => 'slide_img_upload_one',
'description' => 'Upload your first slider image here.'
)));
```
I can not get the `WP_Customize_Image_Control();` to output either "https" or a (best case scenario) protocol relative `//` url to the image for SSL compliance.
Some things to note. I'm not going to force SSL on my website so in Settings -> General; I'm not changing the url away from the http protocol.
I am also not looking for a way to use .htaccess to force this action.
Bottom line, there MUST be a way for images uploaded via the theme customizer to be protocol relative, I need some help figuring this one out though. I am currently running WP 4.6 (yes I know I'm a little behind).
Hopefully someone else has encountered this as hours of R&D have proved useless in trying to address something as specific as WordPress theme customizer func's.
Thanks in advance for any help, ideas, brainstorming... all ideas are welcome!
I am calling in the customizer function on the page using:
```
<a href="<?php echo esc_url(get_theme_mod('slide_one_link')); ?>"><img src="<?php echo esc_url( get_theme_mod( 'slide_img_upload_one' ) ); ?>" alt="<?php echo get_theme_mod( 'slide_title_1' ); ?>" /></a>
```
FYI: I have tried the solution here to no avail: [Failed Attempt](https://wordpress.stackexchange.com/questions/79958/how-to-make-wordpress-use-protocol-indepentent-upload-files) | If the taxonomies in question are used ONLY in the post\_type in question, then the following simple function will do what you need:
```
function
count_term_use ($post_type)
{
$args = array (
'taxonomy' => get_object_taxonomies ($post_type, 'names'),
) ;
foreach (get_terms ($args) as $term) {
echo "$term->name - $term->count\n" ;
}
return ;
}
```
However, if a taxonomy is shared by multiple post\_type's then the above counts will reflect the total number of posts of any type that use the term, which is not what you're looking for. If that is true in your case, let me know and I'll post the more complicated (and expensive in terms of execution time/db queries) code. |
256,868 | <p>I'm attempting to add my logo to the middle of my navbar, and while looking at the nav walker class I couldn't figure what the best way to do this would be.</p>
<p>So my question is essentially how do I do that. the Walker_Nav_Menu() method start_el() seems to build only one li so where is it iterating over all of them and writing them to file. </p>
| [
{
"answer_id": 256882,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 0,
"selected": false,
"text": "<p>The best way to achieve the desired functionality, is to add a new menu item for the logo, by going to t... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256868",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/108441/"
] | I'm attempting to add my logo to the middle of my navbar, and while looking at the nav walker class I couldn't figure what the best way to do this would be.
So my question is essentially how do I do that. the Walker\_Nav\_Menu() method start\_el() seems to build only one li so where is it iterating over all of them and writing them to file. | You need to make your own walker menu (i am guessing you already know that), and the best way i think is overriding the function that `ends` each menu item which is `end_el` :
```
class logo_in_middle_Menu_Walker extends Walker_Nav_Menu {
public $menu_location = 'primary';
function __construct($menu_location_var) {
// parent class doesnt have a constructor so no parent::__construct();
$this->menu_location = $menu_location_var;
}
public function end_el(&$output, $item, $depth = 0, $args = array()) {
$locations = get_nav_menu_locations(); //get all menu locations
$menu = wp_get_nav_menu_object($locations[$this->menu_location]); //one menu for one location so lets get the menu of this location
$menu_items = wp_get_nav_menu_items($menu->term_id);
$top_lvl_menu_items_count = 0; //we need this to work with a menu with children too so we dont use simply $menu->count here
foreach ($menu_items as $menu_item) {
if ($menu_item->menu_item_parent == "0") {
$top_lvl_menu_items_count++;
}
}
$total_menu_items = $top_lvl_menu_items_count;
$item_position = $item->menu_order;
$position_to_have_the_logo = ceil($total_menu_items / 2);
if ($item_position == $position_to_have_the_logo && $item->menu_item_parent == "0") { //make sure we output for top level only
$output .= "</li>\n<img src='PATH_TO_YOUR_LOGO' alt='' />"; //here we add the logo
} else {
$output .= "</li>\n";
}
}
}
```
i am assuming that if its a menu with an uneven number of item say 5 the logo will be after the third element, also that this is only for top elements only.
you have to use it like this in the menu location:
```
<?php
wp_nav_menu(array(
'theme_location' => 'footer',
"walker" => new logo_in_middle_Menu_Walker('footer'),
));
?>
```
you have to supply the name of the theme location.
Here with 4 items:
[](https://i.stack.imgur.com/XG6wn.png)
Here with 5:
[](https://i.stack.imgur.com/KgMir.png) |
256,896 | <ol>
<li>I created a php class on a separate file</li>
<li>I included the file in functions.php</li>
<li>I initialized the class</li>
</ol>
<p>The class among many other things has one functions that does this:</p>
<pre><code>$data = array(
'time' => date('Y-m-d H:i:s'),
'offset' => 0,
);
$format = array(
'%s',
'%d'
);
$wpdb->insert('my_custom_table',$data,$format);
</code></pre>
<p>One page load the class runs, and for some reason I get 2 entries in the database instead of one. The data is correct, but I don't know why I have 2 entries if I only inserted once.</p>
<p>In my class $wpdb->insert only runs once. I can test that buy echoing anything right next to it.</p>
<p>troubleshooting:</p>
<p>So I removed $wpdb->insert outside the class and added directly to functions.php. I noticed that the $wpdb->insert was running 2 or more times.</p>
<p>What's causing it to run multiple times?</p>
<p>No, I don't have a loop.
Yes, I know I should not run it in functions.php, but it' for testing only.</p>
<p>I have found similar questions, but no good answer.</p>
| [
{
"answer_id": 256903,
"author": "Nathan Johnson",
"author_id": 106269,
"author_profile": "https://wordpress.stackexchange.com/users/106269",
"pm_score": 1,
"selected": false,
"text": "<p>It's hard to say why without seeing more of your code. So if you're interested in knowing why, then ... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256896",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/30984/"
] | 1. I created a php class on a separate file
2. I included the file in functions.php
3. I initialized the class
The class among many other things has one functions that does this:
```
$data = array(
'time' => date('Y-m-d H:i:s'),
'offset' => 0,
);
$format = array(
'%s',
'%d'
);
$wpdb->insert('my_custom_table',$data,$format);
```
One page load the class runs, and for some reason I get 2 entries in the database instead of one. The data is correct, but I don't know why I have 2 entries if I only inserted once.
In my class $wpdb->insert only runs once. I can test that buy echoing anything right next to it.
troubleshooting:
So I removed $wpdb->insert outside the class and added directly to functions.php. I noticed that the $wpdb->insert was running 2 or more times.
What's causing it to run multiple times?
No, I don't have a loop.
Yes, I know I should not run it in functions.php, but it' for testing only.
I have found similar questions, but no good answer. | It's hard to say why without seeing more of your code. So if you're interested in knowing why, then I'd encourage you to share more of your code.
If you're only looking for a solution, then something like the following will probably work. (I say probably because I don't know because I don't have your code.) What we want to do is make sure that the code to insert the table is executed once and only once. Because we're inserting the table on the `init` hook, the `register()` method will only fire once because `init` only fires once. So the conditional check is really unnecessary, but now we know for extra sure that the table will only be added once.
---
functions.php
```
require_once( PATH_TO . '/class-wpse106269.php' );
add_action( 'init', [ wpse106269::getInstance(), 'register' ] );
```
class-wpse106269.php
```
<?php
class wpse106269 {
private static $instance;
protected $table_already_inserted;
protected function __construct() {}
protected function __clone() {}
protected function __wakeup() {}
public static function getInstance() {
if( ! isset( self::$instance ) ) {
self::$instance = new self;
}
return self::$instance;
}
public function register() {
if( ! $table_already_inserted ) {
$this->insert_table();
$this->table_already_inserted = true;
}
}
protected function insert_table() {
//* Insert table here
}
```
---
Add:
I placed this in my functions.php with only ACF (free) active. The init hook only runs once. So this is either a problem with ACF (pro) or there's another plugin that's still active that doesn't play nicely with ACF (Pro?).
```
//* Don't access this file directly
defined( 'ABSPATH' ) or die();
add_action( 'init', [ new wpse106269(), 'init' ] );
class wpse106269{
protected $n = 1;
public function init() {
echo $this->n;
$this->n = 1 + $this->n;
}
}
``` |
256,897 | <p>Wondering if you might have some ideas on this problem. I’m googled for days but can’t figure it out. </p>
<p>Here’s where I’m at:</p>
<p>I have a meta box for the Woocommerce post type ‘products’. Inside the meta box there’s a <code>'type' = > 'select'</code> that I want to populate with a list of all of the available <code>'taxonomy' = > 'product_cat'</code>.</p>
<p>I can get the select box to populate and work with the standard post categories, <code>'taxonomy' = > 'category'</code> using the following code:</p>
<pre><code>function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'category' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
</code></pre>
<p>It all falls apart though when I try to use <code>‘taxonomy' = > ‘product_cat’</code> or any other custom taxonomy I have. </p>
<p>I thought the issue was that I’m trying to access the custom taxonomy before it’s being registered, so I swapped around some declarations/calls in my function.php file (ones which call the CPT, meta boxes, and woocommece) to potentially change the order that things run in but no luck.</p>
<p>BUT, based on the question and answer below, I can now confirm that the function can 'see' and display all terms, across taxonomies. If I exclude the <code>'taxonomy =></code> from the arguments it returns terms from across custom post types and taxonomies. </p>
<p>Ideally the basic function would read:</p>
<pre><code>function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'product_cat' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
</code></pre>
<p>Just wondering if you had any general thoughts? I know it’s difficult without seeing the whole code base, but I thought it would be worth an ask. </p>
<p>Wordpress Version 4.7.2</p>
<p>Woocommerce Version 2.6.14</p>
<p><strong>UPDATE:</strong></p>
<p>Slowly I'm trying to pinpoint my issue.</p>
<p>It appears that <code>'product_cat'</code> can be accessed after all (good) but it's spitting out an array that's not displaying properly. </p>
<p>This is confusing to me as if I simply use <code>get_terms()</code> without any parameters, or specifying <code>'taxonomy' => 'category'</code> the code above works flawlessly</p>
<p>The other pieces of code that I need to work with this are: </p>
<p><em>The array that I'd like the list of options to dump in to</em></p>
<pre><code> array(
'label'=> 'Collections',
'desc' => 'Select the collection you would like to display',
'id' => $prefix.'collection',
'type' => 'select',
'options' => product_cats()
),
</code></pre>
<p><em>the code which generates the select list (used for other meta fields)</em></p>
<pre><code>// select
case 'select':
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;
</code></pre>
<p>I have zero issues with any other meta fields working or displaying, including select lists. </p>
<p>I'd rather no re-write the entire meta box with all of its fields so I'm trying to work with what I have at the moment. </p>
| [
{
"answer_id": 256900,
"author": "Marinus Klasen",
"author_id": 113579,
"author_profile": "https://wordpress.stackexchange.com/users/113579",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably not gonna fix it, but wanted to share: I ran into the same issue today and this was... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256897",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113596/"
] | Wondering if you might have some ideas on this problem. I’m googled for days but can’t figure it out.
Here’s where I’m at:
I have a meta box for the Woocommerce post type ‘products’. Inside the meta box there’s a `'type' = > 'select'` that I want to populate with a list of all of the available `'taxonomy' = > 'product_cat'`.
I can get the select box to populate and work with the standard post categories, `'taxonomy' = > 'category'` using the following code:
```
function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'category' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
```
It all falls apart though when I try to use `‘taxonomy' = > ‘product_cat’` or any other custom taxonomy I have.
I thought the issue was that I’m trying to access the custom taxonomy before it’s being registered, so I swapped around some declarations/calls in my function.php file (ones which call the CPT, meta boxes, and woocommece) to potentially change the order that things run in but no luck.
BUT, based on the question and answer below, I can now confirm that the function can 'see' and display all terms, across taxonomies. If I exclude the `'taxonomy =>` from the arguments it returns terms from across custom post types and taxonomies.
Ideally the basic function would read:
```
function product_cats() {
$options = array();
$categories = get_terms( array( 'taxonomy' => 'product_cat' ) );
foreach( $categories as $category ) {
$options[$category->term_id] = array(
'label' => $category->name,
'value' => $category->slug
);
}
// return array('options'=>$options);
return $options;
}
```
Just wondering if you had any general thoughts? I know it’s difficult without seeing the whole code base, but I thought it would be worth an ask.
Wordpress Version 4.7.2
Woocommerce Version 2.6.14
**UPDATE:**
Slowly I'm trying to pinpoint my issue.
It appears that `'product_cat'` can be accessed after all (good) but it's spitting out an array that's not displaying properly.
This is confusing to me as if I simply use `get_terms()` without any parameters, or specifying `'taxonomy' => 'category'` the code above works flawlessly
The other pieces of code that I need to work with this are:
*The array that I'd like the list of options to dump in to*
```
array(
'label'=> 'Collections',
'desc' => 'Select the collection you would like to display',
'id' => $prefix.'collection',
'type' => 'select',
'options' => product_cats()
),
```
*the code which generates the select list (used for other meta fields)*
```
// select
case 'select':
echo '<select name="'.$field['id'].'" id="'.$field['id'].'">';
foreach ($field['options'] as $option) {
echo '<option', $meta == $option['value'] ? ' selected="selected"' : '', ' value="'.$option['value'].'">'.$option['label'].'</option>';
}
echo '</select><br /><span class="description">'.$field['desc'].'</span>';
break;
```
I have zero issues with any other meta fields working or displaying, including select lists.
I'd rather no re-write the entire meta box with all of its fields so I'm trying to work with what I have at the moment. | For the life of me I really want to get this working the *right way*. For the life of me I can't figure the integration out.
Previously I had looked at [`wp_dropdown_categories()`](https://codex.wordpress.org/Function_Reference/wp_dropdown_categories) and thought it was a better (and easier) solution. I landed working on the problem above because I couldn't figure out how to get it to working with the existing meta box syntax.
For now I've decided on the temporary fix found below. It's not ideal and certainly not the best way, but it allows me to move forward with calling the values in the templates that will utilize this field.
```
// Wrap all categories in a function
function product_cats() {
$output = array();
$categories = get_terms( array(
'orderby' => 'name',
'pad_counts' => false,
'hierarchical' => 1,
'hide_empty' => true,
) );
foreach( $categories as $category ) {
if ($category->taxonomy == 'product_cat' ) {
$output[$category->slug] = array(
'label' => $category->name,
'value' => $category->slug
);
}
}
//return array('options'=>$output);
return $output;
}
```
I'll update more as I move along. |
256,904 | <p>I migrated my wordpress, and the subscribe2 plugin
<a href="https://wordpress.org/plugins/subscribe2/installation/" rel="nofollow noreferrer">https://wordpress.org/plugins/subscribe2/installation/</a></p>
<p>looks different now. Before it has a text box with a placeholder, and then two buttons under saying subscribe and unsubscribe. The old plugin was version 4.16, and now the new version is 10.21. The way the new version looks like, is there is no input field or buttons. Rather it's just a sentence that says "you may manage your subscription options from your profile". And "profile" is a link.</p>
<p>Does anyone know how to get it to look like the old way?</p>
<p>Thanks</p>
| [
{
"answer_id": 256900,
"author": "Marinus Klasen",
"author_id": 113579,
"author_profile": "https://wordpress.stackexchange.com/users/113579",
"pm_score": 0,
"selected": false,
"text": "<p>This is probably not gonna fix it, but wanted to share: I ran into the same issue today and this was... | 2017/02/17 | [
"https://wordpress.stackexchange.com/questions/256904",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113339/"
] | I migrated my wordpress, and the subscribe2 plugin
<https://wordpress.org/plugins/subscribe2/installation/>
looks different now. Before it has a text box with a placeholder, and then two buttons under saying subscribe and unsubscribe. The old plugin was version 4.16, and now the new version is 10.21. The way the new version looks like, is there is no input field or buttons. Rather it's just a sentence that says "you may manage your subscription options from your profile". And "profile" is a link.
Does anyone know how to get it to look like the old way?
Thanks | For the life of me I really want to get this working the *right way*. For the life of me I can't figure the integration out.
Previously I had looked at [`wp_dropdown_categories()`](https://codex.wordpress.org/Function_Reference/wp_dropdown_categories) and thought it was a better (and easier) solution. I landed working on the problem above because I couldn't figure out how to get it to working with the existing meta box syntax.
For now I've decided on the temporary fix found below. It's not ideal and certainly not the best way, but it allows me to move forward with calling the values in the templates that will utilize this field.
```
// Wrap all categories in a function
function product_cats() {
$output = array();
$categories = get_terms( array(
'orderby' => 'name',
'pad_counts' => false,
'hierarchical' => 1,
'hide_empty' => true,
) );
foreach( $categories as $category ) {
if ($category->taxonomy == 'product_cat' ) {
$output[$category->slug] = array(
'label' => $category->name,
'value' => $category->slug
);
}
}
//return array('options'=>$output);
return $output;
}
```
I'll update more as I move along. |
256,930 | <p>I created a page template named custpage.php
I also created a separate css file named style2.css to style the custpage which has html and php code.
The page templates loads fine it shows under the page attributes but the css stylesheet doesn't seem to work.</p>
<p>This is what I did in functions.php</p>
<pre><code>function register_cust_style() {
if ( is_page_template( 'custpage.php' ) ) {
wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );
}
}
add_action( 'wp_enqueue_scripts', 'register_cust_style' );
</code></pre>
<p>The css file is inside vega/style2.css (where vega is name of the template directory).</p>
| [
{
"answer_id": 256936,
"author": "TrubinE",
"author_id": 111011,
"author_profile": "https://wordpress.stackexchange.com/users/111011",
"pm_score": 0,
"selected": false,
"text": "<p><code>'vega'</code> - must be unique name (example: 'vega-custpage-css')</p>\n\n<pre><code>wp_enqueue_style... | 2017/02/18 | [
"https://wordpress.stackexchange.com/questions/256930",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113620/"
] | I created a page template named custpage.php
I also created a separate css file named style2.css to style the custpage which has html and php code.
The page templates loads fine it shows under the page attributes but the css stylesheet doesn't seem to work.
This is what I did in functions.php
```
function register_cust_style() {
if ( is_page_template( 'custpage.php' ) ) {
wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );
}
}
add_action( 'wp_enqueue_scripts', 'register_cust_style' );
```
The css file is inside vega/style2.css (where vega is name of the template directory). | This will work only if your template is in the root folder, if its in a subdirectory you need to supply that too:
```
if ( is_page_template( 'template_folder_name/custpage.php' ) ) {
wp_enqueue_style( 'vega', get_stylesheet_directory_uri() . '/style2.css' );
}
``` |
256,967 | <p>My website has a logo and this logo have 2 states (i.e. online and offline ). Each of them has an image that will be uploaded to the media. What I am trying to achieve is that, when hovering on, the state of the logo changes (this can be done quite easy). However, in order to easily keep track of the logo image, I am thinking of allowing the theme to support custom_logo through add_theme_support. This works halfway, meaning I can only control 1 of the image at the moment. Are there any ways I can allow adding 2 different images from the theme customizing (custom logo) and display them? Thanks in advance</p>
| [
{
"answer_id": 256980,
"author": "EBennett",
"author_id": 91050,
"author_profile": "https://wordpress.stackexchange.com/users/91050",
"pm_score": 4,
"selected": true,
"text": "<p>I am assuming that by online and offline you mean active states of the logo. I think there are several option... | 2017/02/18 | [
"https://wordpress.stackexchange.com/questions/256967",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109824/"
] | My website has a logo and this logo have 2 states (i.e. online and offline ). Each of them has an image that will be uploaded to the media. What I am trying to achieve is that, when hovering on, the state of the logo changes (this can be done quite easy). However, in order to easily keep track of the logo image, I am thinking of allowing the theme to support custom\_logo through add\_theme\_support. This works halfway, meaning I can only control 1 of the image at the moment. Are there any ways I can allow adding 2 different images from the theme customizing (custom logo) and display them? Thanks in advance | I am assuming that by online and offline you mean active states of the logo. I think there are several options for you to use. The first two options can be used within your theme and then are simply changing the image file within the directory.
### Option One (not using WP):
You can utilise a simple use of transparancy. Apply a transparent effect to the logo and then on hover, make the opacity full. E.g:
```
.logo {
opacity: 0.75;
}
.logo:hover {
opacity: 1;
}
// If you want to use SASS:
.logo {
opacity: 0.75;
&:hover {
opacity: 1;
}
}
```
### Option Two (not using WP):
If you need to use imagery instead of an hover effect, then you can try the following (again using classes):
```
.logo {
background-image: url('path/to/your-off-image.jpg');
background-repeat: no-repeat;
background-size: cover;
width: 200px; // Have to set a width/height in order for the background to appear
height: 200px;
}
.logo:hover {
background-image: url('path/to/your-on-image.jpg');
background-repeat: no-repeat;
background-size: cover;
}
// If you want to use SASS:
.logo {
background-image: url('path/to/your-off-image.jpg');
background-repeat: no-repeat;
background-size: cover;
width: 200px; // Have to set a width/height in order for the background to appear
height: 200px;
&:hover {
background-image: url('path/to/your-on-image.jpg');
background-repeat: no-repeat;
background-size: cover;
}
}
```
### Option Three (using the customiser in WP):
*Taken from the [WP Customiser Docs](https://codex.wordpress.org/Theme_Customization_API#Adding_a_New_Setting)*
With this option you have to register the setting using the following:
```
function mytheme_customize_register( $wp_customize ) {
//All our sections, settings, and controls will be added here
$wp_customize->add_section( 'my_site_logo' , array(
'title' => __( 'My Site Logo', 'mytheme' ),
'priority' => 30,
) );
$wp_customize->add_control(
new WP_Customize_Image_Control(
$wp_customize,
'logo',
array(
'label' => __( 'Upload a logo', 'theme_name' ),
'section' => 'my_site_logo',
'settings' => 'my_site_logo_id'
)
)
);
}
add_action( 'customize_register', 'mytheme_customize_register' );
```
The above code would be added into the functions.php file that should be located within your theme directory. In order retrieve the image you do the following:
```
get_theme_mod( 'my_site_logo_id' );
```
And then you would have to break with convention of using inline-styling to output the two different options for the logos, on hover.
Please check out the codex to check over the various options you may have in order to achieve what you are after. |
256,976 | <p>I'm currently setting up a sidebar menu with multiple menus and sections. Each section with the title (the menu name) and a bunch of links underneath (the menu items) - I printed the items, but how do I print the menu name?</p>
<p>Thanks,</p>
<p>Jacob</p>
| [
{
"answer_id": 256979,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 5,
"selected": true,
"text": "<p>You can access the menu metadata using the <code>wp_get_nav_menu_object</code> function</p>\n\n<p>BY NAME... | 2017/02/18 | [
"https://wordpress.stackexchange.com/questions/256976",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94333/"
] | I'm currently setting up a sidebar menu with multiple menus and sections. Each section with the title (the menu name) and a bunch of links underneath (the menu items) - I printed the items, but how do I print the menu name?
Thanks,
Jacob | You can access the menu metadata using the `wp_get_nav_menu_object` function
BY NAME:
```
$menu = wp_get_nav_menu_object("my mainmenu" );
```
BY SLUG:
```
$menu = wp_get_nav_menu_object("my-mainmenu" );
```
The return object as follows:
```
Object (
term_id => 4
name => My Menu Name
slug => my-menu-name
term_group => 0
term_taxonomy_id => 4
taxonomy => nav_menu
description =>
parent => 0
count => 6
)
```
To display the name:
```
echo $menu->name;
``` |
257,024 | <p>The following code gives all posts from the network.
What I am trying to achieve :</p>
<ul>
<li>Select which blogs to display (by ID)</li>
<li>Select how many post to display (My code selects how many post <strong>per blog</strong>)</li>
<li><p>Order by date or random</p>
<pre><code>$blogs = get_last_updated();
foreach ($blogs AS $blog) {
switch_to_blog($blog["blog_id"]);
$lastposts = get_posts('numberposts=3');
foreach($lastposts as $post) : ?>
<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php endforeach;
restore_current_blog();
}
</code></pre></li>
</ul>
| [
{
"answer_id": 267876,
"author": "Rick Hellewell",
"author_id": 29416,
"author_profile": "https://wordpress.stackexchange.com/users/29416",
"pm_score": 2,
"selected": true,
"text": "<p>I created a plugin which does something similar (called Multisite Post Display <a href=\"https://wordpr... | 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257024",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/33719/"
] | The following code gives all posts from the network.
What I am trying to achieve :
* Select which blogs to display (by ID)
* Select how many post to display (My code selects how many post **per blog**)
* Order by date or random
```
$blogs = get_last_updated();
foreach ($blogs AS $blog) {
switch_to_blog($blog["blog_id"]);
$lastposts = get_posts('numberposts=3');
foreach($lastposts as $post) : ?>
<a href="<?php echo get_permalink(); ?>"><?php the_title(); ?></a></h3>
<?php endforeach;
restore_current_blog();
}
``` | I created a plugin which does something similar (called Multisite Post Display <https://wordpress.org/plugins/multisite-post-reader/> ) . It displays posts from all multisite sub-sites.
The code in there might be helpful for what you are doing. You are welcome to dig into it and use the code to help with your project. (After all, I used other people's code snippets to develop it.)
I wrote it after I did the Multisite Media Display, since I wanted a way to display media from subsites on one page, and couldn't find any plugin that did that. Both have been useful to monitor posted media and content from my multisite.
Free, open source, and all that. Hope it is helpful. |
257,046 | <p>I need to set a cookie based on a GET variable so my customers can get a coupon code on our site even if they move around after selecting the coupon link. </p>
<p>I am using the code here: <a href="https://www.gravityhelp.com/forums/topic/using-cookies-to-populate-forms#post-74281" rel="noreferrer">Gravity Help</a> to populate the coupon field based on the cookie. Just the second half of the code.</p>
<p>I need to set the coupon code in a cookie. There is a piece here: <a href="https://wordpress.stackexchange.com/questions/243170/setting-cookie-using-a-variable-from-the-url">Setting a Cookie using a variable from the URL</a> But I think that will also set an empty cookie if there is no variable which I think would over write the code if they user browses around the site. What would be the best way to make sure that function only runs if the variable is set?</p>
| [
{
"answer_id": 257051,
"author": "majick",
"author_id": 76440,
"author_profile": "https://wordpress.stackexchange.com/users/76440",
"pm_score": 1,
"selected": false,
"text": "<p>Yes you just need to wrap in an <code>isset</code> check before setting the cookie:</p>\n\n<pre><code>$name = ... | 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257046",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
] | I need to set a cookie based on a GET variable so my customers can get a coupon code on our site even if they move around after selecting the coupon link.
I am using the code here: [Gravity Help](https://www.gravityhelp.com/forums/topic/using-cookies-to-populate-forms#post-74281) to populate the coupon field based on the cookie. Just the second half of the code.
I need to set the coupon code in a cookie. There is a piece here: [Setting a Cookie using a variable from the URL](https://wordpress.stackexchange.com/questions/243170/setting-cookie-using-a-variable-from-the-url) But I think that will also set an empty cookie if there is no variable which I think would over write the code if they user browses around the site. What would be the best way to make sure that function only runs if the variable is set? | Just check if the variable is set, using the code from your link:
```
add_action( 'init', 'set_agent_cookie' );
function set_agent_cookie() {
if (isset($_GET['code'])) {
$name = 'agent';
$id = $_GET['code'];
setcookie( $name, $id, time() + 3600, "/", COOKIE_DOMAIN );
}
}
``` |
257,055 | <p>First time I faced this problem & trying to find out solution but it seems to me that it happens very few and that is why no more solution has been found like this & that is why I am here.</p>
<p>WordPress Import Message:</p>
<blockquote>
<p>File is empty. Please upload something more
substantial. This error could also be caused by uploads being disabled
in your <code>php.ini</code> or by <code>post_max_size</code> being defined as smaller than
<code>upload_max_filesize</code> in <code>php.ini</code>.</p>
</blockquote>
<p>I am getting above message when trying to import a previously imported file like the bellow image. Could you please tell me how to solve this?</p>
<p><a href="https://i.stack.imgur.com/4A1Qg.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/4A1Qg.jpg" alt="enter image description here"></a></p>
<p>I already tried to find the solution by googling but could not yet? </p>
| [
{
"answer_id": 257066,
"author": "Arsalan Mithani",
"author_id": 111402,
"author_profile": "https://wordpress.stackexchange.com/users/111402",
"pm_score": 3,
"selected": true,
"text": "<p>You need to increase the upload limit in your <code>php.ini</code>.</p>\n<p>To increase the maximum ... | 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257055",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113702/"
] | First time I faced this problem & trying to find out solution but it seems to me that it happens very few and that is why no more solution has been found like this & that is why I am here.
WordPress Import Message:
>
> File is empty. Please upload something more
> substantial. This error could also be caused by uploads being disabled
> in your `php.ini` or by `post_max_size` being defined as smaller than
> `upload_max_filesize` in `php.ini`.
>
>
>
I am getting above message when trying to import a previously imported file like the bellow image. Could you please tell me how to solve this?
[](https://i.stack.imgur.com/4A1Qg.jpg)
I already tried to find the solution by googling but could not yet? | You need to increase the upload limit in your `php.ini`.
To increase the maximum upload file size, open your php.ini file in the "`xampp/php/php.ini`" directory. search for `upload_max_filesize` and increase the value like :
```
upload_max_filesize = 128M
``` |
257,071 | <p>I need to get the ID posts for which the category(taxonomy "category") is not specified.
Post include other taxonomy.</p>
<p>I get posts from code:</p>
<pre><code>$posts = $wpdb->get_results('SELECT ...', , ARRAY_A);
</code></pre>
<p>My query selects the desired type of recording</p>
<pre><code>SELECT distinct posts.ID FROM wp_posts AS posts
LEFT JOIN wp_term_relationships AS cat_link ON
cat_link.object_id = posts.ID
LEFT JOIN wp_term_taxonomy AS cat_tax ON
cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
WHERE post_type = 'popular_music' AND post_status = 'publish' ORDER BY posts.ID DESC
</code></pre>
<p>But it is not considered:</p>
<pre><code>cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
</code></pre>
<p>How to select the record, Uncategorized?</p>
| [
{
"answer_id": 257072,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>The SQL you're after is something similar to this:</p>\n\n<pre><code>SELECT *\nFROM wp_posts AS post... | 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257071",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111011/"
] | I need to get the ID posts for which the category(taxonomy "category") is not specified.
Post include other taxonomy.
I get posts from code:
```
$posts = $wpdb->get_results('SELECT ...', , ARRAY_A);
```
My query selects the desired type of recording
```
SELECT distinct posts.ID FROM wp_posts AS posts
LEFT JOIN wp_term_relationships AS cat_link ON
cat_link.object_id = posts.ID
LEFT JOIN wp_term_taxonomy AS cat_tax ON
cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
WHERE post_type = 'popular_music' AND post_status = 'publish' ORDER BY posts.ID DESC
```
But it is not considered:
```
cat_link.term_taxonomy_id = cat_tax.term_taxonomy_id AND cat_tax.taxonomy NOT IN ('category')
```
How to select the record, Uncategorized? | If I understand the question, you're looking for the SQL for the equivalent of
```
$args = array (
'post_type' => 'popular_music',
'post_status' => 'publish',
'tax_query' => array (
array (
'taxonomy' => 'category',
'operator' => 'NOT EXISTS',
),
),
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'DESC',
) ;
$query = new WP_Query ($args) ;
echo $query->request ;
```
If so, then this is the SQL that WP\_Query produces
```
SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID
FROM
$wpdb->posts
WHERE
1=1 AND
(
NOT EXISTS
(
SELECT 1
FROM
$wpdb->term_relationships INNER JOIN
$wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
WHERE
$wpdb->term_taxonomy.taxonomy = 'category' AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
)
) AND
$wpdb->posts.post_type = 'popular_music' AND
(($wpdb->posts.post_status = 'publish'))
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.ID DESC
``` |
257,073 | <p>I need to parse widget content based on it's ID.</p>
<p>But a widget works like a function that pulls data based on it's arguments, right? So when I pull the widget data, I can only get it's arguments, not the actual output.</p>
<p>How can I parse the widget content based on it's ID?</p>
<p>Example code:</p>
<pre><code>// Update widget rounds automatically
function automatize_games_rounds($instance, $widget, $args){
// Check if there is a caption
if (isset($instance['caption']) && !empty($instance['caption'])) {
// If there is, does it contain the word "round"?
if (strpos(strtolower($instance['caption']), 'round')) {
// If yes, it's the kind of widget I'm looking for. Let's get it's ID.
$id = $args['widget_id'];
// Now I need to parse the widget output to do some stuff based on it's content, but how can I get the widget output?
}
}
return $instance;
}
add_filter('widget_display_callback','automatize_games_rounds',10,3);
</code></pre>
| [
{
"answer_id": 257072,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>The SQL you're after is something similar to this:</p>\n\n<pre><code>SELECT *\nFROM wp_posts AS post... | 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257073",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27278/"
] | I need to parse widget content based on it's ID.
But a widget works like a function that pulls data based on it's arguments, right? So when I pull the widget data, I can only get it's arguments, not the actual output.
How can I parse the widget content based on it's ID?
Example code:
```
// Update widget rounds automatically
function automatize_games_rounds($instance, $widget, $args){
// Check if there is a caption
if (isset($instance['caption']) && !empty($instance['caption'])) {
// If there is, does it contain the word "round"?
if (strpos(strtolower($instance['caption']), 'round')) {
// If yes, it's the kind of widget I'm looking for. Let's get it's ID.
$id = $args['widget_id'];
// Now I need to parse the widget output to do some stuff based on it's content, but how can I get the widget output?
}
}
return $instance;
}
add_filter('widget_display_callback','automatize_games_rounds',10,3);
``` | If I understand the question, you're looking for the SQL for the equivalent of
```
$args = array (
'post_type' => 'popular_music',
'post_status' => 'publish',
'tax_query' => array (
array (
'taxonomy' => 'category',
'operator' => 'NOT EXISTS',
),
),
'posts_per_page' => -1,
'orderby' => 'ID',
'order' => 'DESC',
) ;
$query = new WP_Query ($args) ;
echo $query->request ;
```
If so, then this is the SQL that WP\_Query produces
```
SELECT SQL_CALC_FOUND_ROWS $wpdb->posts.ID
FROM
$wpdb->posts
WHERE
1=1 AND
(
NOT EXISTS
(
SELECT 1
FROM
$wpdb->term_relationships INNER JOIN
$wpdb->term_taxonomy ON $wpdb->term_taxonomy.term_taxonomy_id = $wpdb->term_relationships.term_taxonomy_id
WHERE
$wpdb->term_taxonomy.taxonomy = 'category' AND
$wpdb->term_relationships.object_id = $wpdb->posts.ID
)
) AND
$wpdb->posts.post_type = 'popular_music' AND
(($wpdb->posts.post_status = 'publish'))
GROUP BY $wpdb->posts.ID
ORDER BY $wpdb->posts.ID DESC
``` |
257,085 | <p>When viewing the home page of my site (<a href="http://zilredloh.com" rel="nofollow noreferrer">zilredloh.com</a>), sometimes I do not see the latest posts. A new post will have been published, but the main index page doesn't reflect this. Refreshing the browser via F5 will then show the new content.</p>
<p>I know that browsers will sometimes cache content, but I have not encountered such a significant caching problem before for other sites. This issue seems to happen sporadically, and I've seen it occur while using different browsers and from different locations.</p>
<p>This morning, I opened up the site in Safari. The most recent post displayed was dated February 10. However, there were two posts made after this time - and they don't show up at all:</p>
<p><a href="https://avoision.com/dev/whb/Screen%20Shot%202017-02-19%20at%206.17.44%20AM.png" rel="nofollow noreferrer">Screenshot of Safari, Dev Tools</a></p>
<p>I know that if I refresh, or if I clear my browser cache - I will see the most recent content. That's not my issue. What I want to understand is where this caching is coming from in the first place. </p>
<p>In the screenshot above, I see a 200 Status for most assets requested. Some assets though (like Google Fonts, Google Analytics, and wp.pixel.com) are not cached. </p>
<p>Is this entirely due to the browser's cache? It seems unusually aggressive if so. I've reached out to my host (WebHostingBuzz), but they are telling me "There is no caching in cPanel by default." </p>
<ul>
<li>I have seen this sporadic issue in Chrome, Firefox, and Safari (Mac). </li>
<li>I am using a Child Theme, based off of a <a href="https://themeforest.net/item/writsy-a-clean-faded-vintage-wordpress-blog-theme/16106738" rel="nofollow noreferrer">custom theme</a>.</li>
<li>I have some plugins installed, but no cache-related plugins installed.</li>
</ul>
<p>I've made direct changes to my child theme's style.css file on the server, and after a refresh - those changes appear instantly and successfully. </p>
<p>Refreshing always seems to retrieve the latest and most recent files/posts, but on occasion when returning to the site... I seem to be getting a cached view. And I'm unclear why. </p>
<p>I would appreciate any suggestions or advice on where to focus my troubleshooting. </p>
<p>Thanks,
-Felix</p>
<hr>
<p>Traceroute results: <a href="https://avoision.com/dev/wpse/traceroute-zilredloh-local.png" rel="nofollow noreferrer">Local</a> vs. <a href="https://avoision.com/dev/wpse/traceroute-zilredloh-pingeu.png" rel="nofollow noreferrer">ping.eu</a></p>
| [
{
"answer_id": 257088,
"author": "Matt",
"author_id": 32255,
"author_profile": "https://wordpress.stackexchange.com/users/32255",
"pm_score": 0,
"selected": false,
"text": "<p>To narrow it down, perhaps try disabling cache in your browser. In Chrome - [Developer tools] > [Network] and ti... | 2017/02/19 | [
"https://wordpress.stackexchange.com/questions/257085",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112846/"
] | When viewing the home page of my site ([zilredloh.com](http://zilredloh.com)), sometimes I do not see the latest posts. A new post will have been published, but the main index page doesn't reflect this. Refreshing the browser via F5 will then show the new content.
I know that browsers will sometimes cache content, but I have not encountered such a significant caching problem before for other sites. This issue seems to happen sporadically, and I've seen it occur while using different browsers and from different locations.
This morning, I opened up the site in Safari. The most recent post displayed was dated February 10. However, there were two posts made after this time - and they don't show up at all:
[Screenshot of Safari, Dev Tools](https://avoision.com/dev/whb/Screen%20Shot%202017-02-19%20at%206.17.44%20AM.png)
I know that if I refresh, or if I clear my browser cache - I will see the most recent content. That's not my issue. What I want to understand is where this caching is coming from in the first place.
In the screenshot above, I see a 200 Status for most assets requested. Some assets though (like Google Fonts, Google Analytics, and wp.pixel.com) are not cached.
Is this entirely due to the browser's cache? It seems unusually aggressive if so. I've reached out to my host (WebHostingBuzz), but they are telling me "There is no caching in cPanel by default."
* I have seen this sporadic issue in Chrome, Firefox, and Safari (Mac).
* I am using a Child Theme, based off of a [custom theme](https://themeforest.net/item/writsy-a-clean-faded-vintage-wordpress-blog-theme/16106738).
* I have some plugins installed, but no cache-related plugins installed.
I've made direct changes to my child theme's style.css file on the server, and after a refresh - those changes appear instantly and successfully.
Refreshing always seems to retrieve the latest and most recent files/posts, but on occasion when returning to the site... I seem to be getting a cached view. And I'm unclear why.
I would appreciate any suggestions or advice on where to focus my troubleshooting.
Thanks,
-Felix
---
Traceroute results: [Local](https://avoision.com/dev/wpse/traceroute-zilredloh-local.png) vs. [ping.eu](https://avoision.com/dev/wpse/traceroute-zilredloh-pingeu.png) | You may need to set nocache headers in your main template header. Include this near the top of the header.php after the opening tag: `nocache_headers()`
From here: [Function Reference/nocache headers](https://codex.wordpress.org/Function_Reference/nocache_headers)
Run some tests, I believe this should only affect the main page file, other files should still cache normally.
More idealy, wordpress should be sending a last modified header with the home page. Hold on while I dig further into this.
Notice the cache-control max-age. As you can see, the cache has been set at 30 days. Meaning the browser will assume nothing has changed for 30 days unless the server sends a different header.
```
HTTP/1.1 200 OK
X-Powered-By: PHP/5.4.45
Cache-Control: public, max-age=2592000
Expires: Wed, 22 Mar 2017 01:15:09 GMT
Content-Type: text/html; charset=UTF-8
Link: <http://zilredloh.com/wp-json/>; rel="https://api.w.org/"
Link: <http://wp.me/1ZLfW>; rel=shortlink
Vary: Accept-Encoding
Date: Mon, 20 Feb 2017 01:15:09 GMT
Accept-Ranges: bytes
Server: LiteSpeed
Connection: close
Content-Length: 85258
```
After adding the code:
----------------------
Notice the second set of Cache Control and Expires.
```
HTTP/1.1 200 OK
X-Powered-By: PHP/5.4.45
Cache-Control: public, max-age=2592000
Expires: Wed, 22 Mar 2017 02:01:16 GMT
Content-Type: text/html; charset=UTF-8
Link: <http://zilredloh.com/wp-json/>; rel="https://api.w.org/"
Link: <http://wp.me/1ZLfW>; rel=shortlink
Expires: Wed, 11 Jan 1984 05:00:00 GMT
Cache-Control: no-cache, must-revalidate, max-age=0
Vary: Accept-Encoding
Date: Mon, 20 Feb 2017 02:01:16 GMT
Accept-Ranges: bytes
Server: LiteSpeed
Connection: close
Content-Length: 85258
``` |
257,105 | <p>I have a child theme where I'm using the old @import to import in the CSS and I know this is no longer best practice. I've seen on the Wordpress codex how to do this properly, which seems straightforward enough, but I need to find the $handle used in the parent theme when it registers its stylesheet.</p>
<p>This is the code they give:</p>
<pre><code><?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
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>
<p>How do I find out the parent theme's style.css $handle so i can swap it for 'parent-style' that is used above? (the theme I'm using is Divi, but I'd like to know how to find this because I do use other themes).</p>
<p>Thanks,</p>
<p>Emily</p>
| [
{
"answer_id": 257113,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 0,
"selected": false,
"text": "<p>That is not possible using a theme, you need to do it manually, or you will have to find a <code>plugin</... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257105",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I have a child theme where I'm using the old @import to import in the CSS and I know this is no longer best practice. I've seen on the Wordpress codex how to do this properly, which seems straightforward enough, but I need to find the $handle used in the parent theme when it registers its stylesheet.
This is the code they give:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
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' );
?>
```
How do I find out the parent theme's style.css $handle so i can swap it for 'parent-style' that is used above? (the theme I'm using is Divi, but I'd like to know how to find this because I do use other themes).
Thanks,
Emily | To clarify this, for anyone using Divi theme (but generally any WP theme), a simple inspection using Dev tools on the "head" for the stylesheet links usually gives a clue about the handle, as Den Isahac mentioned previously (it wasn't clear as he mentioned it can't be found).
**Anything before the "-css" on the ID of the link for the stylesheet of the Parent theme is generally that handle.**
Example below with Divi, id="divi-style-css" thus $handle = 'divi-style"
[](https://i.stack.imgur.com/kdPJU.jpg)
Thus for Divi, you would enqueue theme like this:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-style'; // This is 'twentyfifteen-style' for the Twenty Fifteen theme.
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' );
?>
```
Little bonus:
Browsers have an annoying tendency of caching the child stylesheet depending on its "Version". The drawback is that it prevents you from ever seeing your edits even after refreshing / clearing cache, unless you change the "Version" number in your css file after every edit.
You can change this behavior by swapping **wp\_get\_theme()->get('Version')** (the $ver parameter) for the handy **filemtime( get\_stylesheet\_directory() . '/style.css' )** instead, which adds a version number after the stylesheet corresponding to the timestamp from the last time you saved your child stylesheet, instead of the true "Version" declared in that stylesheet. You can eventually revert to the regular function before going live, but it can be extremely helpful during production.
The whole enqueue script for Divi would thus become:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'divi-style'; // This is 'Divi' style referrence for the Divi theme.
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 ),
filemtime( get_stylesheet_directory() . '/style.css' )
);
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
``` |
257,108 | <p>I want to remove the WordPress version from my Source Code. To achieve this, I have placed the following code in my functions.php file:</p>
<pre><code>function wordpress_remove_version() {
return '';
}
add_filter('the_generator', 'wordpress_remove_version');
</code></pre>
<p>This code has worked for me in the past but for some reason, the WordPress version is still appearing in my Source Code. </p>
<p>I have deactivated my Plugins but still with no success. Nor has trailing the internet for any updates on new codes etc. </p>
<p>Has anyone else got this problem or know of where may be going wrong? </p>
| [
{
"answer_id": 257109,
"author": "Milo",
"author_id": 4771,
"author_profile": "https://wordpress.stackexchange.com/users/4771",
"pm_score": 2,
"selected": false,
"text": "<p>Your code works for me in version 4.7.2 with 2016 theme, but a slightly simpler version is to remove the action en... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257108",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112472/"
] | I want to remove the WordPress version from my Source Code. To achieve this, I have placed the following code in my functions.php file:
```
function wordpress_remove_version() {
return '';
}
add_filter('the_generator', 'wordpress_remove_version');
```
This code has worked for me in the past but for some reason, the WordPress version is still appearing in my Source Code.
I have deactivated my Plugins but still with no success. Nor has trailing the internet for any updates on new codes etc.
Has anyone else got this problem or know of where may be going wrong? | I have figured out the problem!
For anyone reading this, my code does work perfectly fine. The issue lied within my functions.php file.
Rather than have the following in my file:
```
function theme_name_script_enqueue() {
wp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css', array(), '1.0', true );
}
add_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );
```
I had ...
```
function theme_name_script_enqueue() {
wp_enqueue_style( 'wpb-fa', get_template_directory_uri() . '/fonts/css/font-awesome.min.css' );
}
add_action( 'wp_enqueue_scripts', 'theme_name_script_enqueue' );
```
Note that I was missing `, array(), '1.0', true`
Once the above was inserted, all worked perfectly fine. |
257,111 | <p>In response to the <a href="https://wordpress.stackexchange.com/questions/257085/help-pinpointing-source-of-caching-issue">question asked here</a> I find myself and this other user needing a solution to set a last modified header that contains the date and time of the most reicent post. Since we both in many themes have the home page set to a static page and then coding our dynamic content into the static files we are missing that important header to make sure cached homepages update when there are new posts. </p>
<p>So, how can we set a last modified HTTP header on a page that it set to the most recent Post?</p>
| [
{
"answer_id": 257431,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>Untested, but it <em>should</em> work:</p>\n\n<pre><code>$query = \"SELECT MAX(post_modified) AS mod... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257111",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/70863/"
] | In response to the [question asked here](https://wordpress.stackexchange.com/questions/257085/help-pinpointing-source-of-caching-issue) I find myself and this other user needing a solution to set a last modified header that contains the date and time of the most reicent post. Since we both in many themes have the home page set to a static page and then coding our dynamic content into the static files we are missing that important header to make sure cached homepages update when there are new posts.
So, how can we set a last modified HTTP header on a page that it set to the most recent Post? | Last-Modified header for visitors on the front-page
---------------------------------------------------
It's useful to see how the *Last-Modified* header is added to the feeds, in the [`wp::send_header()`](https://github.com/WordPress/WordPress/blob/55df308b4d4ea733a3738d8c210ffb0ab0d7d7bf/wp-includes/class-wp.php#L399) method.
If we want to be able to use `is_front_page()`, then the filters `wp_headers` or `send_header` are probably applied to early.
We could instead use the `template_redirect` hook to target the front-page, before the headers are sent and after `is_front_page()` is ready.
Here's an example:
```
/**
* Set the Last-Modified header for visitors on the front-page
* based on when a post was last modified.
*/
add_action( 'template_redirect', function() use ( &$wp )
{
// Only visitors (not logged in)
if( is_user_logged_in() )
return;
// Target front-page
if( ! is_front_page() )
return;
// Don't add it if there's e.g. 404 error (similar as the error check for feeds)
if( ! empty( $wp->query_vars['error'] ) )
return;
// Don't override the last-modified header if it's already set
$headers = headers_list();
if( ! empty( $headers['last-modified'] ) )
return;
// Get last modified post
$last_modified = mysql2date( 'D, d M Y H:i:s', get_lastpostmodified( 'GMT' ), false );
// Add last modified header
if( $last_modified && ! headers_sent() )
header( "Last-Modified: " . $last_modified . ' GMT' );
}, 1 );
```
Here we used the core PHP functions [`header()`](http://php.net/manual/en/function.header.php), [`headers_list()`](http://php.net/manual/en/function.headers-list.php) and [`headers_sent()`](http://php.net/manual/en/function.headers-sent.php) and the WordPress core function [`get_lastpostmodified()`](https://developer.wordpress.org/reference/functions/get_lastpostmodified/)
The *Etag* header could be added here too as the *md5* of the last modified date.
We can then test it from the command line with e.g.:
```
# curl --head https://example.tld
```
or just use the shorthand parameter `-I` to only fetch the HTTP headers. |
257,114 | <p>I'm trying to get a thumbnail for my post. Like if the first custom meta box doesn't have any <code>value/content</code>, should use <code>}else if ($img =get_post_custom_values('backdrop_img')) { $imgsrc = $img[0]; }</code> (which is the 2nd metabox) then 3rd, <code>else if</code> it also doesn't have any <code>content/value</code> just use an image from my theme directory.</p>
<p>But my problem is, it only works on the first meta box, which is:</p>
<pre><code>if($img = get_post_custom_values('featured_img')){ $imgsrc = $img[0];
</code></pre>
<p>after that line the codes doesn't work and won't get values from 2nd custom meta box or use the defaul image if nothing from the conditions work.</p>
<p>I'm new to php and stil learning so i'm still confused. I'd appreciate any help.</p>
<p>So here's my code so far. </p>
<p>UPDATED: with the entire test code of the loop.</p>
<pre><code> <?php $year = date ("Y"); query_posts(array(get_option('year') => $year, 'posts_per_page' => 5, 'showposts' => 5)); ?>
<?php while (have_posts()) : the_post(); ?>
<?php if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'medium');
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
} else {
if($img = get_post_custom_values('featured_img')){
$imgsrc = $img[0];
}elseif($img = get_post_custom_values('backdrop_img')){
$imgsrc = $img;
} else {
$img = get_template_directory_uri().'/movies/no_img.png';
$imgsrc = $img;
}
} ?>
<div class="post_content">
<img src="<?php echo $imgsrc; $imgsrc = ''; ?>
<a href="<?php the_permalink() ?>" class="slide-link" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<p class="sc-desc"> <?php the_excerpt(); ?></p>
</div>
<?php } endwhile; ?>
</code></pre>
| [
{
"answer_id": 257116,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing the <code>$post ID</code>:</p>\n\n<pre><code> <?php\n //lets put the def... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257114",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110405/"
] | I'm trying to get a thumbnail for my post. Like if the first custom meta box doesn't have any `value/content`, should use `}else if ($img =get_post_custom_values('backdrop_img')) { $imgsrc = $img[0]; }` (which is the 2nd metabox) then 3rd, `else if` it also doesn't have any `content/value` just use an image from my theme directory.
But my problem is, it only works on the first meta box, which is:
```
if($img = get_post_custom_values('featured_img')){ $imgsrc = $img[0];
```
after that line the codes doesn't work and won't get values from 2nd custom meta box or use the defaul image if nothing from the conditions work.
I'm new to php and stil learning so i'm still confused. I'd appreciate any help.
So here's my code so far.
UPDATED: with the entire test code of the loop.
```
<?php $year = date ("Y"); query_posts(array(get_option('year') => $year, 'posts_per_page' => 5, 'showposts' => 5)); ?>
<?php while (have_posts()) : the_post(); ?>
<?php if (has_post_thumbnail()) {
$imgsrc = wp_get_attachment_image_src(get_post_thumbnail_id($post->ID),'medium');
$imgsrc = $imgsrc[0];
} elseif ($postimages = get_children("post_parent=$post->ID&post_type=attachment&post_mime_type=image&numberposts=0")) {
foreach($postimages as $postimage) {
$imgsrc = wp_get_attachment_image_src($postimage->ID, 'medium');
$imgsrc = $imgsrc[0];
}
} elseif (preg_match('/<img [^>]*src=["|\']([^"|\']+)/i', get_the_content(), $match) != FALSE) {
$imgsrc = $match[1];
} else {
if($img = get_post_custom_values('featured_img')){
$imgsrc = $img[0];
}elseif($img = get_post_custom_values('backdrop_img')){
$imgsrc = $img;
} else {
$img = get_template_directory_uri().'/movies/no_img.png';
$imgsrc = $img;
}
} ?>
<div class="post_content">
<img src="<?php echo $imgsrc; $imgsrc = ''; ?>
<a href="<?php the_permalink() ?>" class="slide-link" title="<?php the_title(); ?>"><?php the_title(); ?></a>
<p class="sc-desc"> <?php the_excerpt(); ?></p>
</div>
<?php } endwhile; ?>
``` | Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing `[0]` in `$imgsrc = $img[0];` and using `custom_get_meta()`
like:
`$img = post_movie_get_meta('featured_img')`
and:
`$img = post_movie_get_meta('backdrop_img')` |
257,135 | <p>I am using the loop in my custom page template as you can see in my code. Only 2 posts must be shown and for the rest I should be able to have pagination.</p>
<pre><code><?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(
array (
'posts_per_page' => 2,
'post_type' => 'post',
'category_name' => 'news',
'category' => 1,
'paged' => $paged )
);
// The Loop
while ( have_posts() ) : the_post();?>
<div class="news-page-content-wrapper">
<div class="news-page-content">
<h1><a class="read-more"href="<?php the_permalink(); ?>"><?php the_title();?></a></h1>
<figure><?php the_post_thumbnail(); ?></figure>
<p><?php echo get_the_excerpt();?></p>
<a href="<?php the_permalink(); ?>">Read More&raquo</a>
</div>
</div>
<?endwhile;
// Reset Query
wp_reset_query();
?>
<?php next_posts_link(); ?>
<?php previous_posts_link(); ?>
</code></pre>
<p>How can I have pagination using the loop with category ID?</p>
| [
{
"answer_id": 257116,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing the <code>$post ID</code>:</p>\n\n<pre><code> <?php\n //lets put the def... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257135",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99178/"
] | I am using the loop in my custom page template as you can see in my code. Only 2 posts must be shown and for the rest I should be able to have pagination.
```
<?php
$paged = (get_query_var('paged')) ? get_query_var('paged') : 1;
query_posts(
array (
'posts_per_page' => 2,
'post_type' => 'post',
'category_name' => 'news',
'category' => 1,
'paged' => $paged )
);
// The Loop
while ( have_posts() ) : the_post();?>
<div class="news-page-content-wrapper">
<div class="news-page-content">
<h1><a class="read-more"href="<?php the_permalink(); ?>"><?php the_title();?></a></h1>
<figure><?php the_post_thumbnail(); ?></figure>
<p><?php echo get_the_excerpt();?></p>
<a href="<?php the_permalink(); ?>">Read More»</a>
</div>
</div>
<?endwhile;
// Reset Query
wp_reset_query();
?>
<?php next_posts_link(); ?>
<?php previous_posts_link(); ?>
```
How can I have pagination using the loop with category ID? | Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing `[0]` in `$imgsrc = $img[0];` and using `custom_get_meta()`
like:
`$img = post_movie_get_meta('featured_img')`
and:
`$img = post_movie_get_meta('backdrop_img')` |
257,153 | <p>I'm at a loss.. </p>
<p>I wanna check the current users post count. If the post count is 1, the user should be redirected. I have tested the following code:</p>
<pre><code>add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
$current_user = wp_get_current_user();
if (empty($the_user_id)) {
$the_user_id = $current_user->ID;
}
$user_post_count = count_user_posts( $the_user_id );
if ( is_page('butiktest') && $user_post_count == 1 ) {
wp_redirect( 'enhytte', 301 );
exit;
}
}
</code></pre>
<p>However, the above code will redirect no matter the amount of posts.</p>
<p>What am I doing wrong?</p>
<p>EDIT: After pointing out my syntax error was a missing "=", it is still not working.</p>
<p>EDIT 2: The code is in theory working, however, once a post is added, the <code>user_post_count</code> is not updated, and stays at the previous value. </p>
<p>EDIT3: count_user_posts only count published posts, how do I check for 'pending' and 'draft'?</p>
| [
{
"answer_id": 257116,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p>I think you are missing the <code>$post ID</code>:</p>\n\n<pre><code> <?php\n //lets put the def... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257153",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112830/"
] | I'm at a loss..
I wanna check the current users post count. If the post count is 1, the user should be redirected. I have tested the following code:
```
add_action( 'template_redirect', 'redirect_to_specific_page' );
function redirect_to_specific_page() {
$current_user = wp_get_current_user();
if (empty($the_user_id)) {
$the_user_id = $current_user->ID;
}
$user_post_count = count_user_posts( $the_user_id );
if ( is_page('butiktest') && $user_post_count == 1 ) {
wp_redirect( 'enhytte', 301 );
exit;
}
}
```
However, the above code will redirect no matter the amount of posts.
What am I doing wrong?
EDIT: After pointing out my syntax error was a missing "=", it is still not working.
EDIT 2: The code is in theory working, however, once a post is added, the `user_post_count` is not updated, and stays at the previous value.
EDIT3: count\_user\_posts only count published posts, how do I check for 'pending' and 'draft'? | Thanks everyone for all the help! I really appreciate it. I was able to make it work by removing `[0]` in `$imgsrc = $img[0];` and using `custom_get_meta()`
like:
`$img = post_movie_get_meta('featured_img')`
and:
`$img = post_movie_get_meta('backdrop_img')` |
257,189 | <p>So right now the site automatically creates pages when a post is updated. I want this page to include an audio playlist. So what I do, is simply add the shortcode: <code>[playlist]</code>.
Then, when the audio files are attached to the page, the playlist automatically generates.</p>
<p>I can confirm that this method works with specified IDs.</p>
<p><strong>The problem is</strong>, that 3 different pages are made, and I need the audio to be attached to all three pages. So my solution is that I make a another page, set the audio files as children to that page, and make the original 3 pages children of the new page. Then I could use the <code>[playlist]</code> shortcode, but tell it to get the id from the parent page.</p>
<p><strong>Example:</strong></p>
<pre><code>[playlist id="<?php get_parent_id ?>"]
</code></pre>
<p>or something like this.</p>
<p>The problem is that I cannot get the parent id. I've tried multiple different lines of code and nothing will work. The playlist just gets the default 0 ID, which it does when <code>id=""</code> is left blank.</p>
<p>This is all going into the <code>functions.php</code> file in my theme's directory.</p>
<p>--</p>
<p>Maybe there is a better way to do this, thusfar, this seems like the simplest solution, if only I can get the direct parent ID. It must exist.</p>
| [
{
"answer_id": 276771,
"author": "Shahzaib Khan",
"author_id": 125791,
"author_profile": "https://wordpress.stackexchange.com/users/125791",
"pm_score": 0,
"selected": false,
"text": "<p>There are multiple ways you can do this:</p>\n\n<ul>\n<li>Manual</li>\n<li>Using plugin</li>\n</ul>\n... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257189",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113483/"
] | So right now the site automatically creates pages when a post is updated. I want this page to include an audio playlist. So what I do, is simply add the shortcode: `[playlist]`.
Then, when the audio files are attached to the page, the playlist automatically generates.
I can confirm that this method works with specified IDs.
**The problem is**, that 3 different pages are made, and I need the audio to be attached to all three pages. So my solution is that I make a another page, set the audio files as children to that page, and make the original 3 pages children of the new page. Then I could use the `[playlist]` shortcode, but tell it to get the id from the parent page.
**Example:**
```
[playlist id="<?php get_parent_id ?>"]
```
or something like this.
The problem is that I cannot get the parent id. I've tried multiple different lines of code and nothing will work. The playlist just gets the default 0 ID, which it does when `id=""` is left blank.
This is all going into the `functions.php` file in my theme's directory.
--
Maybe there is a better way to do this, thusfar, this seems like the simplest solution, if only I can get the direct parent ID. It must exist. | Why images don't get imported
=============================
It's the export step that causes the issue here with image attachments. WordPress’ export function doesn’t include the “attachment” post type unless you select the “All content” export option. But if you only want to import and export your posts from one site to another, you lose your attachments. There is more information about the why of this [here](https://mor10.com/wordpress-importer-not-importing-attachments-try-exporting-all-statuses/#comment-1151023).
How to get images into your new website anyway
==============================================
So if you're only exporting and importing posts, one option is to move your images manually. But that's potentially a lot of work, especially on larger sites. The other option is to import you posts without the images, and then use the [Auto Upload Images plugin](https://wordpress.org/plugins/auto-upload-images/) to add the images afterwards. This plugin does several things:
* It looks for image URLs in your posts (imported posts do still have image URLs in them, but they point to the site the content was exported from);
* It then gets those external images and uploads them to the local WordPress uploads directory and adds the images to the media library;
* And finally, it replaces the old image URLs with new URLs.
The process is semi-automatic and relatively quick. You can uninstall the plugin again when you're done, so you're not left with an extra plugin on your website. Using the plugin for this purpose isn't explicitly documented in the plugin's documentation, so here is a step-by-step guide.
Step by step: Importing posts and images from one website into another with the WordPress Importer and Auto Upload Images plugin
--------------------------------------------------------------------------------------------------------------------------------
**Step 1: Prepare your export file on the old site**
On your old website go to 'Tools > Export' and export your posts only.
**Step 2: Import your posts into the new site**
On your new website go to 'Tools > Import' and import the posts you exported. The importer has an option to download and import file attachments, but this won't work if you're not migrating all content, so you can ignore this.
**Step 3: Install and activate the Auto Upload Images plugin**
It installs as any other plugin in the WordPress repository. Once activated the plugin adds a settings page under 'Settings > Auto Upload Images', but in my experience you can leave these to their defaults.
**Step 4: Get the image from your old site into your new site**
At the time of writing the plugin has no option to automatically go through your posts and bulk upload plus update all the images. Instead, it updates each post individually when you save it. If you have many posts this is a lot of work, but there is a little trick. You can go to your posts overview screen and *bulk update your posts*. There is a little more information on this [here](https://wordpress.org/support/topic/why-no-option-to-run-this-in-bulk-on-all-existing-posts/) (useful note on multisite).
Essentially, you select multiple posts and then under 'bulk actions' choose 'edit' and press the 'apply' button. Then, without making any adjustments, click the 'Update' button. Depending on your server you may get a timeout as the process runs, so it's a good idea to do this maybe 20 to 50 posts at a time.
[](https://i.stack.imgur.com/DKzjs.png)
**Step 5: Check your posts and deactivate/uninstall the plugin**
When all is done you can check your posts and confirm they now reference local images. You then no longer need the plugin and you can safely deactivate and delete it.
Final thoughts
==============
Probably a good idea to make a backup of your new site first (at least of your site's database).
At the time of writing the Auto Upload Images plugin hasn't been updated for quite some time, but on testing it worked fine.
With this method all images in posts get imported, not just featured images. |
257,227 | <p>I created a custom post type for WP, that should just be visitable for user that have a custom capability <code>read_cpt</code>. Within templates and <code>pre_get_posts</code> I can run checks to include or exclude the CPT by using <code>current_user_can()</code>.</p>
<p>I don't want the CPT, not even the endpoint, to show up within the REST API, to keep it top secret, as long as a user doesn't have the custom capability.</p>
<p>The only way I could figure out to hide the endpoints in the API to run this code.</p>
<p>Register post type for "classic" WP:</p>
<pre><code>function add_post_type() {
$args = array(
[...]
'public' => false,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_in_rest' => false,
);
register_post_type( 'cpt', $args );
}
add_action( 'init', 'add_post_type', 0 );
</code></pre>
<p>and separately add it to the REST API:</p>
<pre><code>add_action( 'init', 'cpt_rest_support', 25 );
function cpt_rest_support() {
global $wp_post_types;
if ( current_user_can( 'read_addresses' ) ) {
//be sure to set this to the name of your post type!
$post_type_name = 'address';
if( isset( $wp_post_types[ 'cpt' ] ) ) {
$wp_post_types[ 'cpt' ]->show_in_rest = true;
}
}
}
</code></pre>
<p>By creating a custom <code>WP_REST_Posts_Controller</code> class I couldn't find a way to hide the endpoint by modifying any of the <code>*_permissions_check</code></p>
<p>Is there something like a "show_in_rest_permition_check" argument for <code>register_post_type()</code> or is the described way the only method?</p>
| [
{
"answer_id": 257250,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>The REST API has no parameters, options to solve this - in my opinion. But you should register only if the users ... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257227",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45303/"
] | I created a custom post type for WP, that should just be visitable for user that have a custom capability `read_cpt`. Within templates and `pre_get_posts` I can run checks to include or exclude the CPT by using `current_user_can()`.
I don't want the CPT, not even the endpoint, to show up within the REST API, to keep it top secret, as long as a user doesn't have the custom capability.
The only way I could figure out to hide the endpoints in the API to run this code.
Register post type for "classic" WP:
```
function add_post_type() {
$args = array(
[...]
'public' => false,
'has_archive' => false,
'exclude_from_search' => true,
'publicly_queryable' => false,
'show_in_rest' => false,
);
register_post_type( 'cpt', $args );
}
add_action( 'init', 'add_post_type', 0 );
```
and separately add it to the REST API:
```
add_action( 'init', 'cpt_rest_support', 25 );
function cpt_rest_support() {
global $wp_post_types;
if ( current_user_can( 'read_addresses' ) ) {
//be sure to set this to the name of your post type!
$post_type_name = 'address';
if( isset( $wp_post_types[ 'cpt' ] ) ) {
$wp_post_types[ 'cpt' ]->show_in_rest = true;
}
}
}
```
By creating a custom `WP_REST_Posts_Controller` class I couldn't find a way to hide the endpoint by modifying any of the `*_permissions_check`
Is there something like a "show\_in\_rest\_permition\_check" argument for `register_post_type()` or is the described way the only method? | The REST API has no parameters, options to solve this - in my opinion. But you should register only if the users have the capability in his role, like the follow example.
```
add_action( 'rest_api_init', function() {
// Exit, if the logged in user have not enough rights.
if ( ! current_user_can( 'edit_posts' ) ) {
return;
}
// Register Meta Data.
register_meta( 'post', 'foo', array(
'show_in_rest' => true,
));
});
```
That's fire the custom data in the REST API only, if the user have enough rights, capabilities in his role. My `register_meta()` is only an example, that should also work with your additional parameter for `register_post_type`, like `$wp_post_types[ 'cpt' ]->show_in_rest = true;`. |
257,235 | <p>After running my Wordpress site through Page Speed Insights I'm told that I need to eliminate render blocking javascript.
So I have moved the vast majority of javascript to just before the closing body tag but the warning still appears in Page Speed Insights.</p>
<p>Can anyone suggest what I can do to resolve this issue please?</p>
<p>The site is <a href="http://www.stewartandsonsroofingliverpool.co.uk/" rel="nofollow noreferrer">http://www.stewartandsonsroofingliverpool.co.uk/</a></p>
<p>Thanks in advance</p>
| [
{
"answer_id": 257238,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to y... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257235",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/46039/"
] | After running my Wordpress site through Page Speed Insights I'm told that I need to eliminate render blocking javascript.
So I have moved the vast majority of javascript to just before the closing body tag but the warning still appears in Page Speed Insights.
Can anyone suggest what I can do to resolve this issue please?
The site is <http://www.stewartandsonsroofingliverpool.co.uk/>
Thanks in advance | You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your `functions.php` to load your scripts asynchronously.
This can get you started,
>
> Warning
>
>
>
loading JavaScript asynchronously will cause several issues with dependencies:
```
/*function to add async to all scripts*/
function js_async_attr($tag){
//Add async to all scripts tags
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
```
so you have to check your JS code and update it. |
257,240 | <p>I'm loading a list of products on an archive type page and creating a custom query to do so. I want to create a 'load more' functionality so that clicking the 'load more' button at the bottom of list loads the next 10 products.</p>
<p>I thought it would be as easy as using a variable to set 'posts_per_page' and simply increment it by 10 when the button is clicked. I get strange results however. This code is not the final code but just to illustrate this problem.</p>
<pre><code>if(isset( $_POST['load-next-amount'] )){
$pageamount = 10
}
else {
$pageamount = 5;
}
</code></pre>
<p>So the first time this is loaded it resolves to false because the button hasny't yet been clicked, so posts_per_page will be set to 5. Then when clicking the button, you would expect 10 to load but for some reason it continues to load 5. If however I change the code to this:</p>
<pre><code>if(isset( $_POST['load-next-amount'] )){
$pageamount = 4
}
else {
$pageamount = 5;
}
</code></pre>
<p>it will load 4. So I cannot increase the amount of posts_per_page through this variable, but I can decrease it. Strange.</p>
<p>Here is my query:</p>
<pre><code>$myArgs = array(
'category' => '',
'category_name' => '',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'include' => '',
'exclude' => '',
'meta_key' => '_price_per_1hr_lesson',
'meta_value' => '',
'post_type' => 'job_listing',
'post_mime_type' => '',
'post_parent' => '',
'post__in' => $what,
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'job_listing_region' => "'" . $city . "'",
'post_status' => 'publish',
'posts_per_page' => $pageamount,
'suppress_filters' => true
);
$myquery = new WP_Query( $myArgs );
</code></pre>
<p>UPDATE: using print_r I can see that the correct value is being assigned to the variable and that value is being correctly assigned to 'posts_per_page'. For whatever reason, it ignores it UNLESS it is LESS than the previously assigned value. For instance if I set the else statement to $pageamount = 20, the first time the page loads there will be 20, then if i click the button(sending the variable to the script which is 10) it will load 10. It will load any number of posts I hard code as long as it's less than 20. </p>
<p>Obviously there is something in WP that is setting a default or something. Still a bit of a newb to WP so I don't know. Looking at wp_config and I dont' see anything.</p>
| [
{
"answer_id": 257238,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to y... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257240",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113232/"
] | I'm loading a list of products on an archive type page and creating a custom query to do so. I want to create a 'load more' functionality so that clicking the 'load more' button at the bottom of list loads the next 10 products.
I thought it would be as easy as using a variable to set 'posts\_per\_page' and simply increment it by 10 when the button is clicked. I get strange results however. This code is not the final code but just to illustrate this problem.
```
if(isset( $_POST['load-next-amount'] )){
$pageamount = 10
}
else {
$pageamount = 5;
}
```
So the first time this is loaded it resolves to false because the button hasny't yet been clicked, so posts\_per\_page will be set to 5. Then when clicking the button, you would expect 10 to load but for some reason it continues to load 5. If however I change the code to this:
```
if(isset( $_POST['load-next-amount'] )){
$pageamount = 4
}
else {
$pageamount = 5;
}
```
it will load 4. So I cannot increase the amount of posts\_per\_page through this variable, but I can decrease it. Strange.
Here is my query:
```
$myArgs = array(
'category' => '',
'category_name' => '',
'orderby' => 'meta_value_num',
'order' => 'ASC',
'include' => '',
'exclude' => '',
'meta_key' => '_price_per_1hr_lesson',
'meta_value' => '',
'post_type' => 'job_listing',
'post_mime_type' => '',
'post_parent' => '',
'post__in' => $what,
'author' => '',
'author_name' => '',
'post_status' => 'publish',
'job_listing_region' => "'" . $city . "'",
'post_status' => 'publish',
'posts_per_page' => $pageamount,
'suppress_filters' => true
);
$myquery = new WP_Query( $myArgs );
```
UPDATE: using print\_r I can see that the correct value is being assigned to the variable and that value is being correctly assigned to 'posts\_per\_page'. For whatever reason, it ignores it UNLESS it is LESS than the previously assigned value. For instance if I set the else statement to $pageamount = 20, the first time the page loads there will be 20, then if i click the button(sending the variable to the script which is 10) it will load 10. It will load any number of posts I hard code as long as it's less than 20.
Obviously there is something in WP that is setting a default or something. Still a bit of a newb to WP so I don't know. Looking at wp\_config and I dont' see anything. | You can install a plugin to load your JavaScript asynchronously or try to do it manually adding code to your `functions.php` to load your scripts asynchronously.
This can get you started,
>
> Warning
>
>
>
loading JavaScript asynchronously will cause several issues with dependencies:
```
/*function to add async to all scripts*/
function js_async_attr($tag){
//Add async to all scripts tags
return str_replace( ' src', ' async="async" src', $tag );
}
add_filter( 'script_loader_tag', 'js_async_attr', 10 );
```
so you have to check your JS code and update it. |
257,253 | <p>I have problem in Wordpress after migrating my website.
In title tag (<code><title></code>) I have
<code>"&#8211;"</code>
instead of
<code>"-"</code></p>
<p>For the browser it's good, in the title it shows good.
But in html code is <code>"&#8211;"</code>....</p>
<p>Please help me <3</p>
| [
{
"answer_id": 257264,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 1,
"selected": false,
"text": "<h1>Background:</h1>\n<p>WordPress converts normal dash (-) to long dash (<code>–</code>), straight quotes to cu... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257253",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113800/"
] | I have problem in Wordpress after migrating my website.
In title tag (`<title>`) I have
`"–"`
instead of
`"-"`
For the browser it's good, in the title it shows good.
But in html code is `"–"`....
Please help me <3 | Background:
===========
WordPress converts normal dash (-) to long dash (`–`), straight quotes to curly quotes and some other similar symbols and punctuations to their printer friendly versions using `wptexturize`.
Generally it's recommended to leave them up to WordPress. However, occasionally, we may want to override this behaviour. For example, in case we are writing Programming CODE or command and want people to copy paste them.
Solution:
=========
One way to avoid this conversion is to have these CODE inside `<code></code>` block. That way WordPress will know that they are meant to be kept as is. However, we may have already written it and don't want a rewrite. In that case, it's possible to stop WordPress to do these auto conversions all together by disabling `wptexturize`.
For WordPress 4.0 and above, it's easy to do using the following CODE in a plugin or your theme's `functions.php` file:
```
add_filter( 'run_wptexturize', '__return_false' );
```
For before WordPress 4.0, you'll need a little more CODE:
```
foreach( array(
'bloginfo',
'the_content',
'the_excerpt',
'the_title',
'comment_text',
'comment_author',
'link_name',
'link_description',
'link_notes',
'list_cats',
'nav_menu_attr_title',
'nav_menu_description',
'single_post_title',
'single_cat_title',
'single_tag_title',
'single_month_title',
'term_description',
'term_name',
'widget_title',
'wp_title'
) as $texturize_disable_for )
remove_filter( $texturize_disable_for, 'wptexturize' );
```
Of course, you may choose to disable `wptexturize` only for part of your content. Say, to disable only for `title`, you may use:
```
remove_filter( 'the_title', 'wptexturize' );
``` |
257,254 | <p>I want to include inline SVGs in a metabox textarea. </p>
<p>That's easy. What's killing me is how do I sanitize the textarea before saving the postmeta, and how do I escape it? </p>
<p>Halp? </p>
<p>Thanks!</p>
| [
{
"answer_id": 340313,
"author": "Marc",
"author_id": 71657,
"author_profile": "https://wordpress.stackexchange.com/users/71657",
"pm_score": 2,
"selected": false,
"text": "<p>Here is a PHP library that was created for sanitizing SVG files that may be worth looking into. <a href=\"https:... | 2017/02/20 | [
"https://wordpress.stackexchange.com/questions/257254",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93720/"
] | I want to include inline SVGs in a metabox textarea.
That's easy. What's killing me is how do I sanitize the textarea before saving the postmeta, and how do I escape it?
Halp?
Thanks! | Here is a PHP library that was created for sanitizing SVG files that may be worth looking into. <https://github.com/darylldoyle/svg-sanitizer>
Here is an example of how this could be used:
```
// Now do what you want with your clean SVG/XML data
function your_save_meta( $post_id, $post, $update ) {
// - Update the post's metadata.
if ( isset( $_POST['svg_meta'] ) ) {
// Load the sanitizer. (This path will need to be updated)
use enshrined\svgSanitize\Sanitizer;
// Create a new sanitizer instance
$sanitizer = new Sanitizer();
// Pass your meta data to the sanitizer and get it back clean
$cleanSVG = $sanitizer->sanitize($_POST['svg_meta']);
// Update your post meta
update_post_meta( $post_id, 'svg_meta_name', $cleanSVG );
}
}
add_action( 'save_post', 'your_save_meta', 10, 3 );
``` |
257,281 | <p>I am working on a WordPress child theme where I do not have access to any markup other than the header.php. (I have access to child functions.php and the style.css)</p>
<p>The site has a body and a div#wrapper, but I would really like there to be 1 or 2 divs between those because I don't want to use body to create a column and currently, the only way to wrangle the whacky markup would be with the body. I would like to get a div that actually wraps the page contents in this case.</p>
<pre><code><html>
<body>
<section class='NEW-WRAPPING-ELEMENT'>
<div id='wrapper'>
...
</div>
<div id="footer'></div>
<div id="other'></div>
</section>
</body>
</html>
</code></pre>
<p>This markup probably worked just fine in most cases with a classic 960px absolutely positioned layout, but it's hard to work with when you want a malleable responsive layout.</p>
<p>I can use JavaScript and wrap them on page load, but it seems like it would be better to build it on the server - since I'm using PHP anyway. ALSO, you can see the flash of styling when the .master wrapper kicks in. No good!</p>
<p>I am removing <code>p</code> tags from images and wrapping things like inline images with a <code>figure</code> with <code>preg_wrap</code>. Can I / <em>should I</em> - use a similar technique to 'wrap' my everything in the body with another div? I do not know regex at all. I hacked this together but no go so far. Thoughts???</p>
<pre><code>function wrap_wrapper( $content ) {
// A regular expression of what to look for.
$pattern = '/<body>(.*?)<\/body>/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<section class="new-master">$1</section>';
return preg_replace( $pattern, $replacement, $content );
}
add_filter( 'the_content', 'wrap_wrapper' );
</code></pre>
<p><a href="http://codepen.io/sheriffderek/pen/15b13233cfb96c7bff2b5f8f83b0c036/" rel="nofollow noreferrer">Here is a CodePen</a> with full markup example of what I have to work with:</p>
| [
{
"answer_id": 260356,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": false,
"text": "<p>You say, </p>\n\n<blockquote>\n <p>I do not have access to anything other than the style-sheet and a header.ph... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257281",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/27168/"
] | I am working on a WordPress child theme where I do not have access to any markup other than the header.php. (I have access to child functions.php and the style.css)
The site has a body and a div#wrapper, but I would really like there to be 1 or 2 divs between those because I don't want to use body to create a column and currently, the only way to wrangle the whacky markup would be with the body. I would like to get a div that actually wraps the page contents in this case.
```
<html>
<body>
<section class='NEW-WRAPPING-ELEMENT'>
<div id='wrapper'>
...
</div>
<div id="footer'></div>
<div id="other'></div>
</section>
</body>
</html>
```
This markup probably worked just fine in most cases with a classic 960px absolutely positioned layout, but it's hard to work with when you want a malleable responsive layout.
I can use JavaScript and wrap them on page load, but it seems like it would be better to build it on the server - since I'm using PHP anyway. ALSO, you can see the flash of styling when the .master wrapper kicks in. No good!
I am removing `p` tags from images and wrapping things like inline images with a `figure` with `preg_wrap`. Can I / *should I* - use a similar technique to 'wrap' my everything in the body with another div? I do not know regex at all. I hacked this together but no go so far. Thoughts???
```
function wrap_wrapper( $content ) {
// A regular expression of what to look for.
$pattern = '/<body>(.*?)<\/body>/i';
// What to replace it with. $1 refers to the content in the first 'capture group', in parentheses above
$replacement = '<section class="new-master">$1</section>';
return preg_replace( $pattern, $replacement, $content );
}
add_filter( 'the_content', 'wrap_wrapper' );
```
[Here is a CodePen](http://codepen.io/sheriffderek/pen/15b13233cfb96c7bff2b5f8f83b0c036/) with full markup example of what I have to work with: | >
> Can I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.
The `the_content` filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.
Unfortunately, there isn't a good way to filter the entire page.
One way to accomplish this would be to use `ob_start()` and `ob_get_clean()` attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.
Then we can do something with the content. Your regex was close, but not quite right.
In your functions.php, add the following:
```
//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {
//* Start out buffering
ob_start();
//* Add action to get the buffer on shutdown
add_action( 'shutdown', 'wpse_shutdown', -1 );
}
function wpse_shutdown() {
//* Get the output buffer
$content = ob_get_clean();
//* Do something useful with the buffer
//* Use preg_replace to add a <section> wrapper inside the <body> tag
$pattern = "/<body(.*?)>(.*?)<\/body>/is";
$replacement = '<body$1><section class="new-master">$2</section></body>';
//* Print the content to the screen
print( preg_replace( $pattern, $replacement, $content ) );
}
```
>
> Should I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option. |
257,284 | <p>I'm displaying three posts (custom post types) with a foreach loop, each displaying an audio player and some metadata. The audio is played via JW Player, which I am calling using their api. There is a function in the JW Player code that allows you to stop any other players from playing if you press one player.</p>
<p>Here's the whole loop. It does the job but I would like something more elegant and dynamic:</p>
<pre><code><?php
$posts = get_posts(array(
'numberposts' => 3,
'post_type' => 'audio'
));
if( $posts ):
$i = 1;
?>
<?php foreach( $posts as $post ) : ?>
<div class="media-container audio player-<?php echo $i; ?>">
<div id="player-<?php echo $i; ?>">Loading this Audio...</div>
<?php
if ($i == 1) :
$x1 = 2;
$x2 = 3;
elseif ($i == 2) :
$x1 = 1;
$x2 = 3;
elseif ($i == 3) :
$x1 = 1;
$x2 = 2;
endif;
?>
<script type="text/javaScript">
var playerInstance = jwplayer("player-<?php echo $i; ?>");
playerInstance.setup({
file: '<?php the_field("audio_upload"); ?>',
image: '<?php the_field("audio_image"); ?>',
events:{
onPlay: function() {
jwplayer('player-<?php echo $x1; ?>').stop();
jwplayer('player-<?php echo $x2; ?>').stop();
}
}
});
</script>
<div class="media-details">
<h2 class="audio-title"><?php the_field('name_of_audio'); ?> </h2>
</div>
</div>
<?php $i++; endforeach; wp_reset_postdata(); endif; ?>
</code></pre>
<p>I'm wondering if there isn't a way to dynamically get $x1 and $x2 rather than explicitly declaring the values like I am doing. For example if I decide to have 4 or 5 (or 10) posts show up on this page I would like to not have to change the code for $x1 and $x2. Any help would be appreciated.</p>
| [
{
"answer_id": 260356,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": false,
"text": "<p>You say, </p>\n\n<blockquote>\n <p>I do not have access to anything other than the style-sheet and a header.ph... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257284",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109951/"
] | I'm displaying three posts (custom post types) with a foreach loop, each displaying an audio player and some metadata. The audio is played via JW Player, which I am calling using their api. There is a function in the JW Player code that allows you to stop any other players from playing if you press one player.
Here's the whole loop. It does the job but I would like something more elegant and dynamic:
```
<?php
$posts = get_posts(array(
'numberposts' => 3,
'post_type' => 'audio'
));
if( $posts ):
$i = 1;
?>
<?php foreach( $posts as $post ) : ?>
<div class="media-container audio player-<?php echo $i; ?>">
<div id="player-<?php echo $i; ?>">Loading this Audio...</div>
<?php
if ($i == 1) :
$x1 = 2;
$x2 = 3;
elseif ($i == 2) :
$x1 = 1;
$x2 = 3;
elseif ($i == 3) :
$x1 = 1;
$x2 = 2;
endif;
?>
<script type="text/javaScript">
var playerInstance = jwplayer("player-<?php echo $i; ?>");
playerInstance.setup({
file: '<?php the_field("audio_upload"); ?>',
image: '<?php the_field("audio_image"); ?>',
events:{
onPlay: function() {
jwplayer('player-<?php echo $x1; ?>').stop();
jwplayer('player-<?php echo $x2; ?>').stop();
}
}
});
</script>
<div class="media-details">
<h2 class="audio-title"><?php the_field('name_of_audio'); ?> </h2>
</div>
</div>
<?php $i++; endforeach; wp_reset_postdata(); endif; ?>
```
I'm wondering if there isn't a way to dynamically get $x1 and $x2 rather than explicitly declaring the values like I am doing. For example if I decide to have 4 or 5 (or 10) posts show up on this page I would like to not have to change the code for $x1 and $x2. Any help would be appreciated. | >
> Can I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.
The `the_content` filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.
Unfortunately, there isn't a good way to filter the entire page.
One way to accomplish this would be to use `ob_start()` and `ob_get_clean()` attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.
Then we can do something with the content. Your regex was close, but not quite right.
In your functions.php, add the following:
```
//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {
//* Start out buffering
ob_start();
//* Add action to get the buffer on shutdown
add_action( 'shutdown', 'wpse_shutdown', -1 );
}
function wpse_shutdown() {
//* Get the output buffer
$content = ob_get_clean();
//* Do something useful with the buffer
//* Use preg_replace to add a <section> wrapper inside the <body> tag
$pattern = "/<body(.*?)>(.*?)<\/body>/is";
$replacement = '<body$1><section class="new-master">$2</section></body>';
//* Print the content to the screen
print( preg_replace( $pattern, $replacement, $content ) );
}
```
>
> Should I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option. |
257,286 | <p>I just need to get real password (before encrypt) when user is registering. I need to save that password in another table. How I access the real password before encrypt? </p>
<p>The reason for it is, I am doing a research about passwords. </p>
| [
{
"answer_id": 260356,
"author": "scott",
"author_id": 93587,
"author_profile": "https://wordpress.stackexchange.com/users/93587",
"pm_score": 3,
"selected": false,
"text": "<p>You say, </p>\n\n<blockquote>\n <p>I do not have access to anything other than the style-sheet and a header.ph... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257286",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113820/"
] | I just need to get real password (before encrypt) when user is registering. I need to save that password in another table. How I access the real password before encrypt?
The reason for it is, I am doing a research about passwords. | >
> Can I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
Absolutely. Almost everything is possible. But you're going to have to do something a little hackish.
The `the_content` filter doesn't actually filter the content of the entire page. That particular filter is used throughout WordPress to filter a variety of different contents.
Unfortunately, there isn't a good way to filter the entire page.
One way to accomplish this would be to use `ob_start()` and `ob_get_clean()` attached to appropriate hooks. We need to hook into before anything is output to the page and start an output buffer. Then we need to hook in at the last possible moment and get the buffer.
Then we can do something with the content. Your regex was close, but not quite right.
In your functions.php, add the following:
```
//* Hook into WordPress immediately before it starts output
add_action( 'wp_head', 'wpse_wp', -1 );
function wpse_wp() {
//* Start out buffering
ob_start();
//* Add action to get the buffer on shutdown
add_action( 'shutdown', 'wpse_shutdown', -1 );
}
function wpse_shutdown() {
//* Get the output buffer
$content = ob_get_clean();
//* Do something useful with the buffer
//* Use preg_replace to add a <section> wrapper inside the <body> tag
$pattern = "/<body(.*?)>(.*?)<\/body>/is";
$replacement = '<body$1><section class="new-master">$2</section></body>';
//* Print the content to the screen
print( preg_replace( $pattern, $replacement, $content ) );
}
```
>
> Should I use a similar technique to 'wrap' my everything in the body with another div?
>
>
>
It depends. A better, faster way to accomplish this would be to edit the template files. Since you state that you don't have access to the template files, then I believe that something like this would be your only option. |
257,301 | <p>I want to use jquery in my admin side programming but it seems there's no jquery loaded in the page at all and it load only at main website! Has my wordpress any problem which can't load jquery or I should do something extra to do it. However I put this code in function.php, but it not works:</p>
<pre><code>if(is_admin()){
function load_admin_script(){
wp_enqueue_script('jquery_script', "/wp-includes/js/jquery/jquery.js");
}
add_action('admin_enqueue_scripts','load_admin_script');
}
</code></pre>
| [
{
"answer_id": 257302,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 2,
"selected": false,
"text": "<p>If you want to load Jquery, wordpress already provides a handler for it (its also the one in <code>/wp-in... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257301",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112741/"
] | I want to use jquery in my admin side programming but it seems there's no jquery loaded in the page at all and it load only at main website! Has my wordpress any problem which can't load jquery or I should do something extra to do it. However I put this code in function.php, but it not works:
```
if(is_admin()){
function load_admin_script(){
wp_enqueue_script('jquery_script', "/wp-includes/js/jquery/jquery.js");
}
add_action('admin_enqueue_scripts','load_admin_script');
}
``` | If you want to load Jquery, wordpress already provides a handler for it (its also the one in `/wp-includes/js/jquery/jquery.js`):
```
function load_admin_script(){
wp_enqueue_script('jquery');
}
add_action('admin_enqueue_scripts','load_admin_script');
```
note that the jQuery in WordPress runs in noConflict mode. |
257,317 | <p>I run WordPress version 4.7.2. and it uses jQuery version 1.12. I need to update this version to a higher one. I replaced it with a new version before, but when I upgrade WordPress core it is replaced with 1.12 again.
How can I change the version of jQuery that WordPress uses permanently?</p>
| [
{
"answer_id": 257363,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Warning:</em></strong> You shouldn't replace core jQuery version, <strong>especial... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257317",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112741/"
] | I run WordPress version 4.7.2. and it uses jQuery version 1.12. I need to update this version to a higher one. I replaced it with a new version before, but when I upgrade WordPress core it is replaced with 1.12 again.
How can I change the version of jQuery that WordPress uses permanently? | >
> ***Warning:*** You shouldn't replace core jQuery version, **especially in the admin panel**. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the `jQuery` version added in the core.
>
>
>
If you are sure that you want to change the core `jQuery` version, in that case you may add the following CODE in your active theme's `functions.php` file (even better if you create a plugin for this):
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery' );
// Change the URL if you want to load a local copy of jQuery from your own server.
wp_register_script( 'jquery', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
}
add_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );
```
This will replace core `jQuery` version and instead load version `3.1.1` from Google's server.
Also, although ***not recommended***, you may use the following additional line of CODE to replace the jQuery version in `wp-admin` as well:
```
add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );
```
This way, even after updating WordPress, you'll have the version of `jQuery` as you want.
A slightly better function:
===========================
The `replace_core_jquery_version` function above also removes `jquery-migrate` script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of `jquery-migrate`. However, you can include a newer version of `jquery-migrate` as well. In that case, use the following function instead:
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery-core' );
wp_register_script( 'jquery-core', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script( 'jquery-migrate', "https://code.jquery.com/jquery-migrate-3.0.0.min.js", array(), '3.0.0' );
}
``` |
257,324 | <p>I'm using the following code to determine if a checkbox has been ticked and then display some text if it has/hasn't as a test.</p>
<p>When its checked, it works fine and the text displays. </p>
<p>When its unchecked I get the message below on the two lines I have commented in my code below.</p>
<blockquote>
<p>Illegal string offset 'chec_checkbox_field_0'</p>
</blockquote>
<pre><code><?php
function webdev_init() {
?>
<h1>Title</h1>
<h2>WedDev Overlay Plugin Options</h2>
<form action='options.php' method='post'>
<h2>Checking</h2>
<?php
settings_fields( 'my_option' );
do_settings_sections( 'checking' );
submit_button();
?>
</form>
<?php
}
function chec_settings_init() {
register_setting( 'my_option', 'chec_settings' );
add_settings_section(
'chec_checking_section',
__( 'Your section description', 'wp' ),
'chec_settings_section_callback',
'checking'
);
add_settings_field(
'chec_checkbox_field_0',
__( 'Settings field description', 'wp' ),
'chec_checkbox_field_0_render',
'checking',
'chec_checking_section'
);
}
function chec_settings_section_callback() {
echo __( 'This section description', 'wp' );
}
function chec_checkbox_field_0_render() {
$options = get_option( 'chec_settings' );
?>
//Error message on line bellow
<input type='checkbox' name='chec_settings[chec_checkbox_field_0]' value='1' <?php if ( 1 == $options['chec_checkbox_field_0'] ) echo 'checked="checked"'; ?> />
<?php
}
$options = get_option( 'chec_settings' );
//Error message on line bellow
if ( $options['chec_checkbox_field_0'] == '1' ) {
echo 'Checked';
} else {
echo 'Unchecked';
}
</code></pre>
| [
{
"answer_id": 257363,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Warning:</em></strong> You shouldn't replace core jQuery version, <strong>especial... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257324",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113840/"
] | I'm using the following code to determine if a checkbox has been ticked and then display some text if it has/hasn't as a test.
When its checked, it works fine and the text displays.
When its unchecked I get the message below on the two lines I have commented in my code below.
>
> Illegal string offset 'chec\_checkbox\_field\_0'
>
>
>
```
<?php
function webdev_init() {
?>
<h1>Title</h1>
<h2>WedDev Overlay Plugin Options</h2>
<form action='options.php' method='post'>
<h2>Checking</h2>
<?php
settings_fields( 'my_option' );
do_settings_sections( 'checking' );
submit_button();
?>
</form>
<?php
}
function chec_settings_init() {
register_setting( 'my_option', 'chec_settings' );
add_settings_section(
'chec_checking_section',
__( 'Your section description', 'wp' ),
'chec_settings_section_callback',
'checking'
);
add_settings_field(
'chec_checkbox_field_0',
__( 'Settings field description', 'wp' ),
'chec_checkbox_field_0_render',
'checking',
'chec_checking_section'
);
}
function chec_settings_section_callback() {
echo __( 'This section description', 'wp' );
}
function chec_checkbox_field_0_render() {
$options = get_option( 'chec_settings' );
?>
//Error message on line bellow
<input type='checkbox' name='chec_settings[chec_checkbox_field_0]' value='1' <?php if ( 1 == $options['chec_checkbox_field_0'] ) echo 'checked="checked"'; ?> />
<?php
}
$options = get_option( 'chec_settings' );
//Error message on line bellow
if ( $options['chec_checkbox_field_0'] == '1' ) {
echo 'Checked';
} else {
echo 'Unchecked';
}
``` | >
> ***Warning:*** You shouldn't replace core jQuery version, **especially in the admin panel**. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the `jQuery` version added in the core.
>
>
>
If you are sure that you want to change the core `jQuery` version, in that case you may add the following CODE in your active theme's `functions.php` file (even better if you create a plugin for this):
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery' );
// Change the URL if you want to load a local copy of jQuery from your own server.
wp_register_script( 'jquery', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
}
add_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );
```
This will replace core `jQuery` version and instead load version `3.1.1` from Google's server.
Also, although ***not recommended***, you may use the following additional line of CODE to replace the jQuery version in `wp-admin` as well:
```
add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );
```
This way, even after updating WordPress, you'll have the version of `jQuery` as you want.
A slightly better function:
===========================
The `replace_core_jquery_version` function above also removes `jquery-migrate` script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of `jquery-migrate`. However, you can include a newer version of `jquery-migrate` as well. In that case, use the following function instead:
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery-core' );
wp_register_script( 'jquery-core', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script( 'jquery-migrate', "https://code.jquery.com/jquery-migrate-3.0.0.min.js", array(), '3.0.0' );
}
``` |
257,325 | <p>Since plugin updates might bring some unexpected issues to the compatibilies. </p>
<p>Is it recommended to modify plugin version value
to fool the wordpress plugin update system if priority is to turn off plugin out-of-date warnings from wordpress backend ?</p>
| [
{
"answer_id": 257363,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 7,
"selected": true,
"text": "<blockquote>\n <p><strong><em>Warning:</em></strong> You shouldn't replace core jQuery version, <strong>especial... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257325",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/63121/"
] | Since plugin updates might bring some unexpected issues to the compatibilies.
Is it recommended to modify plugin version value
to fool the wordpress plugin update system if priority is to turn off plugin out-of-date warnings from wordpress backend ? | >
> ***Warning:*** You shouldn't replace core jQuery version, **especially in the admin panel**. Since many WordPress core functionality may depend on the version. Also, other plugin may depend on the `jQuery` version added in the core.
>
>
>
If you are sure that you want to change the core `jQuery` version, in that case you may add the following CODE in your active theme's `functions.php` file (even better if you create a plugin for this):
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery' );
// Change the URL if you want to load a local copy of jQuery from your own server.
wp_register_script( 'jquery', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
}
add_action( 'wp_enqueue_scripts', 'replace_core_jquery_version' );
```
This will replace core `jQuery` version and instead load version `3.1.1` from Google's server.
Also, although ***not recommended***, you may use the following additional line of CODE to replace the jQuery version in `wp-admin` as well:
```
add_action( 'admin_enqueue_scripts', 'replace_core_jquery_version' );
```
This way, even after updating WordPress, you'll have the version of `jQuery` as you want.
A slightly better function:
===========================
The `replace_core_jquery_version` function above also removes `jquery-migrate` script added by WordPress core. This is reasonable, because the newest version of jQuery will not work properly with an older version of `jquery-migrate`. However, you can include a newer version of `jquery-migrate` as well. In that case, use the following function instead:
```
function replace_core_jquery_version() {
wp_deregister_script( 'jquery-core' );
wp_register_script( 'jquery-core', "https://code.jquery.com/jquery-3.1.1.min.js", array(), '3.1.1' );
wp_deregister_script( 'jquery-migrate' );
wp_register_script( 'jquery-migrate', "https://code.jquery.com/jquery-migrate-3.0.0.min.js", array(), '3.0.0' );
}
``` |
257,337 | <p>My local WordPress installation on XAMPP seems to have a wrong time setting. When I do</p>
<pre><code>date( 'Y-m-d H:i:s' );
</code></pre>
<p>I get <strong>2017-02-21 10:46:43</strong> as result. However my PCs time really is <strong>2017-02-21 11:46:43</strong>, so my WordPress is one hour behind.</p>
<p>Now I already did, what was recommended <a href="https://stackoverflow.com/questions/15359451/xampp-php-date-function-time-is-different-from-local-machine-time">here</a> and changed <strong>date.timezone</strong> in the <strong>php.ini</strong> to my timezone and restarted the apache afterwards, since I thought the problem might be cause by XAMPP. But still I get the wrong time displayed.</p>
<p>I also went to <strong>settings -> general</strong> in WordPress and changed the timezone there to the correct one. The local time shown there is correct: </p>
<p><em>"Local time is 2017-02-21 11:46:43"</em></p>
<p>But when I use the function, it's still wrong. Do you have any idea, what else could cause this problem?</p>
| [
{
"answer_id": 257338,
"author": "fischi",
"author_id": 15680,
"author_profile": "https://wordpress.stackexchange.com/users/15680",
"pm_score": 3,
"selected": false,
"text": "<p><code>date()</code> is a <code>PHP</code> function depending on your server settings. You can go around that b... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257337",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105498/"
] | My local WordPress installation on XAMPP seems to have a wrong time setting. When I do
```
date( 'Y-m-d H:i:s' );
```
I get **2017-02-21 10:46:43** as result. However my PCs time really is **2017-02-21 11:46:43**, so my WordPress is one hour behind.
Now I already did, what was recommended [here](https://stackoverflow.com/questions/15359451/xampp-php-date-function-time-is-different-from-local-machine-time) and changed **date.timezone** in the **php.ini** to my timezone and restarted the apache afterwards, since I thought the problem might be cause by XAMPP. But still I get the wrong time displayed.
I also went to **settings -> general** in WordPress and changed the timezone there to the correct one. The local time shown there is correct:
*"Local time is 2017-02-21 11:46:43"*
But when I use the function, it's still wrong. Do you have any idea, what else could cause this problem? | `date()` is a `PHP` function depending on your server settings. You can go around that by using the WordPress function:
```
current_time( 'Y-m-d H:i:s' );
```
This function takes the settings in `wp-admin` into account. |
257,355 | <p>How to use live images on a local WP install? I want to do something like the code down here in the <code>wp-config.php</code>. Problem is that the <code>siteurl</code> must be a relative path and cant be a url. I want to set up a local environment to test some parts offline and need to show the images.</p>
<pre><code>if ($_SERVER['SERVER_ADMIN'] == 'dev') {
define('WP_HOME','http://localhost/siteurl.com/public_html/');
define('WP_SITEURL','http://localhost/siteurl.com/public_html/');
// use live images
define( 'UPLOADS', 'http://siteurl.com/wp-content/uploads/' );
}
</code></pre>
| [
{
"answer_id": 257359,
"author": "Johansson",
"author_id": 94498,
"author_profile": "https://wordpress.stackexchange.com/users/94498",
"pm_score": 1,
"selected": true,
"text": "<p>Try to filter the output URLs temporarily to replace them with online images, using the following code:</p>\... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257355",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54693/"
] | How to use live images on a local WP install? I want to do something like the code down here in the `wp-config.php`. Problem is that the `siteurl` must be a relative path and cant be a url. I want to set up a local environment to test some parts offline and need to show the images.
```
if ($_SERVER['SERVER_ADMIN'] == 'dev') {
define('WP_HOME','http://localhost/siteurl.com/public_html/');
define('WP_SITEURL','http://localhost/siteurl.com/public_html/');
// use live images
define( 'UPLOADS', 'http://siteurl.com/wp-content/uploads/' );
}
``` | Try to filter the output URLs temporarily to replace them with online images, using the following code:
```
add_filter( 'wp_get_attachment_image_src', function ( $image, $attachment_id, $size ) {
// For thumbnails
if ( $size ) {
switch ( $size ) {
case 'thumbnail':
case 'medium':
case 'medium-large':
case 'large':
$image[0] = str_replace( 'localhost/', 'EXAMPLE.COM/', $image[0] );
break;
default:
break;
}
} else {
$image[0] = str_replace( 'localhost/', 'EXAMPLE.COM/', $image[0] );
}
return $image;
}, 10, 3 );
```
This will replace any string containing `localhost` with your online domain's name. However, you can't modify or do anything with the image's, it's just for correcting the URL for development purposes.
Note that you should use the domain name without `http://` or any `/` before the domain's name.
Delete this function from your theme's `functions.php` after you are done with it. |
257,366 | <p>How do I create a complete organisation's database, where I can access tables and perform custom SQL requests.
I can use PHP and mySQL, I am actually working on a WordPress theme.
And I am trying to do something like this:</p>
<pre><code>+----------+ +------------+ +------------+
| Book | | Borrow | | Reader |
|----------| |------------| |------------|
|codeBook# |_____|codeBook# | |codeReader# |
|title | |codeReader# |_____|name |
|datepub | |date | |age |
+----------+ +------------+ |contacts |
+------------+
</code></pre>
<p>Some explanation and link will be great</p>
| [
{
"answer_id": 257368,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 3,
"selected": true,
"text": "<p>You can do that accessing the <a href=\"https://www.phpmyadmin.net/\" rel=\"nofollow noreferrer\">phpmyadm... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257366",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/109858/"
] | How do I create a complete organisation's database, where I can access tables and perform custom SQL requests.
I can use PHP and mySQL, I am actually working on a WordPress theme.
And I am trying to do something like this:
```
+----------+ +------------+ +------------+
| Book | | Borrow | | Reader |
|----------| |------------| |------------|
|codeBook# |_____|codeBook# | |codeReader# |
|title | |codeReader# |_____|name |
|datepub | |date | |age |
+----------+ +------------+ |contacts |
+------------+
```
Some explanation and link will be great | You can do that accessing the [phpmyadmin](https://www.phpmyadmin.net/) dashboard of your host, but that is no the right way to do it, i recommend you to research and learn about:
* [Custom Post Types](https://codex.wordpress.org/Post_Types)
* [Custom Taxonomies](https://codex.wordpress.org/Taxonomies) |
257,370 | <p>Here's my code:</p>
<pre><code>add_action('admin_menu', 'test_plugin_setup_menu'); /**/
function test_plugin_setup_menu(){ /**/
add_submenu_page('options-general.php','Forhandler options side','Forhandler Options', 'manage_options', 'mine-første-options', 'test_init'); /**/
} /**/
function test_init(){ /**/
//echo "<h1>Hello World!</h1>";
?>
<div>
<h1>Codehero Dealers</h1>
<form action="options.php" method="post">
<?php settings_fields('mine_plugin_options'); ?>
<?php do_settings_sections('mine-første-options'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php
}
function mine_plugin_section_text() {
echo '<p>Her finder du indstillinger til forhandler delen.</p>';
}
// add the admin settings and such
add_action('admin_init', 'mine_plugin_admin_init');
function mine_plugin_admin_init(){
register_setting( 'mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate' );
add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');
add_settings_field('mine_plugin_text_string', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');
}
function mine_plugin_setting_string() {
$options = get_option('mine_plugin_options');
echo "<input id='plugin_checkbox' name='mine_plugin_options[plugin_checkbox]' type='checkbox' value='true' />";
}
// validate our options
function mine_plugin_options_validate($input) {
/*
$options = get_option('mine_plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options; */
}
</code></pre>
<p>It says that the settings have been saved, but the checkbox reverts back to not being clicked.</p>
<p>I'm pretty new to the whole "create your own options" thing, so any help would be appreciated. I followed this tutorial to make the code: <a href="http://ottopress.com/2009/wordpress-settings-api-tutorial/" rel="nofollow noreferrer">http://ottopress.com/2009/wordpress-settings-api-tutorial/</a></p>
| [
{
"answer_id": 257371,
"author": "Phoenix Online",
"author_id": 108091,
"author_profile": "https://wordpress.stackexchange.com/users/108091",
"pm_score": 0,
"selected": false,
"text": "<p>It looks like you're missing the <code>checked=\"checked\"</code> value from your input...</p>\n\n<p... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257370",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113286/"
] | Here's my code:
```
add_action('admin_menu', 'test_plugin_setup_menu'); /**/
function test_plugin_setup_menu(){ /**/
add_submenu_page('options-general.php','Forhandler options side','Forhandler Options', 'manage_options', 'mine-første-options', 'test_init'); /**/
} /**/
function test_init(){ /**/
//echo "<h1>Hello World!</h1>";
?>
<div>
<h1>Codehero Dealers</h1>
<form action="options.php" method="post">
<?php settings_fields('mine_plugin_options'); ?>
<?php do_settings_sections('mine-første-options'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php
}
function mine_plugin_section_text() {
echo '<p>Her finder du indstillinger til forhandler delen.</p>';
}
// add the admin settings and such
add_action('admin_init', 'mine_plugin_admin_init');
function mine_plugin_admin_init(){
register_setting( 'mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate' );
add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');
add_settings_field('mine_plugin_text_string', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');
}
function mine_plugin_setting_string() {
$options = get_option('mine_plugin_options');
echo "<input id='plugin_checkbox' name='mine_plugin_options[plugin_checkbox]' type='checkbox' value='true' />";
}
// validate our options
function mine_plugin_options_validate($input) {
/*
$options = get_option('mine_plugin_options');
$options['text_string'] = trim($input['text_string']);
if(!preg_match('/^[a-z0-9]{}$/i', $options['text_string'])) {
$options['text_string'] = '';
}
return $options; */
}
```
It says that the settings have been saved, but the checkbox reverts back to not being clicked.
I'm pretty new to the whole "create your own options" thing, so any help would be appreciated. I followed this tutorial to make the code: <http://ottopress.com/2009/wordpress-settings-api-tutorial/> | Don't comment out your validation code remember you are using it to validate the data, so its returning nothing right now, so its saving nothing, try this:
```
add_action('admin_bar_menu', 'make_parent_node', 999);
function make_parent_node($wp_admin_bar) {
$args = array(
'id' => 'test1234', // id of the existing child node (New > Post)
'title' => 'test', // alter the title of existing node
'parent' => 'new-content', // set parent to false to make it a top level (parent) node
'href' => admin_url('admin.php?page=enter_timesheet')
);
$wp_admin_bar->add_node($args);
}
add_action('admin_menu', 'test_plugin_setup_menu');
function test_plugin_setup_menu() { /**/
add_submenu_page('options-general.php', 'Forhandler options side', 'Forhandler Options', 'manage_options', 'mine-første-options', 'test_init');
}
/**/
function test_init() { /**/
//echo "<h1>Hello World!</h1>";
?>
<div>
<h1>Codehero Dealers</h1>
<form action="options.php" method="post">
<?php settings_fields('mine_plugin_options'); ?>
<?php do_settings_sections('mine-første-options'); ?>
<input name="Submit" type="submit" value="<?php esc_attr_e('Save Changes'); ?>" />
</form>
</div>
<?php
}
function mine_plugin_section_text() {
echo '<p>Her finder du indstillinger til forhandler delen.</p>';
}
// add the admin settings and such
add_action('admin_init', 'mine_plugin_admin_init');
function mine_plugin_admin_init() {
register_setting('mine_plugin_options', 'mine_plugin_options', 'mine_plugin_options_validate');
add_settings_section('mine_plugin_main', 'Main Settings', 'mine_plugin_section_text', 'mine-første-options');
add_settings_field('mine_plugin_checkbox', 'Forhandler checkout indstilling', 'mine_plugin_setting_string', 'mine-første-options', 'mine_plugin_main');
}
function mine_plugin_setting_string() {
$options = get_option('mine_plugin_options');
echo "<input id='mine_plugin_checkbox' name='mine_plugin_options[checkbox]' type='checkbox' value='1'" . checked( 1, $options['checkbox'], false ) . " />";
}
// validate our options
function mine_plugin_options_validate($input) {
$newinput['checkbox'] = trim($input['checkbox']);
return $newinput;
}
```
Rather than reading the option, setting up a conditional, and checking for the presence or absence of a value, we can use the WordPress `checked` function. |
257,384 | <p>I have created a custom page that I have called mypage.php.</p>
<p>It is in my template folder with al the other pages (index.php, page.php, ...)</p>
<p>I want this page to be opened when i click on the below code.</p>
<pre><code><a href="<?php site_url(); ?>/mypage.php">Go to page</a>
</code></pre>
<p>When I click on the link the url in my browser look like: <a href="http://localhost:8888/mypage.php" rel="nofollow noreferrer">http://localhost:8888/mypage.php</a> which I guess is correct.</p>
<p>BUT it uses index.php as template ignoring the code I have into mypage.php </p>
<p>So all i am getting at the moment is an empty page with only my header and footer.</p>
<p>Is it possible to use pages in this way with Wordpress? I had a look online and on this site but I haven't been able to find a solution for this problem.</p>
| [
{
"answer_id": 257385,
"author": "shishir mishra",
"author_id": 111219,
"author_profile": "https://wordpress.stackexchange.com/users/111219",
"pm_score": 1,
"selected": false,
"text": "<p>@Martina Sartor, you can use wordpress custom template process. Add a the below comment to the file ... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257384",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111936/"
] | I have created a custom page that I have called mypage.php.
It is in my template folder with al the other pages (index.php, page.php, ...)
I want this page to be opened when i click on the below code.
```
<a href="<?php site_url(); ?>/mypage.php">Go to page</a>
```
When I click on the link the url in my browser look like: <http://localhost:8888/mypage.php> which I guess is correct.
BUT it uses index.php as template ignoring the code I have into mypage.php
So all i am getting at the moment is an empty page with only my header and footer.
Is it possible to use pages in this way with Wordpress? I had a look online and on this site but I haven't been able to find a solution for this problem. | WordPress doesn't load templates that way.
First: give the template a name:
================================
To load a page template, first you'll have to make sure your template has a name. To do that, you'll have to have the following CODE in your template file (here `mypage.php`):
```
<?php
/**
* Template Name: My Page
*/
```
Once you have the above PHP comment, WordPress will recognise it as a template file.
Then, assign the template to a page:
====================================
Now you'll have to create a WordPress `page` (from `wp-admin`).
While you create the `page`, WordPress will give you the option to choose a custom template (if there is one). After you choose the template and `Publish`, that page will use your `mypage.php` file as a template.
[](https://i.stack.imgur.com/hikDh.png) |
257,403 | <p>I have a partial that I call around the website at various points. This partial simply displays the latest Post.</p>
<p>It looks like so:</p>
<pre><code><?php
$args = array(
'posts_per_page' => 1,
'order' => 'desc'
);
query_posts($args);
if ( have_posts() ) :
while ( have_posts() ) : the_post();
if (has_post_thumbnail( $post->ID ) ){
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'home-news-thumbnail' );
}
?>
<a href="<?php echo get_the_permalink(); ?>"><h3><?php echo get_the_title(); ?></h3></a>
<?php if(!empty($featured_image)): ?>
<a href="<?php echo get_the_permalink(); ?>">
<img src="<?php echo $featured_image[0]; ?>" alt="" width="250" class="pull-left">
</a>
<?php endif; ?>
<p>
<?php echo get_the_excerpt(); ?>
</p>
<a href="<?php echo get_the_permalink(); ?>" class="btn btn-brand-dark">more</a>
<div class="clearfix"></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
</code></pre>
<p>This works fine until I 'Sticky' a post. Then I get 2 posts instead of 1.</p>
<p>How can I amend all queries so that <code>posts_per_page</code> has the requested number of posts, regardless of sticky posts?</p>
<p>So in the example above, I'm currently getting <strong>2</strong> posts (despite requesting 1), but I want the latest post, whether that's a sticky post or not.</p>
<p>I know about <code>ignore_sticky_posts</code> parameter, but that will ignore the sticky post, which I don't want to do. If there's a sticky post it should be first.</p>
| [
{
"answer_id": 257404,
"author": "David Lee",
"author_id": 111965,
"author_profile": "https://wordpress.stackexchange.com/users/111965",
"pm_score": 1,
"selected": false,
"text": "<p><strike>If you want your query to ignore if a post is sticky and dont have it at the top of your ordered ... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257403",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/56935/"
] | I have a partial that I call around the website at various points. This partial simply displays the latest Post.
It looks like so:
```
<?php
$args = array(
'posts_per_page' => 1,
'order' => 'desc'
);
query_posts($args);
if ( have_posts() ) :
while ( have_posts() ) : the_post();
if (has_post_thumbnail( $post->ID ) ){
$featured_image = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'home-news-thumbnail' );
}
?>
<a href="<?php echo get_the_permalink(); ?>"><h3><?php echo get_the_title(); ?></h3></a>
<?php if(!empty($featured_image)): ?>
<a href="<?php echo get_the_permalink(); ?>">
<img src="<?php echo $featured_image[0]; ?>" alt="" width="250" class="pull-left">
</a>
<?php endif; ?>
<p>
<?php echo get_the_excerpt(); ?>
</p>
<a href="<?php echo get_the_permalink(); ?>" class="btn btn-brand-dark">more</a>
<div class="clearfix"></div>
<?php
endwhile;
endif;
wp_reset_postdata();
?>
```
This works fine until I 'Sticky' a post. Then I get 2 posts instead of 1.
How can I amend all queries so that `posts_per_page` has the requested number of posts, regardless of sticky posts?
So in the example above, I'm currently getting **2** posts (despite requesting 1), but I want the latest post, whether that's a sticky post or not.
I know about `ignore_sticky_posts` parameter, but that will ignore the sticky post, which I don't want to do. If there's a sticky post it should be first. | Here's a way to force the exact `posts_per_page` value in `WP_Query`, regardless of sticky posts or custom post injects:
```
$args = [
'posts_per_page' => 1,
'_exact_posts_per_page' => true // <-- our custom input argument
];
```
by using our custom `_exact_posts_per_page` input argument.
I'm sure this has been implemented many times before, but I didn't find it at the moment, so let us try to implement it with this demo plugin:
```
<?php
/**
* Plugin Name: Exact Posts Per Pages
* Description: Activated through the '_exact_posts_per_page' bool argument of WP_Query
* Plugin URI: http://wordpress.stackexchange.com/a/257523/26350
*/
add_filter( 'the_posts', function( $posts, \WP_Query $q )
{
if(
wp_validate_boolean( $q->get( '_exact_posts_per_page' ) )
&& ! empty( $posts )
&& is_int( $q->get( 'posts_per_page' ) )
)
$posts = array_slice( $posts, 0, absint( $q->get( 'posts_per_page' ) ) );
return $posts;
}, 999, 2 ); // <-- some late priority here!
```
Here we use the `the_posts` filter to slice the array, no matter if it contains sticky posts or not.
The `the_posts` filter is not applied if the `suppress_filters` input argument of `WP_Query` is `true`.
**Note** that `query_posts()` is not recommended in plugins or themes. Check out the many warnings in the *Code reference* [here](https://developer.wordpress.org/reference/functions/query_posts/).
Hope you can test it further and adjust to your needs! |
257,405 | <p>I am new to WordPress Plugins development, and I just started working with the widget. My question is: What are the limitations of WordPress Widget?</p>
<p>I tried to use jQuery to make the Widget Form more interactive/dynamic, but it doesn't seem to work at all. For example, I have a button that when clicked will add a string of "Hello!" to a div that has id "here".</p>
<pre><code><div id="here"></div>
<input type="button" id="add" value="Click Me!" " />
<script>
jQuery(document).ready(function(){
//call when the button is click
$(document).on('click', '#add', function() {
$('#here').append('<p>Hello</p>');
});
});
</script>
</code></pre>
<ol>
<li><p>Why doesn't the paragraph of "Hello" show up on the form? Is it because widget form prevent it from doing so?</p></li>
<li><p>I also heard about Backbone.js that refreshes the front-end, but I am not sure if that will work. </p></li>
<li><p>If possible, please explain how the whole wordpress widget class work. Thank you in advance!</p></li>
</ol>
<p><strong>Update: I already tried what are suggested, but it still doesn't work. Here are my code.</strong></p>
<p><strong>repeat.php</strong> </p>
<pre><code> <?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input',
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
?>
<div id="here"></div>
<input type="button" id="addRepeat" value="Click Me!" />
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
function repeat_field_widget_scripts() {
wp_enqueue_script( 'repeat-field-widget-scripts', get_template_directory_uri() . '/repeat.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'repeat_field_widget_scripts' );
</code></pre>
<p><strong>repeat.js</strong></p>
<pre><code> jQuery(document).ready(function($){
//call when the button is click
$("#addRepeat").click(function() {
$('#here').append('<p>Hello</p>');
});
});
</code></pre>
| [
{
"answer_id": 257415,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Widget forms are tricky for JS manipulation. In general you should never use IDs to detect elements in th... | 2017/02/21 | [
"https://wordpress.stackexchange.com/questions/257405",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113869/"
] | I am new to WordPress Plugins development, and I just started working with the widget. My question is: What are the limitations of WordPress Widget?
I tried to use jQuery to make the Widget Form more interactive/dynamic, but it doesn't seem to work at all. For example, I have a button that when clicked will add a string of "Hello!" to a div that has id "here".
```
<div id="here"></div>
<input type="button" id="add" value="Click Me!" " />
<script>
jQuery(document).ready(function(){
//call when the button is click
$(document).on('click', '#add', function() {
$('#here').append('<p>Hello</p>');
});
});
</script>
```
1. Why doesn't the paragraph of "Hello" show up on the form? Is it because widget form prevent it from doing so?
2. I also heard about Backbone.js that refreshes the front-end, but I am not sure if that will work.
3. If possible, please explain how the whole wordpress widget class work. Thank you in advance!
**Update: I already tried what are suggested, but it still doesn't work. Here are my code.**
**repeat.php**
```
<?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input',
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
?>
<div id="here"></div>
<input type="button" id="addRepeat" value="Click Me!" />
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
function repeat_field_widget_scripts() {
wp_enqueue_script( 'repeat-field-widget-scripts', get_template_directory_uri() . '/repeat.js', array( 'jquery' ), '1.0.0', true );
}
add_action( 'wp_enqueue_scripts', 'repeat_field_widget_scripts' );
```
**repeat.js**
```
jQuery(document).ready(function($){
//call when the button is click
$("#addRepeat").click(function() {
$('#here').append('<p>Hello</p>');
});
});
``` | Thank you **Dave Romsey** and **Mark Kaplun** for pointing out about not using HTML ID in WordPress Widget. I finally find a solution for my need.
**Solution:**
We need to add a preset variables into all of the 3 functions (widget, form, update). In my codes, they are called "spotlight\_image\_link1, spotlight\_image\_link2, etc". Then in the "form function" give their id using php code. Please read my code below for more information.
**What can my solution do?**
Basically, it is not fully dynamic because we need to predefine all the spotlights beforehand. In my case, I only predefined two spotlights to make the code simple to read.
**Here what it looks like:**
[](https://i.stack.imgur.com/Z6oZD.png)
**Logic behind the scene:**
* whenever the "Click me!" button is clicked, a spotlight will be added.
* There is a tracker array called "tracker" that keep track of which predefined spotlights are already used. When all spotlights are used, disable the "Click me!" button.
* When the "delete spotlight" is clicked, remove that specific spotlight, and re-enable the "Click me!" button. Note that the name of each delete button is append with number. This lets us know which spotlight to be deleted.
* The spotlight is saved only if and only if the input is not empty. That condition is in the "while" loop of the "form" function.
**Limitation:**
As of now, whenever, we clicked "Save", the spotlight order is rearranged from 1 to n. It's not super user-friendly, but I plan to use Ajax to sync the front-end to the back-end. I am not sure how just yet.
**Source code:**
* As of WordPress 4.7.2, it works without any error.
* Put all the source code into "repeat.php" file in your plugin directory. If you don't know how, please google it.
**repeat.php**
```
<?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input'
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
$tracker1;
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
$spotlight_add_row = ! empty( $instance['spotlight_add_row'] ) ? $instance['spotlight_add_row'] : '';
$spotlight_row_appender = ! empty( $instance['spotlight_row_appender'] ) ? $instance['spotlight_row_appender'] : '';
/**============== Spotlight 1 =========================*/
$spotlight_image_link1 = ! empty( $instance['spotlight_image_link1'] ) ? $instance['spotlight_image_link1'] : '';
$spotlight_add_image1 = ! empty( $instance['spotlight_add_image1'] ) ? $instance['spotlight_add_image1'] : '';
$spotlight_image_preview1 = ! empty( $instance['spotlight_image_preview1'] ) ? $instance['spotlight_image_preview1'] : '';
$spotlight_name1 = ! empty( $instance['spotlight_name1'] ) ? $instance['spotlight_name1'] : '';
$spotlight_description1 = ! empty( $instance['spotlight_description1'] ) ? $instance['spotlight_description1'] : '';
$spotlight_link1 = ! empty( $instance['spotlight_link1'] ) ? $instance['spotlight_link1'] : '';
/**============== Spotlight 2 =========================*/
$spotlight_image_link2 = ! empty( $instance['spotlight_image_link2'] ) ? $instance['spotlight_image_link2'] : '';
$spotlight_add_image2 = ! empty( $instance['spotlight_add_image2'] ) ? $instance['spotlight_add_image2'] : '';
$spotlight_image_preview2 = ! empty( $instance['spotlight_image_preview2'] ) ? $instance['spotlight_image_preview2'] : '';
$spotlight_name2 = ! empty( $instance['spotlight_name2'] ) ? $instance['spotlight_name2'] : '';
$spotlight_description2 = ! empty( $instance['spotlight_description2'] ) ? $instance['spotlight_description2'] : '';
$spotlight_link2 = ! empty( $instance['spotlight_link2'] ) ? $instance['spotlight_link2'] : '';
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
$instance = wp_parse_args( (array) $instance, array( 'spotlight_add_row' => '', 'spotlight_row_appender' => '', 'spotlight_image_link1' => '', 'spotlight_add_image1' => '', 'spotlight_image_preview1' => '', 'spotlight_name1' => '', 'spotlight_description1' => '', 'spotlight_link1' => '',
'spotlight_image_link2' => '', 'spotlight_add_image2' => '', 'spotlight_image_preview2' => '', 'spotlight_name2' => '', 'spotlight_description2' => '', 'spotlight_link2' => '' ));
//Create Add and delete button
$spotlight_add_row = $instance['spotlight_add_row'];
$spotlight_row_appender = $instance['spotlight_row_appender'];
/**================== Spotlight 1 ==============*/
$spotlight_image_link1 = $instance['spotlight_image_link1'];
$spotlight_add_image1 = $instance['spotlight_add_image1'];
$spotlight_image_preview1 = $instance['spotlight_image_preview1'];
$spotlight_name1 = $instance['spotlight_name1'];
$spotlight_description1 = $instance['spotlight_description1'];
$spotlight_link1 = $instance['spotlight_link1'];
/**================== Spotlight 2 ==============*/
$spotlight_image_link2 = $instance['spotlight_image_link2'];
$spotlight_add_image2 = $instance['spotlight_add_image2'];
$spotlight_image_preview2 = $instance['spotlight_image_preview2'];
$spotlight_name2 = $instance['spotlight_name2'];
$spotlight_description2 = $instance['spotlight_description2'];
$spotlight_link2 = $instance['spotlight_link2'];
$starter = 1; //Store which number to continue adding spotlight.
$num = 1;
$max_spotlight = 2; //number of spotlight allowed.
static $tracker = array(0,0); //setup a tracker for each spotlight, zero mean none active.
while($num <= $max_spotlight){
$tempImage = 'spotlight_image_link' . $num;
if ($$tempImage != ''){
$starter++;
$tracker[$num - 1] = 1;
?>
<!-- Image input -->
<div>
<p class="spotlight-para">Spotlight <?php echo $num; ?></p>
<p> <?php $tempImage = 'spotlight_image_link' . $num; $tempDeleteName = 'deletespotlight_'. $num;?> <!-- store the combined name. -->
<label for="<?php echo esc_attr( $this->get_field_id( $tempImage ) ); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label>
<input
class="widefat"
id="<?php echo $this->get_field_id($tempImage); ?>"
name="<?php echo $this->get_field_name($tempImage); ?>"
type="text"
value="<?php echo esc_attr($$tempImage); ?>"
/>
<input style="float:right;" id="delete-spotlight" name="<?php echo $tempDeleteName; ?>" type="button" value="Delete Spotlight" class="button"/>
<br />
</p>
</div>
<?php
}
$num++;
}
$id_prefix = $this->get_field_id(''); //get the widget prefix id.
?>
<span id="<?php echo $this->get_field_id('spotlight_row_appender'); ?>"> </span>
<div>
<br />
<input
class="button"
type="button"
id="<?php echo $this->get_field_id('spotlight_add_row'); ?>"
value="Click Me!"
onclick="repeater.uploader('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;"
/>
</div>
<script>
jQuery(document).ready(function($){
var tracker = <?php echo json_encode($tracker); ?>;
var c1 = <?php echo json_encode($starter - 1); ?>;//index of the array.
//disbale add button when reaches max spotlight.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
repeater = {
//TRY to mass Number into this function........
uploader :function(widget_id, widget_id_string){
//Find the non active element
var i;
for (i = 0; i < <?php echo $max_spotlight; ?>; i++){
if ( tracker[i] == 0){
c1 = i;
break;
}
}
c1++;
//alert(c1);
$("#" + widget_id_string + "spotlight_row_appender").append('<div> <p class="spotlight-para">Spotlight '+c1+'</p><p> <label for="<?php echo esc_attr( $this->get_field_id( "spotlight_image_link'+c1+'")); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id("spotlight_image_link'+c1+'"); ?>" name="<?php echo $this->get_field_name("spotlight_image_link'+c1+'"); ?>" type="text" value="" /> <input style="float:right;"id="delete-spotlight" name="deletespotlight_'+c1+'" type="button" value="Delete Spotlight" class="button"/><br /> </p></div>');
//check element as active
tracker[c1-1] = 1;
//if all element is > 0, disable the deleteButton.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
//alert(c1);
return false;
}
};
$(document).on('click', '#delete-spotlight', function() {
$(this).parent().parent().remove(); //remove the field.
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').removeAttr("disabled"); //reset add button.
//Get the name, and parse to get the ID.
var deleteButtonName = this.name;
var stringDeleteButton = deleteButtonName.split("_").pop();
var deleteButtonID = parseInt(stringDeleteButton);
tracker[deleteButtonID-1] = 0; //reset element
//alert(tracker);
});
});
</script>
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
$instance = $old_instance;
$instance['spotlight_add_row'] = sanitize_text_field($new_instance['spotlight_add_row']);
$instance['spotlight_row_appender'] = sanitize_text_field($new_instance['spotlight_row_appender']);
$increment = 1;
while ( $increment <= 2 ){
//increment variables
$increment_image_link = 'spotlight_image_link' . $increment;
$increment_add_image = 'spotlight_add_image' . $increment;
$increment_image_preview = 'spotlight_image_preview' . $increment;
$increment_description = 'spotlight_description' . $increment;
$increment_name = 'spotlight_name' . $increment;
$increment_link = 'spotlight_link' . $increment;
$instance[$increment_image_link] = sanitize_text_field( $new_instance[$increment_image_link] );
$instance[$increment_add_image] = sanitize_text_field( $new_instance[$increment_add_image] );
$instance[$increment_image_preview] = sanitize_text_field( $new_instance[$increment_image_preview]);
$instance[$increment_name] = sanitize_text_field( $new_instance[$increment_name] );
$instance[$increment_description] = sanitize_text_field( $new_instance[$increment_description] );
$instance[$increment_link] = sanitize_text_field( $new_instance[$increment_link] );
$increment++;
}
$starter = 1;
$num = 1;
return $instance;
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
```
**Quick Note:**
I know that this is not the most clean, secure, and best code, but I am still learning. I hope that helps anyone who faces the same issues as me. |
257,451 | <p>I have my blogs on <code>wordpress.com</code> (e.g. <code>test.wordpress.com</code>). I want to migrate all those blogs to my self hosted WordPress website. Is this possible?</p>
<p>Is there any plugin in WordPress or do I need to develop any API?</p>
| [
{
"answer_id": 257415,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 1,
"selected": false,
"text": "<p>Widget forms are tricky for JS manipulation. In general you should never use IDs to detect elements in th... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257451",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113898/"
] | I have my blogs on `wordpress.com` (e.g. `test.wordpress.com`). I want to migrate all those blogs to my self hosted WordPress website. Is this possible?
Is there any plugin in WordPress or do I need to develop any API? | Thank you **Dave Romsey** and **Mark Kaplun** for pointing out about not using HTML ID in WordPress Widget. I finally find a solution for my need.
**Solution:**
We need to add a preset variables into all of the 3 functions (widget, form, update). In my codes, they are called "spotlight\_image\_link1, spotlight\_image\_link2, etc". Then in the "form function" give their id using php code. Please read my code below for more information.
**What can my solution do?**
Basically, it is not fully dynamic because we need to predefine all the spotlights beforehand. In my case, I only predefined two spotlights to make the code simple to read.
**Here what it looks like:**
[](https://i.stack.imgur.com/Z6oZD.png)
**Logic behind the scene:**
* whenever the "Click me!" button is clicked, a spotlight will be added.
* There is a tracker array called "tracker" that keep track of which predefined spotlights are already used. When all spotlights are used, disable the "Click me!" button.
* When the "delete spotlight" is clicked, remove that specific spotlight, and re-enable the "Click me!" button. Note that the name of each delete button is append with number. This lets us know which spotlight to be deleted.
* The spotlight is saved only if and only if the input is not empty. That condition is in the "while" loop of the "form" function.
**Limitation:**
As of now, whenever, we clicked "Save", the spotlight order is rearranged from 1 to n. It's not super user-friendly, but I plan to use Ajax to sync the front-end to the back-end. I am not sure how just yet.
**Source code:**
* As of WordPress 4.7.2, it works without any error.
* Put all the source code into "repeat.php" file in your plugin directory. If you don't know how, please google it.
**repeat.php**
```
<?php
/**
* Plugin Name: Repeat Field
*
*/
class repeat_field_widget extends WP_Widget {
/**
* Sets up the widgets name etc
*/
public function __construct() {
$widget_ops = array(
'classname' => 'repeat_field_widget',
'description' => 'Repeat Field for Name input'
);
parent::__construct( 'repeat_field_widget', 'Repeat Field', $widget_ops );
$tracker1;
}
/**
* Outputs the content of the widget
*
* @param array $args
* @param array $instance
*/
public function widget( $args, $instance ) {
// outputs the content of the widget
$spotlight_add_row = ! empty( $instance['spotlight_add_row'] ) ? $instance['spotlight_add_row'] : '';
$spotlight_row_appender = ! empty( $instance['spotlight_row_appender'] ) ? $instance['spotlight_row_appender'] : '';
/**============== Spotlight 1 =========================*/
$spotlight_image_link1 = ! empty( $instance['spotlight_image_link1'] ) ? $instance['spotlight_image_link1'] : '';
$spotlight_add_image1 = ! empty( $instance['spotlight_add_image1'] ) ? $instance['spotlight_add_image1'] : '';
$spotlight_image_preview1 = ! empty( $instance['spotlight_image_preview1'] ) ? $instance['spotlight_image_preview1'] : '';
$spotlight_name1 = ! empty( $instance['spotlight_name1'] ) ? $instance['spotlight_name1'] : '';
$spotlight_description1 = ! empty( $instance['spotlight_description1'] ) ? $instance['spotlight_description1'] : '';
$spotlight_link1 = ! empty( $instance['spotlight_link1'] ) ? $instance['spotlight_link1'] : '';
/**============== Spotlight 2 =========================*/
$spotlight_image_link2 = ! empty( $instance['spotlight_image_link2'] ) ? $instance['spotlight_image_link2'] : '';
$spotlight_add_image2 = ! empty( $instance['spotlight_add_image2'] ) ? $instance['spotlight_add_image2'] : '';
$spotlight_image_preview2 = ! empty( $instance['spotlight_image_preview2'] ) ? $instance['spotlight_image_preview2'] : '';
$spotlight_name2 = ! empty( $instance['spotlight_name2'] ) ? $instance['spotlight_name2'] : '';
$spotlight_description2 = ! empty( $instance['spotlight_description2'] ) ? $instance['spotlight_description2'] : '';
$spotlight_link2 = ! empty( $instance['spotlight_link2'] ) ? $instance['spotlight_link2'] : '';
}
/**
* Outputs the options form on admin
*
* @param array $instance The widget options
*/
public function form( $instance ) {
// outputs the options form on admin
$instance = wp_parse_args( (array) $instance, array( 'spotlight_add_row' => '', 'spotlight_row_appender' => '', 'spotlight_image_link1' => '', 'spotlight_add_image1' => '', 'spotlight_image_preview1' => '', 'spotlight_name1' => '', 'spotlight_description1' => '', 'spotlight_link1' => '',
'spotlight_image_link2' => '', 'spotlight_add_image2' => '', 'spotlight_image_preview2' => '', 'spotlight_name2' => '', 'spotlight_description2' => '', 'spotlight_link2' => '' ));
//Create Add and delete button
$spotlight_add_row = $instance['spotlight_add_row'];
$spotlight_row_appender = $instance['spotlight_row_appender'];
/**================== Spotlight 1 ==============*/
$spotlight_image_link1 = $instance['spotlight_image_link1'];
$spotlight_add_image1 = $instance['spotlight_add_image1'];
$spotlight_image_preview1 = $instance['spotlight_image_preview1'];
$spotlight_name1 = $instance['spotlight_name1'];
$spotlight_description1 = $instance['spotlight_description1'];
$spotlight_link1 = $instance['spotlight_link1'];
/**================== Spotlight 2 ==============*/
$spotlight_image_link2 = $instance['spotlight_image_link2'];
$spotlight_add_image2 = $instance['spotlight_add_image2'];
$spotlight_image_preview2 = $instance['spotlight_image_preview2'];
$spotlight_name2 = $instance['spotlight_name2'];
$spotlight_description2 = $instance['spotlight_description2'];
$spotlight_link2 = $instance['spotlight_link2'];
$starter = 1; //Store which number to continue adding spotlight.
$num = 1;
$max_spotlight = 2; //number of spotlight allowed.
static $tracker = array(0,0); //setup a tracker for each spotlight, zero mean none active.
while($num <= $max_spotlight){
$tempImage = 'spotlight_image_link' . $num;
if ($$tempImage != ''){
$starter++;
$tracker[$num - 1] = 1;
?>
<!-- Image input -->
<div>
<p class="spotlight-para">Spotlight <?php echo $num; ?></p>
<p> <?php $tempImage = 'spotlight_image_link' . $num; $tempDeleteName = 'deletespotlight_'. $num;?> <!-- store the combined name. -->
<label for="<?php echo esc_attr( $this->get_field_id( $tempImage ) ); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label>
<input
class="widefat"
id="<?php echo $this->get_field_id($tempImage); ?>"
name="<?php echo $this->get_field_name($tempImage); ?>"
type="text"
value="<?php echo esc_attr($$tempImage); ?>"
/>
<input style="float:right;" id="delete-spotlight" name="<?php echo $tempDeleteName; ?>" type="button" value="Delete Spotlight" class="button"/>
<br />
</p>
</div>
<?php
}
$num++;
}
$id_prefix = $this->get_field_id(''); //get the widget prefix id.
?>
<span id="<?php echo $this->get_field_id('spotlight_row_appender'); ?>"> </span>
<div>
<br />
<input
class="button"
type="button"
id="<?php echo $this->get_field_id('spotlight_add_row'); ?>"
value="Click Me!"
onclick="repeater.uploader('<?php echo $this->id;?>', '<?php echo $id_prefix;?>'); return false;"
/>
</div>
<script>
jQuery(document).ready(function($){
var tracker = <?php echo json_encode($tracker); ?>;
var c1 = <?php echo json_encode($starter - 1); ?>;//index of the array.
//disbale add button when reaches max spotlight.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
repeater = {
//TRY to mass Number into this function........
uploader :function(widget_id, widget_id_string){
//Find the non active element
var i;
for (i = 0; i < <?php echo $max_spotlight; ?>; i++){
if ( tracker[i] == 0){
c1 = i;
break;
}
}
c1++;
//alert(c1);
$("#" + widget_id_string + "spotlight_row_appender").append('<div> <p class="spotlight-para">Spotlight '+c1+'</p><p> <label for="<?php echo esc_attr( $this->get_field_id( "spotlight_image_link'+c1+'")); ?>"><?php esc_attr_e( 'Image\'s link:', 'text_domain' ); ?></label> <input class="widefat" id="<?php echo $this->get_field_id("spotlight_image_link'+c1+'"); ?>" name="<?php echo $this->get_field_name("spotlight_image_link'+c1+'"); ?>" type="text" value="" /> <input style="float:right;"id="delete-spotlight" name="deletespotlight_'+c1+'" type="button" value="Delete Spotlight" class="button"/><br /> </p></div>');
//check element as active
tracker[c1-1] = 1;
//if all element is > 0, disable the deleteButton.
if(tracker.every(x => x > 0)){
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').attr("disabled",true);
}
//alert(c1);
return false;
}
};
$(document).on('click', '#delete-spotlight', function() {
$(this).parent().parent().remove(); //remove the field.
$('#' + '<?php echo $id_prefix; ?>' + 'spotlight_add_row').removeAttr("disabled"); //reset add button.
//Get the name, and parse to get the ID.
var deleteButtonName = this.name;
var stringDeleteButton = deleteButtonName.split("_").pop();
var deleteButtonID = parseInt(stringDeleteButton);
tracker[deleteButtonID-1] = 0; //reset element
//alert(tracker);
});
});
</script>
<?php
}
/**
* Processing widget options on save
*
* @param array $new_instance The new options
* @param array $old_instance The previous options
*/
public function update( $new_instance, $old_instance ) {
// processes widget options to be saved
$instance = $old_instance;
$instance['spotlight_add_row'] = sanitize_text_field($new_instance['spotlight_add_row']);
$instance['spotlight_row_appender'] = sanitize_text_field($new_instance['spotlight_row_appender']);
$increment = 1;
while ( $increment <= 2 ){
//increment variables
$increment_image_link = 'spotlight_image_link' . $increment;
$increment_add_image = 'spotlight_add_image' . $increment;
$increment_image_preview = 'spotlight_image_preview' . $increment;
$increment_description = 'spotlight_description' . $increment;
$increment_name = 'spotlight_name' . $increment;
$increment_link = 'spotlight_link' . $increment;
$instance[$increment_image_link] = sanitize_text_field( $new_instance[$increment_image_link] );
$instance[$increment_add_image] = sanitize_text_field( $new_instance[$increment_add_image] );
$instance[$increment_image_preview] = sanitize_text_field( $new_instance[$increment_image_preview]);
$instance[$increment_name] = sanitize_text_field( $new_instance[$increment_name] );
$instance[$increment_description] = sanitize_text_field( $new_instance[$increment_description] );
$instance[$increment_link] = sanitize_text_field( $new_instance[$increment_link] );
$increment++;
}
$starter = 1;
$num = 1;
return $instance;
}
}
function register_repeat_field_widget() {
register_widget( 'repeat_field_widget' );
}
add_action( 'widgets_init', 'register_repeat_field_widget' );
```
**Quick Note:**
I know that this is not the most clean, secure, and best code, but I am still learning. I hope that helps anyone who faces the same issues as me. |
257,478 | <p>How to get Custom Post ID by adding code to child theme's function. The following code works fine for the regular post, but can't figure out for the custom post types.</p>
<pre><code>add_filter( 'manage_posts_columns', 'revealid_add_id_column', 5 );
add_action( 'manage_posts_custom_column', 'revealid_id_column_content', 5, 2 );
function revealid_add_id_column( $columns ) {
$columns['revealid_id'] = 'ID';
return $columns;
}
function revealid_id_column_content( $column, $id ) {
if( 'revealid_id' == $column ) {
echo $id;
}
}
</code></pre>
| [
{
"answer_id": 257479,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<pre><code>add_action( 'manage_posts_custom_column', 'id_data' );\nadd_filter( 'manage_posts_columns', 'id_column... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257478",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93692/"
] | How to get Custom Post ID by adding code to child theme's function. The following code works fine for the regular post, but can't figure out for the custom post types.
```
add_filter( 'manage_posts_columns', 'revealid_add_id_column', 5 );
add_action( 'manage_posts_custom_column', 'revealid_id_column_content', 5, 2 );
function revealid_add_id_column( $columns ) {
$columns['revealid_id'] = 'ID';
return $columns;
}
function revealid_id_column_content( $column, $id ) {
if( 'revealid_id' == $column ) {
echo $id;
}
}
``` | ```
add_action( 'manage_posts_custom_column', 'id_data' );
add_filter( 'manage_posts_columns', 'id_column' );
function id_column( $defaults ) {
$defaults['id'] = 'ID';
return $defaults;
}
function id_data( $column_name ) {
global $post;
switch ( $column_name ) {
case 'id':
echo $post->ID;
}
}
``` |
257,482 | <p>I am creating a WordPress Plugin for WordPress directory.</p>
<p>How can I get <code>the_content()</code> after applying all the shortcodes that are presents in <code>the_content</code>?</p>
<p>Let me explain:</p>
<p>My plugin will be used in multiple themes and websites; and users will add some shortcodes in their posts or pages. I want my plugin to work after these shortcodes are parsed, and then use the content for my plugin as input.</p>
| [
{
"answer_id": 257479,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 1,
"selected": false,
"text": "<pre><code>add_action( 'manage_posts_custom_column', 'id_data' );\nadd_filter( 'manage_posts_columns', 'id_column... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257482",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113920/"
] | I am creating a WordPress Plugin for WordPress directory.
How can I get `the_content()` after applying all the shortcodes that are presents in `the_content`?
Let me explain:
My plugin will be used in multiple themes and websites; and users will add some shortcodes in their posts or pages. I want my plugin to work after these shortcodes are parsed, and then use the content for my plugin as input. | ```
add_action( 'manage_posts_custom_column', 'id_data' );
add_filter( 'manage_posts_columns', 'id_column' );
function id_column( $defaults ) {
$defaults['id'] = 'ID';
return $defaults;
}
function id_data( $column_name ) {
global $post;
switch ( $column_name ) {
case 'id':
echo $post->ID;
}
}
``` |
257,483 | <p>Here is my script : </p>
<pre><code>$my_post = array(
'post_title' => "post test",
'post_date' => current_time('mysql'),
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(1)
);
$post_id= wp_insert_post($my_post);
var_dump($post_id);
</code></pre>
| [
{
"answer_id": 257487,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the date param or use the right format for the time stamp, like <code>date('Y-m-d H:i:s'),</code> But it i... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257483",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/113921/"
] | Here is my script :
```
$my_post = array(
'post_title' => "post test",
'post_date' => current_time('mysql'),
'post_content' => 'This is my post.',
'post_status' => 'publish',
'post_author' => 1,
'post_category' => array(1)
);
$post_id= wp_insert_post($my_post);
var_dump($post_id);
``` | Remove the date param or use the right format for the time stamp, like `date('Y-m-d H:i:s'),` But it is not necessary, WP use the current timestamp on the insert post time. |
257,489 | <p>I've been tasked to move a website into a new domain, and I've encontered this weird issue.<br>
On the homepage, I always see these:</p>
<blockquote>
<p>Notice: Constant AUTOSAVE_INTERVAL already defined in /home/gturnat/public_html/wp-config.php on line 99</p>
<p>Notice: Constant WP_POST_REVISIONS already defined in /home/gturnat/public_html/wp-config.php on line 100</p>
</blockquote>
<hr>
<p>What I have tried:</p>
<ul>
<li><a href="https://wordpress.stackexchange.com/q/158075/89236">Notice: Constant WP_POST_REVISIONS already defined</a> suggests commenting the constants on <code>default-constants.php</code>, but it doesn't work.</li>
<li>Settings <code>display_errors</code> to <code>0</code>, <code>'0'</code> or <code>'Off'</code> does nothing.</li>
<li>Running <code>error_reporting(0)</code> will still display the errors.</li>
<li>Creating a <code>mu-plugin</code> (<a href="https://stackoverflow.com/a/27997023">As suggested on How can I stop PHP notices from appearing in wordpress?</a>).<br>
Nothing happens and the plugin isn't even loaded.<br>
The errors still keep showing up.</li>
<li>Tried to comment out the lines in <code>wp-config.php</code>, but didn't work. The notices are still there.</li>
<li>Removed the lines <strong>entirelly</strong> and moved them around <code>wp-config.php</code>, but the warnings insist it is on line 99 and 100.<br>
Causing a syntax error inside <code>wp-config.php</code> does lead to an error being logged, which means that the file isn't cached.</li>
<li>Tried to enable and disable the debug mode, set <code>display_errors</code> to <code>false</code>, <code>0</code>, <code>'0'</code> and <code>'Off'</code>, but doesn't work.</li>
<li>Ran <code>grep -1R WP_POST_REVISIONS *</code> and <code>grep -1R AUTOSAVE_INTERVAL *</code> with the following result:
<blockquote>
<p>root@webtest:# grep -lR WP_POST_REVISIONS *<br>
wp-config.php<br>
wp-includes/default-constants.php<br>
wp-includes/revision.php<br>
root@webtest:# grep -lR AUTOSAVE_INTERVAL *<br>
wp-config.php<br>
wp-includes/script-loader.php<br>
wp-includes/default-constants.php<br>
wp-includes/class-wp-customize-manager.php</p>
</blockquote></li>
</ul>
<p>I really am out of any other idea to try.</p>
<hr>
<p>I'm using Wordpress 4.7.2, running on PHP 5.4 with the following modules loaded:</p>
<p><a href="https://i.stack.imgur.com/6kH47.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/6kH47.png" alt="loaded modules"></a></p>
<p>There is no op-cache working in the server. Just those options.</p>
<p>PHP was configured with the following options:</p>
<pre><code>'./configure' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' '--libexecdir=/usr/libexec' '--sharedstatedir=/var/lib' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--build=x86_64-redhat-linux-gnu' '--host=x86_64-redhat-linux-gnu' '--target=x86_64-redhat-linux-gnu' '--program-prefix=' '--prefix=/opt/alt/php54' '--exec-prefix=/opt/alt/php54' '--bindir=/opt/alt/php54/usr/bin' '--sbindir=/opt/alt/php54/usr/sbin' '--sysconfdir=/opt/alt/php54/etc' '--datadir=/opt/alt/php54/usr/share' '--includedir=/opt/alt/php54/usr/include' '--libdir=/opt/alt/php54/usr/lib64' '--libexecdir=/opt/alt/php54/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/opt/alt/php54/usr/share/man' '--infodir=/opt/alt/php54/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib64' '--with-config-file-path=/opt/alt/php54/etc' '--with-config-file-scan-dir=/opt/alt/php54/link/conf' '--with-exec-dir=/usr/bin' '--with-layout=GNU' '--disable-debug' '--disable-rpath' '--without-pear' '--without-gdbm' '--with-pic' '--with-zlib' '--with-bz2' '--with-gettext' '--with-gmp' '--with-iconv' '--with-openssl' '--with-kerberos' '--with-mhash' '--with-readline' '--with-pcre-regex=/opt/alt/pcre/usr' '--with-libxml-dir=/opt/alt/libxml2/usr' '--with-curl=/opt/alt/curlssl/usr' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-shmop' '--enable-calendar' '--enable-xml' '--enable-force-cgi-redirect' '--enable-fastcgi' '--enable-pcntl' '--enable-bcmath=shared' '--enable-dba=shared' '--with-db4=/usr' '--enable-dbx=shared,/usr' '--enable-dom=shared' '--enable-fileinfo=shared' '--enable-intl=shared' '--enable-json=shared' '--enable-mbstring=shared' '--enable-mbregex' '--enable-pdo=shared' '--enable-phar=shared' '--enable-posix=shared' '--enable-soap=shared' '--enable-sockets=shared' '--enable-sqlite3=shared,/opt/alt/sqlite/usr' '--enable-sysvsem=shared' '--enable-sysvshm=shared' '--enable-sysvmsg=shared' '--enable-wddx=shared' '--enable-xmlreader=shared' '--enable-xmlwriter=shared' '--enable-zip=shared' '--with-gd=shared' '--enable-gd-native-ttf' '--with-jpeg-dir=/usr' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--with-xpm-dir=/usr' '--with-t1lib=/opt/alt/t1lib/usr' '--with-imap=shared' '--with-imap-ssl' '--with-xmlrpc=shared' '--with-ldap=shared' '--with-ldap-sasl' '--with-pgsql=shared' '--with-snmp=shared,/usr' '--enable-ucd-snmp-hack' '--with-xsl=shared,/usr' '--with-pdo-odbc=shared,unixODBC,/usr' '--with-pdo-pgsql=shared,/usr' '--with-pdo-sqlite=shared,/opt/alt/sqlite/usr' '--with-mssql=shared,/opt/alt/freetds/usr' '--with-interbase=shared,/usr' '--with-pdo-firebird=shared,/usr' '--with-pdo-dblib=shared,/opt/alt/freetds/usr' '--with-mcrypt=shared,/usr' '--with-tidy=shared,/usr' '--with-recode=shared,/usr' '--with-enchant=shared,/usr' '--with-pspell=shared' '--with-unixODBC=shared,/usr' '--with-icu-dir=/opt/alt/libicu/usr' '--with-sybase-ct=shared,/opt/alt/freetds/usr'
</code></pre>
<hr>
<p>As a testing point, I tried to run it on PHP 5.6, with the same results, with the following modules:</p>
<p><a href="https://i.stack.imgur.com/ezCyR.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/ezCyR.png" alt="php 5.6"></a></p>
| [
{
"answer_id": 257487,
"author": "bueltge",
"author_id": 170,
"author_profile": "https://wordpress.stackexchange.com/users/170",
"pm_score": 2,
"selected": false,
"text": "<p>Remove the date param or use the right format for the time stamp, like <code>date('Y-m-d H:i:s'),</code> But it i... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257489",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/89236/"
] | I've been tasked to move a website into a new domain, and I've encontered this weird issue.
On the homepage, I always see these:
>
> Notice: Constant AUTOSAVE\_INTERVAL already defined in /home/gturnat/public\_html/wp-config.php on line 99
>
>
> Notice: Constant WP\_POST\_REVISIONS already defined in /home/gturnat/public\_html/wp-config.php on line 100
>
>
>
---
What I have tried:
* [Notice: Constant WP\_POST\_REVISIONS already defined](https://wordpress.stackexchange.com/q/158075/89236) suggests commenting the constants on `default-constants.php`, but it doesn't work.
* Settings `display_errors` to `0`, `'0'` or `'Off'` does nothing.
* Running `error_reporting(0)` will still display the errors.
* Creating a `mu-plugin` ([As suggested on How can I stop PHP notices from appearing in wordpress?](https://stackoverflow.com/a/27997023)).
Nothing happens and the plugin isn't even loaded.
The errors still keep showing up.
* Tried to comment out the lines in `wp-config.php`, but didn't work. The notices are still there.
* Removed the lines **entirelly** and moved them around `wp-config.php`, but the warnings insist it is on line 99 and 100.
Causing a syntax error inside `wp-config.php` does lead to an error being logged, which means that the file isn't cached.
* Tried to enable and disable the debug mode, set `display_errors` to `false`, `0`, `'0'` and `'Off'`, but doesn't work.
* Ran `grep -1R WP_POST_REVISIONS *` and `grep -1R AUTOSAVE_INTERVAL *` with the following result:
>
> root@webtest:# grep -lR WP\_POST\_REVISIONS \*
>
> wp-config.php
>
> wp-includes/default-constants.php
>
> wp-includes/revision.php
>
> root@webtest:# grep -lR AUTOSAVE\_INTERVAL \*
>
> wp-config.php
>
> wp-includes/script-loader.php
>
> wp-includes/default-constants.php
>
> wp-includes/class-wp-customize-manager.php
>
>
>
I really am out of any other idea to try.
---
I'm using Wordpress 4.7.2, running on PHP 5.4 with the following modules loaded:
[](https://i.stack.imgur.com/6kH47.png)
There is no op-cache working in the server. Just those options.
PHP was configured with the following options:
```
'./configure' '--prefix=/usr' '--exec-prefix=/usr' '--bindir=/usr/bin' '--sbindir=/usr/sbin' '--sysconfdir=/etc' '--datadir=/usr/share' '--includedir=/usr/include' '--libdir=/usr/lib64' '--libexecdir=/usr/libexec' '--sharedstatedir=/var/lib' '--mandir=/usr/share/man' '--infodir=/usr/share/info' '--build=x86_64-redhat-linux-gnu' '--host=x86_64-redhat-linux-gnu' '--target=x86_64-redhat-linux-gnu' '--program-prefix=' '--prefix=/opt/alt/php54' '--exec-prefix=/opt/alt/php54' '--bindir=/opt/alt/php54/usr/bin' '--sbindir=/opt/alt/php54/usr/sbin' '--sysconfdir=/opt/alt/php54/etc' '--datadir=/opt/alt/php54/usr/share' '--includedir=/opt/alt/php54/usr/include' '--libdir=/opt/alt/php54/usr/lib64' '--libexecdir=/opt/alt/php54/usr/libexec' '--localstatedir=/var' '--sharedstatedir=/usr/com' '--mandir=/opt/alt/php54/usr/share/man' '--infodir=/opt/alt/php54/usr/share/info' '--cache-file=../config.cache' '--with-libdir=lib64' '--with-config-file-path=/opt/alt/php54/etc' '--with-config-file-scan-dir=/opt/alt/php54/link/conf' '--with-exec-dir=/usr/bin' '--with-layout=GNU' '--disable-debug' '--disable-rpath' '--without-pear' '--without-gdbm' '--with-pic' '--with-zlib' '--with-bz2' '--with-gettext' '--with-gmp' '--with-iconv' '--with-openssl' '--with-kerberos' '--with-mhash' '--with-readline' '--with-pcre-regex=/opt/alt/pcre/usr' '--with-libxml-dir=/opt/alt/libxml2/usr' '--with-curl=/opt/alt/curlssl/usr' '--enable-exif' '--enable-ftp' '--enable-magic-quotes' '--enable-shmop' '--enable-calendar' '--enable-xml' '--enable-force-cgi-redirect' '--enable-fastcgi' '--enable-pcntl' '--enable-bcmath=shared' '--enable-dba=shared' '--with-db4=/usr' '--enable-dbx=shared,/usr' '--enable-dom=shared' '--enable-fileinfo=shared' '--enable-intl=shared' '--enable-json=shared' '--enable-mbstring=shared' '--enable-mbregex' '--enable-pdo=shared' '--enable-phar=shared' '--enable-posix=shared' '--enable-soap=shared' '--enable-sockets=shared' '--enable-sqlite3=shared,/opt/alt/sqlite/usr' '--enable-sysvsem=shared' '--enable-sysvshm=shared' '--enable-sysvmsg=shared' '--enable-wddx=shared' '--enable-xmlreader=shared' '--enable-xmlwriter=shared' '--enable-zip=shared' '--with-gd=shared' '--enable-gd-native-ttf' '--with-jpeg-dir=/usr' '--with-freetype-dir=/usr' '--with-png-dir=/usr' '--with-xpm-dir=/usr' '--with-t1lib=/opt/alt/t1lib/usr' '--with-imap=shared' '--with-imap-ssl' '--with-xmlrpc=shared' '--with-ldap=shared' '--with-ldap-sasl' '--with-pgsql=shared' '--with-snmp=shared,/usr' '--enable-ucd-snmp-hack' '--with-xsl=shared,/usr' '--with-pdo-odbc=shared,unixODBC,/usr' '--with-pdo-pgsql=shared,/usr' '--with-pdo-sqlite=shared,/opt/alt/sqlite/usr' '--with-mssql=shared,/opt/alt/freetds/usr' '--with-interbase=shared,/usr' '--with-pdo-firebird=shared,/usr' '--with-pdo-dblib=shared,/opt/alt/freetds/usr' '--with-mcrypt=shared,/usr' '--with-tidy=shared,/usr' '--with-recode=shared,/usr' '--with-enchant=shared,/usr' '--with-pspell=shared' '--with-unixODBC=shared,/usr' '--with-icu-dir=/opt/alt/libicu/usr' '--with-sybase-ct=shared,/opt/alt/freetds/usr'
```
---
As a testing point, I tried to run it on PHP 5.6, with the same results, with the following modules:
[](https://i.stack.imgur.com/ezCyR.png) | Remove the date param or use the right format for the time stamp, like `date('Y-m-d H:i:s'),` But it is not necessary, WP use the current timestamp on the insert post time. |
257,499 | <p>I'm using a function to filter the_title, adding a string onto the end, but would also like to return the original title, unfiltered on the same page. Is there a way to get the title without it being filtered? </p>
| [
{
"answer_id": 257501,
"author": "engelen",
"author_id": 40403,
"author_profile": "https://wordpress.stackexchange.com/users/40403",
"pm_score": 3,
"selected": true,
"text": "<p>There's a few ways to do this, but I would argue that the preferred way is, in general, fetching the <code>pos... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257499",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/45504/"
] | I'm using a function to filter the\_title, adding a string onto the end, but would also like to return the original title, unfiltered on the same page. Is there a way to get the title without it being filtered? | There's a few ways to do this, but I would argue that the preferred way is, in general, fetching the `post_title` attribute from the post object. This does not depend on removing all filters for a certain function and adding them back later — the latter requires you to directly access the global `$wp_filter`.
[`get_post`](https://codex.wordpress.org/Function_Reference/get_post) retrieves the post object for a post ID, and the post object, on construction, populates all post fields with the fields from the database, without applying any filtering.
Thus, your code would simply be
```
$title = get_post( $post_id )->post_title;
```
If the post with ID `$post_id` is not guaranteed to exist, be sure to check whether the returned value from `get_post` is a post object.
NB another approach is to use `get_post_field( 'post_title', $post_id )`, which by default only has the filter `'post_title'` applied to it (and not the `the_title` filter). However, as @PatJ kindly pointed out, using the optional `$context` parameter, you can get the raw value using the context `"raw"`:
```
get_post_field( 'post_title', $post_id, 'raw' );
``` |
257,542 | <p>All I did was adding this in my functions.php file:</p>
<pre><code>function save_nb_image()
{
global $wpdb;
$id = $_POST['id'];
$file = wp_get_attachment_url($id);
if ( !is_wp_error($id) )
{
$meta = wp_generate_attachment_metadata($id, $file);
$meta = nb_image_crop($meta);
wp_update_attachment_metadata($id, $meta);
}
wp_die();
}
add_action( 'wp_ajax_nb-image-autofix', 'save_nb_image' );
</code></pre>
<p>Then I tried to call it from a custom button in image edit form. Something didn't worked because nothing happened.</p>
<p>Then little later when I went into the Media Library again, the images wouldn't load. Chrome Console log said something about problem with mixed content. I have pretty recently changed to SSL/https so I thought that might been the problem. Although it's strange that change for some weeks ago make this affect now. I have been in media library a lot of times after that change and everything has worked perfectly.</p>
<p>But anyway, IF there is a SSL problem, I added "SSL Insecure Content Fixer" plugin to let that clear out everything. And I ran that plugin and then went in to the media library again. The console errors was now gone. But the images is still not loading. There is just a load spinner going on forever.</p>
<p>I have also tried activate the debug mode from wp_config but there is no related errors.</p>
<p>I have also tried re-installing the Wordpress version from Dashboard > Updates.</p>
<p>I have also of course tried remove the code I mentioned above.</p>
<p>What is there else to try?</p>
<p><strong>Edit:</strong> I think it might be a database issue. Cause I even tried to remove all the files except /wp-content folder and wp-config.php file. And installed the older WP 4.4 version. Then went in and updated to latest version. After that: Still no images in grid view....</p>
<p><strong>Edit, 27 feb 2017:</strong> I have found out that <code>wp_get_attachment_url()</code> was the wrong function to use since I wanted the absolute path and not the URL. So the right function to use is <code>get_attached_file()</code>. When I used the <code>wp_get_attachment_url()</code> function the ajax was loading very long time and returned a lot of strange code that I suspect was the image on some kind of code format. After changing to <code>get_attached_file()</code> the loading was much faster and the functionality of everything I wanted with the code did work as expected. However, maybe something with the earlier code made a mess in the database causing the Grid Mode problem?</p>
| [
{
"answer_id": 257576,
"author": "Purple Haze Design Group",
"author_id": 113974,
"author_profile": "https://wordpress.stackexchange.com/users/113974",
"pm_score": 0,
"selected": false,
"text": "<p>I had a similar issue recently. I had moved over a theme with some plugin specific code in... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257542",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/3216/"
] | All I did was adding this in my functions.php file:
```
function save_nb_image()
{
global $wpdb;
$id = $_POST['id'];
$file = wp_get_attachment_url($id);
if ( !is_wp_error($id) )
{
$meta = wp_generate_attachment_metadata($id, $file);
$meta = nb_image_crop($meta);
wp_update_attachment_metadata($id, $meta);
}
wp_die();
}
add_action( 'wp_ajax_nb-image-autofix', 'save_nb_image' );
```
Then I tried to call it from a custom button in image edit form. Something didn't worked because nothing happened.
Then little later when I went into the Media Library again, the images wouldn't load. Chrome Console log said something about problem with mixed content. I have pretty recently changed to SSL/https so I thought that might been the problem. Although it's strange that change for some weeks ago make this affect now. I have been in media library a lot of times after that change and everything has worked perfectly.
But anyway, IF there is a SSL problem, I added "SSL Insecure Content Fixer" plugin to let that clear out everything. And I ran that plugin and then went in to the media library again. The console errors was now gone. But the images is still not loading. There is just a load spinner going on forever.
I have also tried activate the debug mode from wp\_config but there is no related errors.
I have also tried re-installing the Wordpress version from Dashboard > Updates.
I have also of course tried remove the code I mentioned above.
What is there else to try?
**Edit:** I think it might be a database issue. Cause I even tried to remove all the files except /wp-content folder and wp-config.php file. And installed the older WP 4.4 version. Then went in and updated to latest version. After that: Still no images in grid view....
**Edit, 27 feb 2017:** I have found out that `wp_get_attachment_url()` was the wrong function to use since I wanted the absolute path and not the URL. So the right function to use is `get_attached_file()`. When I used the `wp_get_attachment_url()` function the ajax was loading very long time and returned a lot of strange code that I suspect was the image on some kind of code format. After changing to `get_attached_file()` the loading was much faster and the functionality of everything I wanted with the code did work as expected. However, maybe something with the earlier code made a mess in the database causing the Grid Mode problem? | Problem is now solved. Thanks to user "blobfolio" [here](https://core.trac.wordpress.org/ticket/39974#comment:2):
>
> It sounds like you may have corrupted the image metadata. Have you
> tried running a plugin like
> <https://wordpress.org/plugins/force-regenerate-thumbnails/> to
> regenerate the images/meta?
>
>
>
**Solution:**
So the solution is to force regenerate all the thumbnails. For example using the plugin mentioned above in the quote. |
257,571 | <p>On my single.php page I am trying to create a function to give me a custom length excerpt of a specific post by ID.</p>
<p>Below are my two functions I am running.</p>
<pre><code>/* Custom get_the_excerpt to allow getting Post excerpt by ID */
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt($post);
$post = $save_post;
return $output;
}
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."&#8230";
echo $excerpt;
}
</code></pre>
<p>What I'm using to call the function.</p>
<pre><code><?php $previous = get_previous_post();
echo excerpt('30', $previous -> ID); ?>
</code></pre>
<p>The issue I am running into is $post is giving me the previous post information, however, when I pass that into get_the_excerpt it returns the current post excerpt rather than the previous post excerpt.</p>
<p>EDIT</p>
<p>Changed function to this after several people told me I can just pass the $post_id to get_the_excerpt()</p>
<pre><code> /* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."&#8230";
echo $excerpt;
}
</code></pre>
<p>Still no change.</p>
| [
{
"answer_id": 257572,
"author": "MaximOrlovsky",
"author_id": 15294,
"author_profile": "https://wordpress.stackexchange.com/users/15294",
"pm_score": 3,
"selected": true,
"text": "<p>Try this one</p>\n\n<pre><code>/* Change Excerpt length */\nfunction excerpt($num, $post_id) { // remove... | 2017/02/22 | [
"https://wordpress.stackexchange.com/questions/257571",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/112804/"
] | On my single.php page I am trying to create a function to give me a custom length excerpt of a specific post by ID.
Below are my two functions I am running.
```
/* Custom get_the_excerpt to allow getting Post excerpt by ID */
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
$output = get_the_excerpt($post);
$post = $save_post;
return $output;
}
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', custom_get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
```
What I'm using to call the function.
```
<?php $previous = get_previous_post();
echo excerpt('30', $previous -> ID); ?>
```
The issue I am running into is $post is giving me the previous post information, however, when I pass that into get\_the\_excerpt it returns the current post excerpt rather than the previous post excerpt.
EDIT
Changed function to this after several people told me I can just pass the $post\_id to get\_the\_excerpt()
```
/* Change Excerpt length */
function excerpt($num, $post_id = '') {
$limit = $num+1;
$excerpt = explode(' ', get_the_excerpt($post_id), $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
```
Still no change. | Try this one
```
/* Change Excerpt length */
function excerpt($num, $post_id) { // removed empty default value
$limit = $num+1;
$excerpt = apply_filters('the_excerpt', get_post_field('post_excerpt', $post_id));
$excerpt = explode(' ', $excerpt, $limit);
array_pop($excerpt);
$excerpt = implode(" ",$excerpt)."…";
echo $excerpt;
}
```
Another solution - using `setup_postdata($post);` and `wp_reset_postdata();`
```
function custom_get_the_excerpt($post_id) {
global $post;
$save_post = $post;
$post = get_post($post_id);
setup_postdata($post);
$output = get_the_excerpt($post);
wp_reset_postdata();
$post = $save_post;
return $output;
}
``` |
257,586 | <p>I've always used @import for the css in my child-theme which i'm now told is bad practice.</p>
<p>What is the best way to set up a child theme going forward? The latest solution on the wordpress codex seems really complex / highly confusing?</p>
<p>There must be a way to do a relatively simple enqueue in my child-theme's functions.php surely?</p>
<p>Any help would be awesome. I feel completely lost / useless trying to find any succinct info on this.</p>
<p>Emily</p>
| [
{
"answer_id": 257588,
"author": "Den Isahac",
"author_id": 113233,
"author_profile": "https://wordpress.stackexchange.com/users/113233",
"pm_score": 2,
"selected": false,
"text": "<p>I think this is the specific code you're looking for, this can be found in the WordPress Codex <a href=\... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257586",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/106972/"
] | I've always used @import for the css in my child-theme which i'm now told is bad practice.
What is the best way to set up a child theme going forward? The latest solution on the wordpress codex seems really complex / highly confusing?
There must be a way to do a relatively simple enqueue in my child-theme's functions.php surely?
Any help would be awesome. I feel completely lost / useless trying to find any succinct info on this.
Emily | The code that is in [codex](https://codex.wordpress.org/Child_Themes#How_to_Create_a_Child_Theme) for queuing the style of the parent theme instead of using `@import`, is not well commented, so i will comment it more, so you have this:
```
<?php
function my_theme_enqueue_styles() {
$parent_style = 'parent-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');
?>
```
1.- line:
```
$parent_style = 'parent-style';
```
this is literally a string name that you are giving to the theme stylesheet, it will be the `$handle` of the stylesheet you are queuing, it can be what you want, by example `'divi-style'`, in the `HTML` it will be used as the `ID` like this `<link rel="stylesheet" id="divi-style" ...`
2.- line:
```
wp_enqueue_style($parent_style, get_template_directory_uri() . '/style.css');
```
its registering the stylesheet and queuing it, when its registering it, it will use the name of the first parameter in this case it will be `'parent-style'`, also its using `get_template_directory_uri()` to get the path to the `parent theme` stylesheet.
3.- line:
```
wp_enqueue_style('child-style',
get_stylesheet_directory_uri() . '/style.css',
array($parent_style),
wp_get_theme()->get('Version')
);
```
this is registering and queuing the child theme stylesheet (the current theme stylesheet), this is the usual procedure for a theme, each parameter its already explained [here](https://developer.wordpress.org/reference/functions/wp_enqueue_style/), for the example:
* `'child-style'` - this is the name of this stylesheet the `$handle`
* `get_stylesheet_directory_uri() . '/style.css'` - this is the path to
the stylesheet file.
* `array($parent_style)` - this is the array of stylesheets that we need
to run before our stylesheet runs we cant put actual paths that is
why we name them with a `$handle`, in this case we need the parent stylesheet to run first (its a dependency)
* `wp_get_theme()->get('Version')` - this is the number version that
will be at the end of the stylesheet `URL` like this `/style.css?ver=1.0`, this is for cache purposes, the standard is that you update the version so the latest file is loaded and not a cached version, you dont want to change that number in all the files where you use it right? so use `wp_get_theme()->get('Version')` it will get the version that is in your `style.css` file (not the parent one).
so if you want the resumed version it will be like this:
```
<?php
function my_theme_enqueue_styles() {
//load the parent stylesheet
wp_enqueue_style( 'parent-style', get_template_directory_uri() . '/style.css' );
//load the child stylesheet but after the parent stylesheet
wp_enqueue_style( 'child-style', get_stylesheet_directory_uri() . '/style.css', array( 'parent-style' ));
}
add_action( 'wp_enqueue_scripts', 'my_theme_enqueue_styles' );
?>
``` |
257,592 | <p>im trying to save different value of radio buttons on same name, it works and was able to make checked appear if the correct value is saved. </p>
<p><a href="https://i.stack.imgur.com/zz0H4.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/zz0H4.png" alt=""></a>
<br>As you can see on the screenshot ABOVE (which is taken on view-source:), it the correct selected input is CHECKED already however even if it's check you can see on the screenshow BELOW that it doesn't display as checked. <br></p>
<p><a href="https://i.stack.imgur.com/UP1zH.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/UP1zH.png" alt="enter image description here"></a></p>
<p><br>
It's already checked but not displaying , i dont know</p>
| [
{
"answer_id": 257608,
"author": "Jignesh Patel",
"author_id": 111556,
"author_profile": "https://wordpress.stackexchange.com/users/111556",
"pm_score": 1,
"selected": false,
"text": "<p>I think you can Also try it checked=\"checked\" some time issue with checked so just try it.</p>\n\n<... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257592",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110405/"
] | im trying to save different value of radio buttons on same name, it works and was able to make checked appear if the correct value is saved.
[](https://i.stack.imgur.com/zz0H4.png)
As you can see on the screenshot ABOVE (which is taken on view-source:), it the correct selected input is CHECKED already however even if it's check you can see on the screenshow BELOW that it doesn't display as checked.
[](https://i.stack.imgur.com/UP1zH.png)
It's already checked but not displaying , i dont know | In the WordPress back-end you have to use `checked="checked"` (stricter XHTML), because the CSS will not be applied otherwise:
```
<input type="radio" name="colors" id="blue" checked="checked">
```
this is the CSS that applies the blue dot:
[](https://i.stack.imgur.com/4PD06.png)
WordPress already provides a function for this [checked()](https://developer.wordpress.org/reference/functions/checked/)
```
<input type="radio" name="colors" id="blue" <?php checked( 'red', get_option( 'color' ) ); ?> />
```
so you dont have to do an `If` and `echo`. |
257,634 | <p>I am using the following code to print another image that is in my images folder in casa a post has no thumbnail but it is giving me errors on the else statement saying that there is a syntax error:</p>
<pre><code><?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else {
echo '<figure><img src="<?php echo get_bloginfo( 'template_directory' ); ?>/images/stone.jpg" /></figure></a>';
}
?>
</code></pre>
<p>However, if I paste this code:</p>
<pre><code><?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else{
}
?>
</code></pre>
<p>It gives no error but also it does not display the thumbnail</p>
<p>Hope you can help</p>
| [
{
"answer_id": 257638,
"author": "Sonali",
"author_id": 84167,
"author_profile": "https://wordpress.stackexchange.com/users/84167",
"pm_score": 2,
"selected": true,
"text": "<p>Try this inside else condition where no image assigned.</p>\n\n<pre><code> if (has_post_thumbnail()) {\n ... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257634",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/99178/"
] | I am using the following code to print another image that is in my images folder in casa a post has no thumbnail but it is giving me errors on the else statement saying that there is a syntax error:
```
<?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else {
echo '<figure><img src="<?php echo get_bloginfo( 'template_directory' ); ?>/images/stone.jpg" /></figure></a>';
}
?>
```
However, if I paste this code:
```
<?php if ( has_post_thumbnail() ) {
echo '<a href="<?php the_permalink(); ?>"> <figure><?php the_post_thumbnail(); ?></figure></a>';
}
else{
}
?>
```
It gives no error but also it does not display the thumbnail
Hope you can help | Try this inside else condition where no image assigned.
```
if (has_post_thumbnail()) {
?><a href="<?php the_post_thumbnail_url(); ?>">
<?php the_post_thumbnail();?>
</a><?php
} else {
echo '<figure><a href="add_link_here"><img src="'.get_bloginfo("stylesheet_directory").'/images/stone.jpg" /></figure></a>';
}
``` |
257,645 | <p>Current structure is <code>/%year%/%monthnum%/%postname%.html</code> </p>
<p>Desired structure is <code>/%postname%/</code></p>
<p>Since we are already positioned with urls like <code>domain.com/2015/04/example-post.html</code>, we want people to be redirected to <code>domain.com/example-post/</code>.</p>
<p>I already tried installing some plugins, like <strong>Simple 301 Redirects</strong>, which looked good since it seems to work with rules as shown in the image below:</p>
<p><a href="https://i.stack.imgur.com/uEWro.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/uEWro.png" alt="enter image description here"></a></p>
<p>But it didn't worked to us, we get 404 from old urls :(</p>
<p>Adding 301 rules manually is not an options since we have thousands of posts, doing it with a script would be a easy option but I don't think is optimal to have thousands of 301 rules, would it be?</p>
<p>Any other suggestion?</p>
| [
{
"answer_id": 257647,
"author": "Mc Kernel",
"author_id": 107424,
"author_profile": "https://wordpress.stackexchange.com/users/107424",
"pm_score": 0,
"selected": false,
"text": "<p>This tool did the work for me: <a href=\"https://yoast.com/research/permalink-helper.php\" rel=\"nofollow... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257645",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/107424/"
] | Current structure is `/%year%/%monthnum%/%postname%.html`
Desired structure is `/%postname%/`
Since we are already positioned with urls like `domain.com/2015/04/example-post.html`, we want people to be redirected to `domain.com/example-post/`.
I already tried installing some plugins, like **Simple 301 Redirects**, which looked good since it seems to work with rules as shown in the image below:
[](https://i.stack.imgur.com/uEWro.png)
But it didn't worked to us, we get 404 from old urls :(
Adding 301 rules manually is not an options since we have thousands of posts, doing it with a script would be a easy option but I don't think is optimal to have thousands of 301 rules, would it be?
Any other suggestion? | You don't need a plugin to achieve your goal. Use server redirect in the `.htaccess` file because it will not load the processor to interpret the WordPress PHP code and will not consume time. The redirect will be completed before the WordPress runs.
```
RewriteRule ^[0-9]+/[0-9]+/(.*)\.html$ /$1 [R=301,L]
```
Where
* `[0-9]+/` is the numeric year and month
* `(.*)` is the part we'll use below (`example-post` in your case)
* `/$1` is the part we've got from the above
301 redirect is completely perfect for SEO. |
257,662 | <p>I am working on a plugin which we need for education website. I have added 3-4 Page templates within my plugin so that we can call when plugin is activated.</p>
<p>Till WordPress <code>4.7</code>, it was working perfectly; but as I upgraded WordPress to the latest (from <code>4.6.3</code>), page templates don't even show in page attribute section.</p>
<p>Here is the code which was working fine with older versions (before <code>4.7</code>):</p>
<pre><code>add_action( 'wp_loaded', 'add_my_templates' );
function add_my_templates() {
if( is_admin() ){
global $wp_object_cache;
$current_theme = wp_get_theme();
$templates = $current_theme->get_page_templates();
$hash = md5( $current_theme->theme_root . '/'. $current_theme->stylesheet );
$templates = $wp_object_cache->get( 'page_templates-'. $hash, 'themes' );
$templates['templates/exams.php'] = __('Exams');
$templates['templates/colleges.php'] = __('Colleges');
$templates['templates/study_home.php'] = __('Study Home');
$templates['templates/study_job_home.php'] = __('Study Job Home');
wp_cache_replace( 'page_templates-'. $hash, $templates, 'themes' );
}
else {
add_filter( 'page_template', 'get_my_template', 1 );
}
}
function get_my_template( $template ) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if( $page_template == 'templates/study_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_home.php";
}
if( $page_template == 'templates/study_job_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_job_home.php";
}
if( $page_template == 'templates/exams.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/exams.php";
}
if( $page_template == 'templates/colleges.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/colleges.php";
}
return $template;
}
</code></pre>
<p>I am searching for the solution from last 2 days, but no luck!</p>
| [
{
"answer_id": 257666,
"author": "Mark Kaplun",
"author_id": 23970,
"author_profile": "https://wordpress.stackexchange.com/users/23970",
"pm_score": 0,
"selected": false,
"text": "<p>Your caching insertion code looks very weird and depending on some specific way core calculates hashes fo... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257662",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/105597/"
] | I am working on a plugin which we need for education website. I have added 3-4 Page templates within my plugin so that we can call when plugin is activated.
Till WordPress `4.7`, it was working perfectly; but as I upgraded WordPress to the latest (from `4.6.3`), page templates don't even show in page attribute section.
Here is the code which was working fine with older versions (before `4.7`):
```
add_action( 'wp_loaded', 'add_my_templates' );
function add_my_templates() {
if( is_admin() ){
global $wp_object_cache;
$current_theme = wp_get_theme();
$templates = $current_theme->get_page_templates();
$hash = md5( $current_theme->theme_root . '/'. $current_theme->stylesheet );
$templates = $wp_object_cache->get( 'page_templates-'. $hash, 'themes' );
$templates['templates/exams.php'] = __('Exams');
$templates['templates/colleges.php'] = __('Colleges');
$templates['templates/study_home.php'] = __('Study Home');
$templates['templates/study_job_home.php'] = __('Study Job Home');
wp_cache_replace( 'page_templates-'. $hash, $templates, 'themes' );
}
else {
add_filter( 'page_template', 'get_my_template', 1 );
}
}
function get_my_template( $template ) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if( $page_template == 'templates/study_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_home.php";
}
if( $page_template == 'templates/study_job_home.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/study_job_home.php";
}
if( $page_template == 'templates/exams.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/exams.php";
}
if( $page_template == 'templates/colleges.php' ) {
$template = plugin_dir_path(__FILE__) . "templates/colleges.php";
}
return $template;
}
```
I am searching for the solution from last 2 days, but no luck! | The Problem:
============
As [Mark suggested already](https://wordpress.stackexchange.com/a/257666/110572), your template loading by manipulating cache is far from standard practice. With these sort of cache alteration, even if you modify your CODE to work with WordPress `4.7+`, there is no guarantee that you'll not find similar problems in future updates. So better use any of the solutions mentioned below:
Theme Solution:
===============
Instead of assigning templates form a plugin, you can have actual [page templates](https://developer.wordpress.org/themes/template-files-section/page-templates/) in the active theme. Your active theme is the **recommended** place to have these page templates.
Plugin Solution
===============
However, if you have to assign these templates with your plugin for some reason, then use the [`theme_page_templates`](https://developer.wordpress.org/reference/hooks/theme_page_templates/) hook to do so. It'll work for WordPress `4.4+`.
Following is the rewrite of your CODE using `theme_page_templates` filter hook:
```
function get_my_template( $template ) {
$post = get_post();
$page_template = get_post_meta( $post->ID, '_wp_page_template', true );
if( $page_template == 'templates/study_home.php' ){
return plugin_dir_path(__FILE__) . "templates/study_home.php";
}
if( $page_template == 'templates/study_job_home.php' ){
return plugin_dir_path(__FILE__) . "templates/study_job_home.php";
}
if( $page_template == 'templates/exams.php' ){
return plugin_dir_path(__FILE__) . "templates/exams.php";
}
if( $page_template == 'templates/colleges.php' ){
return plugin_dir_path(__FILE__) . "templates/colleges.php";
}
return $template;
}
function filter_admin_page_templates( $templates ) {
$templates['templates/exams.php'] = __('Exams');
$templates['templates/colleges.php'] = __('Colleges');
$templates['templates/study_home.php'] = __('Study Home');
$templates['templates/study_job_home.php'] = __('Study Job Home');
return $templates;
}
function add_my_templates() {
if( is_admin() ) {
add_filter( 'theme_page_templates', 'filter_admin_page_templates' );
}
else {
add_filter( 'page_template', 'get_my_template', 1 );
}
}
add_action( 'wp_loaded', 'add_my_templates' );
```
Use the above CODE instead of the CODE you've provided. It'll work for any WordPress version `4.4` and later. I've tested it for WordPress `4.7.2` & it works fine. |
257,667 | <p>I've been looking and looking for a solution for my problem but i have been unable to find anything. </p>
<p>I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.</p>
<p>Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words?</p>
| [
{
"answer_id": 257672,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 3,
"selected": true,
"text": "<p>There's a <a href=\"https://developer.wordpress.org/reference/hooks/validate_username/\" rel=\"nofollow noreferr... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257667",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/80842/"
] | I've been looking and looking for a solution for my problem but i have been unable to find anything.
I have found a plugin that allow me to restrict certain usernames, I found even a function but there is nothing that allows me to restrict partially matching usernames, there is nothing to prevent users to register under names like "joeadmin" or "seanadmin" and etc.
Is there anything that can be done to prevent users to register anything that contain "admin" and other prohibited words? | There's a [`validate_username`](https://developer.wordpress.org/reference/hooks/validate_username/) filter hook that is used by [`validate_user()`](https://developer.wordpress.org/reference/functions/validate_username/) which is in turn used by [`register_new_user()`](https://developer.wordpress.org/reference/functions/register_new_user/).
So you can disallow usernames containing `admin` or other prohibited terms:
```
add_filter( 'validate_username', 'wpse257667_check_username', 10, 2 );
function wpse257667_check_username( $valid, $username ) {
// This array can grow as large as needed.
$disallowed = array( 'admin', 'other_disallowed_string' );
foreach( $disallowed as $string ) {
// If any disallowed string is in the username,
// mark $valid as false.
if ( $valid && false !== strpos( $username, $string ) ) {
$valid = false;
}
}
return $valid;
}
```
You can add this code to your theme's `functions.php` file or (preferably) [make it a plugin](https://codex.wordpress.org/Writing_a_Plugin).
References
----------
* [`validate_username` filter hook](https://developer.wordpress.org/reference/hooks/validate_username/)
* [`validate_user()`](https://developer.wordpress.org/reference/functions/validate_username/)
* [`register_new_user()`](https://developer.wordpress.org/reference/functions/register_new_user/)
* [Writing a plugin](https://codex.wordpress.org/Writing_a_Plugin) |
257,684 | <p>Say you have 4 example domains:
1. dogsrule.com
2. dogsrule.cn
3. dogsrulecatsdrool.co.uk
4. dogsrule.au</p>
<p>Currently, each are their own WordPress sites hosted on the same server. Each are only 2 pages, the homepage which includes a form, and a thank you page.</p>
<p>Since they are such small sites and hosted on the same server, would like to consolidate if possible. One option would be to do wordpress multisite setup which may help? Would that be the best option for this scenario or...</p>
<p>Can we have a single normal WordPress install with custom pages for each site that all 4 domains points to respectively?</p>
| [
{
"answer_id": 257687,
"author": "Pat J",
"author_id": 16121,
"author_profile": "https://wordpress.stackexchange.com/users/16121",
"pm_score": 1,
"selected": false,
"text": "<p>You can use WordPress Multisite version 4.5 or higher to map domains to sites: <a href=\"https://codex.wordpres... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257684",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/5465/"
] | Say you have 4 example domains:
1. dogsrule.com
2. dogsrule.cn
3. dogsrulecatsdrool.co.uk
4. dogsrule.au
Currently, each are their own WordPress sites hosted on the same server. Each are only 2 pages, the homepage which includes a form, and a thank you page.
Since they are such small sites and hosted on the same server, would like to consolidate if possible. One option would be to do wordpress multisite setup which may help? Would that be the best option for this scenario or...
Can we have a single normal WordPress install with custom pages for each site that all 4 domains points to respectively? | Why not multisite:
==================
* Multisite installations are difficult to maintain compared to single site installations.
* Many useful plugins don't work properly on multisite installations.
* There may be SEO concern for such short web sites with basically just one page (thank you page doesn't count) that looks very similar from the names. Multisite won't solve this probable issue.
>
> I have assumed they have similar content from your example domain names, however, if the content of the four sites are very very different, then form an SEO point of view, having separate sites with a Multisite installation may be better.
>
>
>
Why not single site:
====================
* Managing multiple languages may not be easy in a single site installation if you haven't done that before.
As @Mark suggested in the comment, if you have different language contents in those sites (again just assumption based on example domain names), merging them into a single site may not be easy. You are encouraged to use plugins such as [Polylang](https://wordpress.org/plugins/polylang/) to manage multiple languages. There are thousands of multilingual sites out there running perfectly fine with WordPress. However, if it turns out to be difficult, then you may consider setting up Multisite or even keeping it as it is.
Leave them as they are?
=======================
If the following conditions are true, then may be it's better to just leave them as they are:
* Managing these multiple separate installations are not too difficult for you.
* You may have plugins that are not well tested in multisite installations.
* You have multilingual content in different sites and you have no experience with WordPress multilingual setup.
Steps for single site installation
==================================
If you decide to go for single site installation, or at least want to test it, you may follow the steps below:
1. Keep any one site (for example `dogsrule.com`) as the main site.
2. Then make the other three sites point to the main site's web root directory.
3. The main site's home page remains as is & then you create three more pages for the other three sites (for example: `dogsrule.com/cn`, `dogsrule.com/dogs-rule-cats-drool` and `dogsrule.com/au`).
4. Then you may use server rewrite rules to redirect other three domains to the corresponding pages of the main site.
For example, if your web server is Apache, then in your main site's `.htaccess` file you may use the following CODE (according to the above pages):
```
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
# redirect rules for the other three domains
RewriteCond %{HTTP_HOST} ^dogsrule\.cn$
RewriteRule . http://dogsrule.com/cn [R=301,L]
RewriteCond %{HTTP_HOST} ^dogsrulecatsdrool\.co\.uk$
RewriteRule . http://dogsrule.com/dogs-rule-cats-drool [R=301,L]
RewriteCond %{HTTP_HOST} ^dogsrule\.au$
RewriteRule . http://dogsrule.com/au [R=301,L]
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
After this you'll have just one site with four main pages (including the home page) and four thank you pages and your other domains will correctly redirect to the corresponding pages.
>
> ***Note:*** You may remove the other three sites after setting up the above, **but don't delete the domains.** Even though, effectively you'll only have one site after this, however, if you delete those domains, old bookmarks and back links will not work.
>
>
> |
257,691 | <p>I have a situation where I have to remove a term from a taxonomy. However, there are items that are linked to that taxonomy. Sometimes, these removals are temporary (ie, we stop shipping to a country, but would like items to stay linked to those countries if ever we start shipping to that country again). </p>
<p>Is there any way to 'disable' a term rather than wp_delete_term? Thanks! </p>
| [
{
"answer_id": 257727,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You can temporarily exclude your terms from the queries. Meaning that you hide them on some listing pages, ... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257691",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114041/"
] | I have a situation where I have to remove a term from a taxonomy. However, there are items that are linked to that taxonomy. Sometimes, these removals are temporary (ie, we stop shipping to a country, but would like items to stay linked to those countries if ever we start shipping to that country again).
Is there any way to 'disable' a term rather than wp\_delete\_term? Thanks! | Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.
The approach I'm taking is to store a term meta when the term is disabled and then to hook into the `get_terms_defaults` filter to strip disabled terms that would be returned by WP Core's calls to `get_terms()`, `get_the_terms()`, etc.
My plugin encapsulates all of this into a class which serves as a wrapper around `register_taxonomy()`. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies).
See `Custom_Taxonomy::enable_term()` and `Custom_Taxonmy::disable_term()` for the code that adds/deletes the relevant term meta; and see `Custom_Taxonomy::strip_disabled_terms()` for the code that strips disabled terms.
Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)
```
/**
* this class is a wrapper around register_taxonomy(), that adds additional functionality
* to allow terms in the taxonomy so registered to be "disabled".
*
* Disabled terms will NOT be returned by the various WP Core functions like get_terms(),
* get_the_terms(), etc.
*
* TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()
*/
class
Custom_Taxonomy
{
const DISABLED_TERM_META_KEY = '_shc_disabled' ;
public $name ;
public $can_disable_terms = false ;
/**
* construct an instance of Custom_Taxonomy
*
* @param $taxonomy string Taxonomy key, must not exceed 32 characters
* @param $post_types array|string post type or array of post types with which the taxonomy should be associated
* @param $args array Array or query string of arguments for registering a taxonomy
*
* params are the same as WP's register_taxonomy() except that $args may have extra keys:
*
* 'can_disable_terms' => true|false
*/
function
__construct ($taxonomy, $post_types, $args)
{
$this->name = $taxonomy ;
// modify args, if needed
$default_args = array (
'can_disable_terms' => false,
) ;
$args = wp_parse_args ($args, $default_args) ;
$this->can_disable_terms = $args['can_disable_terms'] ;
unset ($args['can_disable_terms']) ;
if ($this->can_disable_terms) {
// TODO: is there a better filter to hook into than 'get_terms_defaults'?
// I've tried 'get_terms_args', but that seems to be called too late
// in the process of builing the WP_Term_Query used by get_terms(), etc
// to have the meta_query that is added by $this->strip_disabled_terms()
add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;
}
// register the taxonomy
register_taxonomy ($taxonomy, $post_types, $args) ;
return ;
}
/**
* disable a term
*
* disabling a term will make it appear as if the term does not exist, without actually deleting it
*
* @param $term int|string|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure
*/
function
disable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;
}
/**
* enable a term
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
enable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;
}
/**
* strip disabled terms from e.g., get_terms() and get_the_terms()
*
* TODO: make sure that this works correctly given WP Core's object caching
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
strip_disabled_terms ($args, $taxonomies)
{
if (!$this->can_disable_terms) {
return ($args) ;
}
// I *think* the count('taxonomy') check is necesary because get_terms_args() is
// applied by the WP Core object_term caching infrastructure by
// passing all taxonomies for a given post_type, and we only want to
// add this restriction when we are getting the terms for just the
// this taxonomy
if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {
return ($args) ;
}
$args['meta_query'] = array (
array (
'key' => self::DISABLED_TERM_META_KEY,
'compare' => 'NOT EXISTS',
)
) ;
return ($args) ;
}
}
```
My use case
===========
I've got 2 custom post types, `type_a` and `type_b`. `type_b` has a custom taxonomy, `taxonomy_b`, the terms of which are the post\_title's of all of the posts of type `type_a`.
Only those posts of `type_a` whose `post_status` is `publish` should have their corresponding terms in `taxonomy_b` enabled. I accomplish this by hooking into `save_post_type_a` to insert the terms (if they don't already exist) and enable/disable them, and hook into `delete_post` to delete them.
If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.
Questions I still have
======================
I'm still working on this plugin and there are a few open issues around it's implementation.
1. is the `get_terms_defaults` filter that I hook into to add the meta\_query to `WP_Term_Query` the best hook to use? I've tried `get_terms_args`, but that seems to be called too late in the process of builing the WP\_Term\_Query used by get\_terms(), etc. to correctly process the meta\_query that is added by `Custom_taxonomy::strip_disabled_terms()`.
2. I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to `get_terms()` caches the terms in the taxonomy, and them the term is enabled in the same execution of `wp()` will a subsequent call to `get_terms()` include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.
If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in! |
257,696 | <p>I'm trying to edit the revelar theme for my site, I've set up my child theme, created a style.css file and successfully imported all the features from the parent theme, but no matter what I try I can't seem to make any changes to my design. I've tried everything and the code I use in my child theme's style.css file simply isn't showing up on my site. What am I doing wrong?</p>
<p>Really hope someone can help, any input is much appreciated!</p>
<p>My site is: resourcefulliving.dk</p>
<p>Best</p>
| [
{
"answer_id": 257727,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You can temporarily exclude your terms from the queries. Meaning that you hide them on some listing pages, ... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257696",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114045/"
] | I'm trying to edit the revelar theme for my site, I've set up my child theme, created a style.css file and successfully imported all the features from the parent theme, but no matter what I try I can't seem to make any changes to my design. I've tried everything and the code I use in my child theme's style.css file simply isn't showing up on my site. What am I doing wrong?
Really hope someone can help, any input is much appreciated!
My site is: resourcefulliving.dk
Best | Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.
The approach I'm taking is to store a term meta when the term is disabled and then to hook into the `get_terms_defaults` filter to strip disabled terms that would be returned by WP Core's calls to `get_terms()`, `get_the_terms()`, etc.
My plugin encapsulates all of this into a class which serves as a wrapper around `register_taxonomy()`. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies).
See `Custom_Taxonomy::enable_term()` and `Custom_Taxonmy::disable_term()` for the code that adds/deletes the relevant term meta; and see `Custom_Taxonomy::strip_disabled_terms()` for the code that strips disabled terms.
Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)
```
/**
* this class is a wrapper around register_taxonomy(), that adds additional functionality
* to allow terms in the taxonomy so registered to be "disabled".
*
* Disabled terms will NOT be returned by the various WP Core functions like get_terms(),
* get_the_terms(), etc.
*
* TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()
*/
class
Custom_Taxonomy
{
const DISABLED_TERM_META_KEY = '_shc_disabled' ;
public $name ;
public $can_disable_terms = false ;
/**
* construct an instance of Custom_Taxonomy
*
* @param $taxonomy string Taxonomy key, must not exceed 32 characters
* @param $post_types array|string post type or array of post types with which the taxonomy should be associated
* @param $args array Array or query string of arguments for registering a taxonomy
*
* params are the same as WP's register_taxonomy() except that $args may have extra keys:
*
* 'can_disable_terms' => true|false
*/
function
__construct ($taxonomy, $post_types, $args)
{
$this->name = $taxonomy ;
// modify args, if needed
$default_args = array (
'can_disable_terms' => false,
) ;
$args = wp_parse_args ($args, $default_args) ;
$this->can_disable_terms = $args['can_disable_terms'] ;
unset ($args['can_disable_terms']) ;
if ($this->can_disable_terms) {
// TODO: is there a better filter to hook into than 'get_terms_defaults'?
// I've tried 'get_terms_args', but that seems to be called too late
// in the process of builing the WP_Term_Query used by get_terms(), etc
// to have the meta_query that is added by $this->strip_disabled_terms()
add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;
}
// register the taxonomy
register_taxonomy ($taxonomy, $post_types, $args) ;
return ;
}
/**
* disable a term
*
* disabling a term will make it appear as if the term does not exist, without actually deleting it
*
* @param $term int|string|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure
*/
function
disable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;
}
/**
* enable a term
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
enable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;
}
/**
* strip disabled terms from e.g., get_terms() and get_the_terms()
*
* TODO: make sure that this works correctly given WP Core's object caching
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
strip_disabled_terms ($args, $taxonomies)
{
if (!$this->can_disable_terms) {
return ($args) ;
}
// I *think* the count('taxonomy') check is necesary because get_terms_args() is
// applied by the WP Core object_term caching infrastructure by
// passing all taxonomies for a given post_type, and we only want to
// add this restriction when we are getting the terms for just the
// this taxonomy
if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {
return ($args) ;
}
$args['meta_query'] = array (
array (
'key' => self::DISABLED_TERM_META_KEY,
'compare' => 'NOT EXISTS',
)
) ;
return ($args) ;
}
}
```
My use case
===========
I've got 2 custom post types, `type_a` and `type_b`. `type_b` has a custom taxonomy, `taxonomy_b`, the terms of which are the post\_title's of all of the posts of type `type_a`.
Only those posts of `type_a` whose `post_status` is `publish` should have their corresponding terms in `taxonomy_b` enabled. I accomplish this by hooking into `save_post_type_a` to insert the terms (if they don't already exist) and enable/disable them, and hook into `delete_post` to delete them.
If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.
Questions I still have
======================
I'm still working on this plugin and there are a few open issues around it's implementation.
1. is the `get_terms_defaults` filter that I hook into to add the meta\_query to `WP_Term_Query` the best hook to use? I've tried `get_terms_args`, but that seems to be called too late in the process of builing the WP\_Term\_Query used by get\_terms(), etc. to correctly process the meta\_query that is added by `Custom_taxonomy::strip_disabled_terms()`.
2. I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to `get_terms()` caches the terms in the taxonomy, and them the term is enabled in the same execution of `wp()` will a subsequent call to `get_terms()` include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.
If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in! |
257,702 | <p>I want my <code>single.php</code> to display posts in the same category for the previous and next posts underneath the post. The problem is that each of my posts belongs to multiple categories, and they are displayed through one of the other categories (24) versus the one I want them to display from (27). Does that even make sense?</p>
<p>Example Categories:</p>
<p>Characters (parent category) (Subcategory IDs listed below:)</p>
<ul>
<li>24 (This category ID displaying instead.)</li>
<li>27 (This is the category ID that I want to display.)</li>
</ul>
<p>Now, my question is, how do I choose the category I want to be pulled from (27) instead of the one being automatically pulled (24)? Here is my code below (that I've found and been fiddling with), with what I've tried so far.</p>
<pre><code> <?php
if (is_single() && in_category('stories')) {
$post_id = $post->ID;
$cat = get_the_category(); //I've tried changing this to my category (both ID and slug)
$current_cat_id = $cat[0]->cat_ID; //Also tried plugging ID and slug
$args = array(
'category' => $current_cat_id, //Also tried plugging ID and slug
'orderby' => 'post_date',
'order' => 'DESC'
);
$posts = get_posts($args);
$ids = array();
foreach ($posts as $thepost) {
$ids[] = $thepost->ID;
}
$thisindex = array_search($post_id, $ids);
$previd = $ids[$thisindex - 1];
$nextid = $ids[$thisindex + 1];
if (!empty($nextid)) {
?><div class="double-grid"><a rel="next" href="<?php echo get_permalink($nextid) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($nextid); ?>'"> <div class="gold-button">LAST STORY >></div></div></a></div><?php
}
if (!empty($previd)) {
?><div class="double-grid"><a rel="prev" href="<?php echo get_permalink($previd) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($previd); ?>'"> <div class="gold-button">NEXT STORY >></div></div></a></div><?php
}
}
?>
</code></pre>
| [
{
"answer_id": 257727,
"author": "Max Yudin",
"author_id": 11761,
"author_profile": "https://wordpress.stackexchange.com/users/11761",
"pm_score": 2,
"selected": false,
"text": "<p>You can temporarily exclude your terms from the queries. Meaning that you hide them on some listing pages, ... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257702",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114049/"
] | I want my `single.php` to display posts in the same category for the previous and next posts underneath the post. The problem is that each of my posts belongs to multiple categories, and they are displayed through one of the other categories (24) versus the one I want them to display from (27). Does that even make sense?
Example Categories:
Characters (parent category) (Subcategory IDs listed below:)
* 24 (This category ID displaying instead.)
* 27 (This is the category ID that I want to display.)
Now, my question is, how do I choose the category I want to be pulled from (27) instead of the one being automatically pulled (24)? Here is my code below (that I've found and been fiddling with), with what I've tried so far.
```
<?php
if (is_single() && in_category('stories')) {
$post_id = $post->ID;
$cat = get_the_category(); //I've tried changing this to my category (both ID and slug)
$current_cat_id = $cat[0]->cat_ID; //Also tried plugging ID and slug
$args = array(
'category' => $current_cat_id, //Also tried plugging ID and slug
'orderby' => 'post_date',
'order' => 'DESC'
);
$posts = get_posts($args);
$ids = array();
foreach ($posts as $thepost) {
$ids[] = $thepost->ID;
}
$thisindex = array_search($post_id, $ids);
$previd = $ids[$thisindex - 1];
$nextid = $ids[$thisindex + 1];
if (!empty($nextid)) {
?><div class="double-grid"><a rel="next" href="<?php echo get_permalink($nextid) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($nextid); ?>'"> <div class="gold-button">LAST STORY >></div></div></a></div><?php
}
if (!empty($previd)) {
?><div class="double-grid"><a rel="prev" href="<?php echo get_permalink($previd) ?>"><div class="image-tile tile-on-archive-page" style="background-image: url('<?php echo get_the_post_thumbnail_url($previd); ?>'"> <div class="gold-button">NEXT STORY >></div></div></a></div><?php
}
}
?>
``` | Not directly, but I have a need for this functionality as well, as part of a plugin I'm writing for a client and have what I think is a pretty good start on an implementation.
The approach I'm taking is to store a term meta when the term is disabled and then to hook into the `get_terms_defaults` filter to strip disabled terms that would be returned by WP Core's calls to `get_terms()`, `get_the_terms()`, etc.
My plugin encapsulates all of this into a class which serves as a wrapper around `register_taxonomy()`. The following is a stripped down version of that class (for the plugin I'm writing, this wrapper does a lot more with custom taxonomies).
See `Custom_Taxonomy::enable_term()` and `Custom_Taxonmy::disable_term()` for the code that adds/deletes the relevant term meta; and see `Custom_Taxonomy::strip_disabled_terms()` for the code that strips disabled terms.
Hopefully, I've left in all of the relevant code from this class when I stripped out the stuff that doesn't apply to this question :-)
```
/**
* this class is a wrapper around register_taxonomy(), that adds additional functionality
* to allow terms in the taxonomy so registered to be "disabled".
*
* Disabled terms will NOT be returned by the various WP Core functions like get_terms(),
* get_the_terms(), etc.
*
* TODO: make sure that this works correctly given WP Core's object caching, see Custom_Taxonomy::strip_disabled_terms()
*/
class
Custom_Taxonomy
{
const DISABLED_TERM_META_KEY = '_shc_disabled' ;
public $name ;
public $can_disable_terms = false ;
/**
* construct an instance of Custom_Taxonomy
*
* @param $taxonomy string Taxonomy key, must not exceed 32 characters
* @param $post_types array|string post type or array of post types with which the taxonomy should be associated
* @param $args array Array or query string of arguments for registering a taxonomy
*
* params are the same as WP's register_taxonomy() except that $args may have extra keys:
*
* 'can_disable_terms' => true|false
*/
function
__construct ($taxonomy, $post_types, $args)
{
$this->name = $taxonomy ;
// modify args, if needed
$default_args = array (
'can_disable_terms' => false,
) ;
$args = wp_parse_args ($args, $default_args) ;
$this->can_disable_terms = $args['can_disable_terms'] ;
unset ($args['can_disable_terms']) ;
if ($this->can_disable_terms) {
// TODO: is there a better filter to hook into than 'get_terms_defaults'?
// I've tried 'get_terms_args', but that seems to be called too late
// in the process of builing the WP_Term_Query used by get_terms(), etc
// to have the meta_query that is added by $this->strip_disabled_terms()
add_filter ('get_terms_defaults', array ($this, 'strip_disabled_terms'), 10, 2) ;
}
// register the taxonomy
register_taxonomy ($taxonomy, $post_types, $args) ;
return ;
}
/**
* disable a term
*
* disabling a term will make it appear as if the term does not exist, without actually deleting it
*
* @param $term int|string|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return int|WP_Error|bool Meta ID on success. WP_Error when term_id is ambiguous between taxonomies. False on failure
*/
function
disable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (add_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY, true, true)) ;
}
/**
* enable a term
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
enable_term ($term, $taxonomy = '', $field = 'name')
{
if (!$this->can_disable_terms) {
return ;
}
$taxonomy = $taxonomy ? $taxonomy : $this->name ;
if (is_string ($term)) {
$term = get_term_by ($field, $term, $taxonomy) ;
}
else {
$term = get_term ($term, $taxonomy) ;
}
return (delete_term_meta ($term->term_id, self::DISABLED_TERM_META_KEY)) ;
}
/**
* strip disabled terms from e.g., get_terms() and get_the_terms()
*
* TODO: make sure that this works correctly given WP Core's object caching
*
* @param $term int|WP_Term the term to disable
* @param $taxonomy string the taxonomy term is in
* @return bool True on success, false on failure
*/
function
strip_disabled_terms ($args, $taxonomies)
{
if (!$this->can_disable_terms) {
return ($args) ;
}
// I *think* the count('taxonomy') check is necesary because get_terms_args() is
// applied by the WP Core object_term caching infrastructure by
// passing all taxonomies for a given post_type, and we only want to
// add this restriction when we are getting the terms for just the
// this taxonomy
if (count ($args['taxonomy']) != 1 || !in_array ($this->name, $args['taxonomy'])) {
return ($args) ;
}
$args['meta_query'] = array (
array (
'key' => self::DISABLED_TERM_META_KEY,
'compare' => 'NOT EXISTS',
)
) ;
return ($args) ;
}
}
```
My use case
===========
I've got 2 custom post types, `type_a` and `type_b`. `type_b` has a custom taxonomy, `taxonomy_b`, the terms of which are the post\_title's of all of the posts of type `type_a`.
Only those posts of `type_a` whose `post_status` is `publish` should have their corresponding terms in `taxonomy_b` enabled. I accomplish this by hooking into `save_post_type_a` to insert the terms (if they don't already exist) and enable/disable them, and hook into `delete_post` to delete them.
If your use case for disabled terms is at all similar, them the above should at least point you in one possible direction.
Questions I still have
======================
I'm still working on this plugin and there are a few open issues around it's implementation.
1. is the `get_terms_defaults` filter that I hook into to add the meta\_query to `WP_Term_Query` the best hook to use? I've tried `get_terms_args`, but that seems to be called too late in the process of builing the WP\_Term\_Query used by get\_terms(), etc. to correctly process the meta\_query that is added by `Custom_taxonomy::strip_disabled_terms()`.
2. I'm not sure how this interacts with WP Core's object caching. For example, if a term is disabled when a call to `get_terms()` caches the terms in the taxonomy, and them the term is enabled in the same execution of `wp()` will a subsequent call to `get_terms()` include the term or will it return the cached terms...which wouldn't include the term. But it seems to be working in the tests I've done thus far.
If anyone reading this has any suggestions for improvements on this class, especially about the object caching aspect, please, chime in! |
257,705 | <p>If you go to the ps4 page you will see that the last post is there</p>
<p><a href="http://gamersaction.com/" rel="nofollow noreferrer">My Site</a></p>
<p>Is it necessary to do something for the post to appear on the homepage or should it appear by default?</p>
| [
{
"answer_id": 257707,
"author": "Ashish Dung Dung",
"author_id": 65102,
"author_profile": "https://wordpress.stackexchange.com/users/65102",
"pm_score": 0,
"selected": false,
"text": "<p>You can set auto purge whenever you publish or update a post. \nHowever its better to purge all cach... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257705",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
] | If you go to the ps4 page you will see that the last post is there
[My Site](http://gamersaction.com/)
Is it necessary to do something for the post to appear on the homepage or should it appear by default? | You are most likely using browser caching ? Therefore new visitors would see the newly published post just fine, but because you've previously visited the page its cached and therefore your browser cache hasnt expired.
Generally its good practice to clear all caches upon publishing posts/pages and/or activating or deactivating a plugin.
You can also disable page caching for the front page :
```
performance - page cache - Don't cache front page
``` |
257,708 | <p>My whole theme uses <code>remove_filter( 'the_content', 'wpautop' );</code> which strips the p tags and lines breaks from the output of the WYSIWYG. I have a custom post type <code>events</code> that I would like to bring back the auto p tags and br tags for, but JUST on that custom post type. Is there a way to make sure that filter doesn't get removed on <code>events</code>.</p>
| [
{
"answer_id": 257707,
"author": "Ashish Dung Dung",
"author_id": 65102,
"author_profile": "https://wordpress.stackexchange.com/users/65102",
"pm_score": 0,
"selected": false,
"text": "<p>You can set auto purge whenever you publish or update a post. \nHowever its better to purge all cach... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257708",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/93770/"
] | My whole theme uses `remove_filter( 'the_content', 'wpautop' );` which strips the p tags and lines breaks from the output of the WYSIWYG. I have a custom post type `events` that I would like to bring back the auto p tags and br tags for, but JUST on that custom post type. Is there a way to make sure that filter doesn't get removed on `events`. | You are most likely using browser caching ? Therefore new visitors would see the newly published post just fine, but because you've previously visited the page its cached and therefore your browser cache hasnt expired.
Generally its good practice to clear all caches upon publishing posts/pages and/or activating or deactivating a plugin.
You can also disable page caching for the front page :
```
performance - page cache - Don't cache front page
``` |
257,738 | <p>I am using "ugly" permalinks and they are fine in index.php and single.php. I also have a template called sidebar.php that builds a sidebar when at the article/post level. When clicking categories and tags on the sidebar I am then returned with a 404. The actual format is: </p>
<p><a href="http://localhost/mywebsite/tag/mytag" rel="nofollow noreferrer">http://localhost/mywebsite/tag/mytag</a></p>
<p><a href="http://localhost/mywebsite/category/mycategory" rel="nofollow noreferrer">http://localhost/mywebsite/category/mycategory</a></p>
<p>As opposed to what I am expecting for ugly permalinks (and it shows in index.php and single.php):</p>
<p><a href="http://localhost/mywebsite/?tag=1" rel="nofollow noreferrer">http://localhost/mywebsite/?tag=1</a></p>
<p><a href="http://localhost/mywebsite/?cat=3" rel="nofollow noreferrer">http://localhost/mywebsite/?cat=3</a></p>
<p>My tags are defined like this:</p>
<pre><code>function printTags($tags){
if ($tags!=false) {
$return = '';
foreach ($tags as $i){
$return .= '<li><a href="' . home_url() . "/tag/" . $i->slug . '">' . $i->name . '</a></li>';
}
return $return;
}
}
function getTags($tagData){
$tagArray = [];
if($tagData!=false){
foreach ($tagData as $i){
array_push($tagArray, $i->name);
}
}
return $tagArray;
}
</code></pre>
<p>My HTML/PHP is as follows:</p>
<pre><code>function newSuggestion($itemTitle, $sectionSlug, $section, $image, $url, $tags){
echo "<li class='row class'>
<div class='col item'>
<div class='row img-container'>
<div class='col'>
<a href='{$url}'><img src='{$image}' alt='No Image'/></a>
</div>
</div>
<div class='row anotherclass'>
<div class='categories-container'>
<strong><a href='". home_url() ."/category/". $sectionSlug."'>{$section}</a></strong>
</div>
<div class='tags-container'>
<ul class='tags'>". printTags($tags) ."</ul>
</div>
</div>
<div class='row title-container'>
<h2 class='h3'><a href='{$url}'>{$itemTitle}</a></h2>
</div>
</div>
</li>";
}
</code></pre>
<p>Where am I going wrong?</p>
<p>Thank you</p>
<p><strong>EDIT1:</strong></p>
<p>Here is my getPosts function from sidebar.php:</p>
<pre><code> function getPosts($posts, $numSuggestion){
foreach ( $posts as $post ) {
if ($post->ID!=get_the_ID() && $GLOBALS['currentSuggestion']<$numSuggestion && !in_array($post->ID, $GLOBALS['$alreadySuggested'])){
$imageUrl = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
if ($imageUrl == false){
$imageUrl = getDefaultImage();
}
newSuggestion($post->post_title, get_the_category($post->ID)[0]->slug, get_the_category($post->ID)[0]->name, $imageUrl, get_permalink($post->ID), get_the_tags($post->ID));
$GLOBALS['currentSuggestion']++;
array_push($GLOBALS['$alreadySuggested'], $post->ID);
}
}
}
</code></pre>
<p><strong>EDIT2:</strong></p>
<p>I have attempted this: </p>
<pre><code><div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $cat_ID."'>{$section}</a></strong>
</div>
</code></pre>
<p>But with no success, is that the right direction. Where do I make the modification in order to get the categories URL in the format "home_url/category/?cat=123"?</p>
<p><strong>EDIT3:</strong></p>
<p>Not sure I am going towards the right direction, but I have managed to get the right URL, however it returns a 404 (as opposed to categories at article/home level)</p>
<p>I have modified the getPosts function so that <code>get_the_category</code> is mapped to the cat_ID rather than the slug (I am not sure that is the right approach):</p>
<pre><code> newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
</code></pre>
<p>then my newSuggestion function has:</p>
<pre><code> <div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $sectionSlug."'>{$section}</a></strong>
</div>
</code></pre>
<p>Any idea why I am still hitting a 404, while the same URL is functioning in other parts of the site (e.g. home/index or article)? </p>
<p><strong>EDIT4:</strong></p>
<p>I finally got the categories working with this:</p>
<pre><code><div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
</code></pre>
| [
{
"answer_id": 257910,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of:</p>\n\n<pre><code>home_url() . \"/tag/\" . $i->slug\n</code></pre>\n\n<p>Use <a href=\"https:/... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257738",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/29402/"
] | I am using "ugly" permalinks and they are fine in index.php and single.php. I also have a template called sidebar.php that builds a sidebar when at the article/post level. When clicking categories and tags on the sidebar I am then returned with a 404. The actual format is:
<http://localhost/mywebsite/tag/mytag>
<http://localhost/mywebsite/category/mycategory>
As opposed to what I am expecting for ugly permalinks (and it shows in index.php and single.php):
<http://localhost/mywebsite/?tag=1>
<http://localhost/mywebsite/?cat=3>
My tags are defined like this:
```
function printTags($tags){
if ($tags!=false) {
$return = '';
foreach ($tags as $i){
$return .= '<li><a href="' . home_url() . "/tag/" . $i->slug . '">' . $i->name . '</a></li>';
}
return $return;
}
}
function getTags($tagData){
$tagArray = [];
if($tagData!=false){
foreach ($tagData as $i){
array_push($tagArray, $i->name);
}
}
return $tagArray;
}
```
My HTML/PHP is as follows:
```
function newSuggestion($itemTitle, $sectionSlug, $section, $image, $url, $tags){
echo "<li class='row class'>
<div class='col item'>
<div class='row img-container'>
<div class='col'>
<a href='{$url}'><img src='{$image}' alt='No Image'/></a>
</div>
</div>
<div class='row anotherclass'>
<div class='categories-container'>
<strong><a href='". home_url() ."/category/". $sectionSlug."'>{$section}</a></strong>
</div>
<div class='tags-container'>
<ul class='tags'>". printTags($tags) ."</ul>
</div>
</div>
<div class='row title-container'>
<h2 class='h3'><a href='{$url}'>{$itemTitle}</a></h2>
</div>
</div>
</li>";
}
```
Where am I going wrong?
Thank you
**EDIT1:**
Here is my getPosts function from sidebar.php:
```
function getPosts($posts, $numSuggestion){
foreach ( $posts as $post ) {
if ($post->ID!=get_the_ID() && $GLOBALS['currentSuggestion']<$numSuggestion && !in_array($post->ID, $GLOBALS['$alreadySuggested'])){
$imageUrl = wp_get_attachment_url( get_post_thumbnail_id($post->ID));
if ($imageUrl == false){
$imageUrl = getDefaultImage();
}
newSuggestion($post->post_title, get_the_category($post->ID)[0]->slug, get_the_category($post->ID)[0]->name, $imageUrl, get_permalink($post->ID), get_the_tags($post->ID));
$GLOBALS['currentSuggestion']++;
array_push($GLOBALS['$alreadySuggested'], $post->ID);
}
}
}
```
**EDIT2:**
I have attempted this:
```
<div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $cat_ID."'>{$section}</a></strong>
</div>
```
But with no success, is that the right direction. Where do I make the modification in order to get the categories URL in the format "home\_url/category/?cat=123"?
**EDIT3:**
Not sure I am going towards the right direction, but I have managed to get the right URL, however it returns a 404 (as opposed to categories at article/home level)
I have modified the getPosts function so that `get_the_category` is mapped to the cat\_ID rather than the slug (I am not sure that is the right approach):
```
newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
```
then my newSuggestion function has:
```
<div class='categories-container'>
<strong><a href='". home_url() ."/category/?cat=". $sectionSlug."'>{$section}</a></strong>
</div>
```
Any idea why I am still hitting a 404, while the same URL is functioning in other parts of the site (e.g. home/index or article)?
**EDIT4:**
I finally got the categories working with this:
```
<div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
``` | Following the suggestion for tags, I have gotten categories working.
I have modified the getposts function by mapping the category to the cat\_ID, rather than the slug:
```
newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
```
Then the NewSuggestion functions works out the categories in this way:
```
<div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
```
The approach works, any suggestion or recommendation on how to improve it is more than welcome. |
257,739 | <p>i'm facing a problem with my custom query and need your help.</p>
<p>I want to display all posts of a specific category and I find this snippet:</p>
<pre><code>// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= 0;
// Make a header for the cateogry
// create a custom wordpress query
query_posts("cat=$cat_id&posts_per_page=22");
// start the wordpress loop!
if (have_posts()) : while (have_posts()) : the_post();
</code></pre>
<p>This is working fine BUT if a posts is in more then one category then all other posts are displayed 2 and 3 times.</p>
<p>For Example:
I want to list all Post of Category 0
There are 2 Posts - post 1 and post 2; post 1 is also in the category 1
Post 1 and Post 2 will be displayed twice in the frontend.</p>
<p>How can i fix this issue?</p>
<p>Thank you guys.</p>
| [
{
"answer_id": 257910,
"author": "cybmeta",
"author_id": 37428,
"author_profile": "https://wordpress.stackexchange.com/users/37428",
"pm_score": 1,
"selected": false,
"text": "<p>Instead of:</p>\n\n<pre><code>home_url() . \"/tag/\" . $i->slug\n</code></pre>\n\n<p>Use <a href=\"https:/... | 2017/02/23 | [
"https://wordpress.stackexchange.com/questions/257739",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114076/"
] | i'm facing a problem with my custom query and need your help.
I want to display all posts of a specific category and I find this snippet:
```
// get all the categories from the database
$cats = get_categories();
// loop through the categries
foreach ($cats as $cat) {
// setup the cateogory ID
$cat_id= 0;
// Make a header for the cateogry
// create a custom wordpress query
query_posts("cat=$cat_id&posts_per_page=22");
// start the wordpress loop!
if (have_posts()) : while (have_posts()) : the_post();
```
This is working fine BUT if a posts is in more then one category then all other posts are displayed 2 and 3 times.
For Example:
I want to list all Post of Category 0
There are 2 Posts - post 1 and post 2; post 1 is also in the category 1
Post 1 and Post 2 will be displayed twice in the frontend.
How can i fix this issue?
Thank you guys. | Following the suggestion for tags, I have gotten categories working.
I have modified the getposts function by mapping the category to the cat\_ID, rather than the slug:
```
newSuggestion($post->post_title, get_the_category($post->ID)[0]->cat_ID, get_the_category($post->ID)[0]->name, $imageUrl,
```
Then the NewSuggestion functions works out the categories in this way:
```
<div class='categories-container'>
<strong><a href='". get_term_link( $sectionSlug) . "'>{$section}</a></strong>
</div>
```
The approach works, any suggestion or recommendation on how to improve it is more than welcome. |
257,749 | <p>We have a site currently with 1000s of pages with 10s of 1000s of urls linking internally to other pages. All current links use the "ugly" form of their url - ....com/?p=IDNUMBER.</p>
<p>In an SEO initiative, we're recreating the url structure. So, my question is, is it ok to leave the internal links "ugly?"</p>
<p>In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link?</p>
| [
{
"answer_id": 257756,
"author": "passionsplay",
"author_id": 82414,
"author_profile": "https://wordpress.stackexchange.com/users/82414",
"pm_score": 3,
"selected": true,
"text": "<p>Changing the permalink structure is definitely a big deal for an existing site. In order to test the vari... | 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257749",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/37934/"
] | We have a site currently with 1000s of pages with 10s of 1000s of urls linking internally to other pages. All current links use the "ugly" form of their url - ....com/?p=IDNUMBER.
In an SEO initiative, we're recreating the url structure. So, my question is, is it ok to leave the internal links "ugly?"
In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link? | Changing the permalink structure is definitely a big deal for an existing site. In order to test the various ways in which changing the permalink structure could break the site, I definitely recommend setting up a test environment.
>
> So, my question is, is it ok to leave the internal links "ugly?"
>
>
>
I'm not sure from an SEO perspective if leaving the urls ugly would matter. It would be tedious, but if you have `ssh` access, you can use [wp-cli](http://wp-cli.org/) to search and replace the urls in the database:
```
wp search-replace 'example.com?p=123' 'example.com/post-slug'
```
You could also create a bash script to do that for each url.
>
> In Wordpress, will a link to ...com/?p=500 automatically redirect to its new pretty url, or will it be a broken link?
>
>
>
The links will not be broken. From a technical standpoint, WordPress performs a [`302` redirect](https://en.wikipedia.org/wiki/HTTP_302).
So yes, the site will still 'work', but you indicate that this is in conjunction with an SEO initiative.
SEO things have more to do with the various indexes that search engines (Google, Bing, etc) have of your site. Note that a `302` redirect implies that the link has "Moved Temporarily". Since you want to move all of the existing SEO "juice" from the old url to the new url, you need to tell the search engines that "This content exists, and has *permanently* moved". For this you want to use a [`301` redirect](https://en.wikipedia.org/wiki/HTTP_301).
There are a couple of ways to do this.
WordPress Plugins
-----------------
There are a few redirection plugins out there that I like:
* [Safe Redirection
Manager](https://wordpress.org/plugins/safe-redirect-manager/)
* [Simple 301
Redirects](https://wordpress.org/plugins/simple-301-redirects/)
But feel free to search and explore. The main drawback is that you have so many urls to input, and doing so for each url will probably be tedious.
Redirects at the Server Level
-----------------------------
You can also create `301` redirects at the server level.
If you are running apache, then you can use its [mod\_rewrite](https://httpd.apache.org/docs/2.4/rewrite/remapping.html) engine inside of an `.htaccess` file.
Nginx has it's own [rewrite module](http://nginx.org/en/docs/http/ngx_http_rewrite_module.html). I think that this [blog post](https://www.nginx.com/blog/creating-nginx-rewrite-rules/) is a little easier to digest than the docs.
Getting a List of the URLs
--------------------------
In any case, one of the challenges is usually getting a complete list of posts, their ids, and the associated slug.
Since the current permalink structure includes the post ID, and the new permalink structure contains the post slug, getting a list of 'before and after' is pretty easy using `wp-cli`. I've used this before to generate the post list:
```
wp post list --fields=ID,post_name --format=csv > posts.csv
```
This will give us a file called `posts.csv` filled with the post id and slug of all the posts:
```
488,a-new-post-slug
495,another-new-post-slug
504,so-many-post-slugs
# ...
```
From there you can do batch transforms using Vim, Sed, or even a spreadsheet program since it's a csv.
Hope this helps with your planing and execution! |
257,757 | <p>I'm creating an advertising portal for a small network using a custom post type. In order to prevent WordPress database corruption or unauthorized access to user information, I need to keep data separated from the advertising app by duplicating custom post type data to an external database when creating and updating an ad post. I'm using the <code>save_post</code> hook to handle when the function should run, and <code>wp_insert_post()</code> to push all post data into the database. What I want to happen is that the post will save in the WordPress database by default, and also save to an external database using my plugin function.</p>
<p>The issue I can't figure out is how to tell <code>wp_insert_post()</code> to use the external database instead of the <code>global $wpdb</code> variable it uses by default, as outlined in WP code reference.</p>
<p>How can I use a custom database with <code>wp_insert_post</code>? Or is there a better method?</p>
<p>My function, based on WordPress codex and Stack Exchange examples:</p>
<pre><code>// Function to push data on update
function my_data_push ($post_id) {
// Check for custom post type
if (get_post_type($post_id) == 'ads'):
// Set up database connection to external ads storage database
$push_to_db = new wpdb('username','password','database','host');
// Insert post data in external database
wp_insert_post($post_id, $wp_error = true);
endif;
}
// Add function to post save hook
add_action('save_post', 'my_data_push');
</code></pre>
| [
{
"answer_id": 257763,
"author": "TMA",
"author_id": 91044,
"author_profile": "https://wordpress.stackexchange.com/users/91044",
"pm_score": -1,
"selected": false,
"text": "<p>For this you need to modify the core wordpress file, in which the function code is written. </p>\n\n<p>You can g... | 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257757",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114085/"
] | I'm creating an advertising portal for a small network using a custom post type. In order to prevent WordPress database corruption or unauthorized access to user information, I need to keep data separated from the advertising app by duplicating custom post type data to an external database when creating and updating an ad post. I'm using the `save_post` hook to handle when the function should run, and `wp_insert_post()` to push all post data into the database. What I want to happen is that the post will save in the WordPress database by default, and also save to an external database using my plugin function.
The issue I can't figure out is how to tell `wp_insert_post()` to use the external database instead of the `global $wpdb` variable it uses by default, as outlined in WP code reference.
How can I use a custom database with `wp_insert_post`? Or is there a better method?
My function, based on WordPress codex and Stack Exchange examples:
```
// Function to push data on update
function my_data_push ($post_id) {
// Check for custom post type
if (get_post_type($post_id) == 'ads'):
// Set up database connection to external ads storage database
$push_to_db = new wpdb('username','password','database','host');
// Insert post data in external database
wp_insert_post($post_id, $wp_error = true);
endif;
}
// Add function to post save hook
add_action('save_post', 'my_data_push');
``` | I have been searching for an answer to this question for over a month now - i do not think wordpress is very good for any site that has a secure external DB or for anyone who does not want to store customer data in the main wordpress database, which is strange as that seems like a highly valued function.
At any rate i came across this code during my research that may help you - it is a global variable for a external DB... according to the author it is usable in the same way as $wpdb global variable is used.
If you want the author's full blurb on it go here <https://bavotasan.com/2011/access-another-database-in-wordpress/>
The code is:
$newdb = new wpdb($DB\_USER, $DB\_PASSWORD, $DB\_NAME, $DB\_HOST);
$newdb->show\_errors();
Hopefully it is of some use to you... |
257,804 | <p>I'm creating for the first time a theme <strong>from scratch</strong>.</p>
<blockquote>
<p>It's not a child theme</p>
</blockquote>
<p>In theme's <code>function.php</code> file I'm doing</p>
<pre><code>add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'style', get_stylesheet_uri());
});
</code></pre>
<p>But the <code>style.css</code> file is not included in the served html.</p>
<p>Is there something I must do to 'force' inclusion of my theme's CSSes ?</p>
<p>In the <code>index.php</code> I tried to print <code>get_stylesheet_uri()</code> and I got the full URL of my css: <code>http://my.domain.it/wp-content/themes/real/style.css</code></p>
<p>For reference, this is my theme's <code>index.php</code></p>
<pre><code><!-- Inizio di INDEX.PHP -->
<?php
get_header();
?>
<!-- Index.php, dopo get_header(); !-->
<DIV id="container">
<div id="row1">
Riga 1
</div>
<div id="row2">
Riga 2
</div>
</DIV> <?php // id="main_container" ?>
<!-- Index.php, prima di get_footer(); !-->
<?php
get_footer();
?>
<!-- Fine di INDEX.PHP -->
</code></pre>
<p>I'm calling <code>get_header()</code> and my header file is included</p>
<p>This is Header.php </p>
<pre><code><!DOCTYPE html>
<html>
<head>
<title>
<?php bloginfo( 'name' ); ?>
</title>
<meta name="description" content=" <?php bloginfo( 'description' ); ?> ">
</head>
<body>
<!-- Fine di HEADER.PHP -->
</code></pre>
| [
{
"answer_id": 257805,
"author": "David Klhufek",
"author_id": 113922,
"author_profile": "https://wordpress.stackexchange.com/users/113922",
"pm_score": -1,
"selected": false,
"text": "<p>let's try this way:</p>\n\n<pre><code><?php\n//\n// Recommended way to include parent theme style... | 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257804",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/94289/"
] | I'm creating for the first time a theme **from scratch**.
>
> It's not a child theme
>
>
>
In theme's `function.php` file I'm doing
```
add_action( 'wp_enqueue_scripts', function() {
wp_enqueue_style( 'style', get_stylesheet_uri());
});
```
But the `style.css` file is not included in the served html.
Is there something I must do to 'force' inclusion of my theme's CSSes ?
In the `index.php` I tried to print `get_stylesheet_uri()` and I got the full URL of my css: `http://my.domain.it/wp-content/themes/real/style.css`
For reference, this is my theme's `index.php`
```
<!-- Inizio di INDEX.PHP -->
<?php
get_header();
?>
<!-- Index.php, dopo get_header(); !-->
<DIV id="container">
<div id="row1">
Riga 1
</div>
<div id="row2">
Riga 2
</div>
</DIV> <?php // id="main_container" ?>
<!-- Index.php, prima di get_footer(); !-->
<?php
get_footer();
?>
<!-- Fine di INDEX.PHP -->
```
I'm calling `get_header()` and my header file is included
This is Header.php
```
<!DOCTYPE html>
<html>
<head>
<title>
<?php bloginfo( 'name' ); ?>
</title>
<meta name="description" content=" <?php bloginfo( 'description' ); ?> ">
</head>
<body>
<!-- Fine di HEADER.PHP -->
``` | Found:
As stated here: <https://codex.wordpress.org/Function_Reference/wp_head>.
>
> Put this template tag immediately before tag in a theme template (ex. header.php, index.php).
>
>
>
So I added
```
<?php wp_head() ?>
```
just before `</HEAD` and now it works. |
257,841 | <p>The idea here is the following (I've now uploaded a picture to make it clearer what I need): </p>
<ol>
<li>Create a new page that contains a nicely formatted CSS table.</li>
<li>Each row would refer to a specific post from a specific category.</li>
<li>Each column would refer to specific information about that post (linked title, post date, post author, etc.)</li>
</ol>
<p>Do I have to learn how to fetch that specific information from the database in order to populate this table?
Or is there any easier way to "tell" WordPress what I need to be (dynamically) allocated to each cell?</p>
<p>Thanks! I'm really in the dark as to how to start this. Would appreciate any help I can get.</p>
<p><a href="https://i.stack.imgur.com/Nz8Jx.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/Nz8Jx.jpg" alt="basic image example of what I need"></a></p>
| [
{
"answer_id": 257849,
"author": "Anwer AR",
"author_id": 83820,
"author_profile": "https://wordpress.stackexchange.com/users/83820",
"pm_score": 2,
"selected": true,
"text": "<p>1: You can use <a href=\"https://developer.wordpress.org/themes/template-files-section/page-templates/\" rel=... | 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257841",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114130/"
] | The idea here is the following (I've now uploaded a picture to make it clearer what I need):
1. Create a new page that contains a nicely formatted CSS table.
2. Each row would refer to a specific post from a specific category.
3. Each column would refer to specific information about that post (linked title, post date, post author, etc.)
Do I have to learn how to fetch that specific information from the database in order to populate this table?
Or is there any easier way to "tell" WordPress what I need to be (dynamically) allocated to each cell?
Thanks! I'm really in the dark as to how to start this. Would appreciate any help I can get.
[](https://i.stack.imgur.com/Nz8Jx.jpg) | 1: You can use [`Page template`](https://developer.wordpress.org/themes/template-files-section/page-templates/) and custom [`WP_Query`](https://codex.wordpress.org/Class_Reference/WP_Query) to show posts from a specific category into a page.
2: you can also achive same thing with [`shortcode`](https://codex.wordpress.org/Shortcode_API) where you will have to create a `shortcode` containing posts from specific category and paste that shortcode into your page.
**Update**
added sample code for custom page template and wp\_query
```
<?php
/**
*
* Template Name: Custom post page
*
**/
get_header(); ?>
<div class="main-content" id="main">
<?php
$args = array(
'post_type' => 'post',
'posts_per_page' => 10,
'category_name' => 'your-category-slug', // replace it with your category slug
);
$query = new WP_Query( $args );
if ( $query->have_posts() ) : ?>
<table class="table post-table">
<thead>
<tr>
<td><strong>Title</strong></td>
<td><strong>Author</strong></td>
<td><strong>Post Date</strong></td>
</tr>
</thead>
<?php while( $query->have_posts() ) : $query->the_post();
?>
<tbody>
<tr>
<td><?php the_title(); ?></td>
<td><?php the_author(); ?></td>
<td><?php the_date( 'F j Y'); ?></td>
</tr>
</tbody>
<?php endwhile; ?>
</table>
<?php endif; wp_reset_postdata(); ?>
</div>
<?php get_footer(); ?>
```
create a new php file inside your theme folder and place the above code into it. and them create a new page from WP dashboard and on the right sidebar select your Custom post page template. |
257,854 | <p>I see that in other sites that use wordpress this does not happen, so I would like to know how to space without creating a blank paragraph or a &nbsp ?</p>
<p>As you can see in the image, in each space a blank paragraph is created</p>
<p><a href="https://i.stack.imgur.com/RZXjV.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/RZXjV.png" alt="enter image description here"></a></p>
<p>And in the_excerpt too</p>
<p><a href="https://i.stack.imgur.com/r6008.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/r6008.png" alt="enter image description here"></a></p>
<p><a href="http://gamersaction.com/" rel="nofollow noreferrer">My site</a> if you want to see more examples</p>
<p>Edit:</p>
<p>The answers of <a href="https://wordpress.stackexchange.com/questions/189692/wordpress-tinymce-prints-empty-p-tag-and-break-html-format/190036#190036">Wordpress tinymce prints empty P tag and break html format</a> did not resolve mine </p>
<p>The paragraphs remain blank and &nbsp keeps appearing</p>
| [
{
"answer_id": 257861,
"author": "Morshed Maruf",
"author_id": 114147,
"author_profile": "https://wordpress.stackexchange.com/users/114147",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\nfunction add_necessary_functions() {\n\n function read_more($limit){\n $p... | 2017/02/24 | [
"https://wordpress.stackexchange.com/questions/257854",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/111513/"
] | I see that in other sites that use wordpress this does not happen, so I would like to know how to space without creating a blank paragraph or a   ?
As you can see in the image, in each space a blank paragraph is created
[](https://i.stack.imgur.com/RZXjV.png)
And in the\_excerpt too
[](https://i.stack.imgur.com/r6008.png)
[My site](http://gamersaction.com/) if you want to see more examples
Edit:
The answers of [Wordpress tinymce prints empty P tag and break html format](https://wordpress.stackexchange.com/questions/189692/wordpress-tinymce-prints-empty-p-tag-and-break-html-format/190036#190036) did not resolve mine
The paragraphs remain blank and   keeps appearing | Judging from your site's content and the comments, you may try using the following CODE in your theme's `functions.php` file. It'll remove empty `<p> </p>` tags from post content:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '', $content );
}
```
However, after it removes the empty `<p> </p>` tags, paragraphs in your site's post content will collapse with each other. To maintain the visual gap between paragraphs, you may use the following CSS:
```
.conteudo-noticia p {
padding-bottom: 15px;
}
```
If `nbsp;` within meta description tags are coming from content (or excerpt) & the plugin used to capture them are handling the content as it should (according to WordPress loop standard), then after using the above CODE, meta tags should be fixed as well.
>
> ***Note:*** After making the above changes, please make sure you **clear browser cache** properly and clear any server cache (from cache plugin, web server etc.) if present before testing the result.
>
>
>
Update:
=======
If you don't want to control paragraph gap with CSS padding, then there is a slightly different CODE you may try:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '<br>', $content );
}
```
This CODE, instead of removing the empty `p` tags, replaces them with line breaks `<br>`. So this way you can control paragraph gaps from within the editor without having empty `p` tags with ` `. |
257,880 | <p>I've created a new widget based on one of my parent theme's custom widgets. In the parent theme the widget files are in the <code>/inc</code> and <code>template-parts</code> folders. I created these same folders in my child theme but can't get the widget to show up on the widgets page. However, it works if I add the widget code to the <code>functions.php</code> file.</p>
<p><strong>UPDATE:</strong></p>
<p>Now I have another problem: <code>Fatal error: Call to undefined function add_action()</code></p>
<p>This is the code I'm using to register the widget:</p>
<pre><code>// Register the widget
function myplugin_register_widgets() {
register_widget( 'Home_Categories' );
}
add_action( 'widgets_init', 'myplugin_register_widgets' );
</code></pre>
<p>This is how the original widget is registered:</p>
<pre><code>// Register the widget
add_action( 'widgets_init', create_function( '', 'return register_widget("Codilight_Widget_Block1");'));
</code></pre>
| [
{
"answer_id": 257861,
"author": "Morshed Maruf",
"author_id": 114147,
"author_profile": "https://wordpress.stackexchange.com/users/114147",
"pm_score": 1,
"selected": false,
"text": "<pre><code><?php\nfunction add_necessary_functions() {\n\n function read_more($limit){\n $p... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257880",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/68414/"
] | I've created a new widget based on one of my parent theme's custom widgets. In the parent theme the widget files are in the `/inc` and `template-parts` folders. I created these same folders in my child theme but can't get the widget to show up on the widgets page. However, it works if I add the widget code to the `functions.php` file.
**UPDATE:**
Now I have another problem: `Fatal error: Call to undefined function add_action()`
This is the code I'm using to register the widget:
```
// Register the widget
function myplugin_register_widgets() {
register_widget( 'Home_Categories' );
}
add_action( 'widgets_init', 'myplugin_register_widgets' );
```
This is how the original widget is registered:
```
// Register the widget
add_action( 'widgets_init', create_function( '', 'return register_widget("Codilight_Widget_Block1");'));
``` | Judging from your site's content and the comments, you may try using the following CODE in your theme's `functions.php` file. It'll remove empty `<p> </p>` tags from post content:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '', $content );
}
```
However, after it removes the empty `<p> </p>` tags, paragraphs in your site's post content will collapse with each other. To maintain the visual gap between paragraphs, you may use the following CSS:
```
.conteudo-noticia p {
padding-bottom: 15px;
}
```
If `nbsp;` within meta description tags are coming from content (or excerpt) & the plugin used to capture them are handling the content as it should (according to WordPress loop standard), then after using the above CODE, meta tags should be fixed as well.
>
> ***Note:*** After making the above changes, please make sure you **clear browser cache** properly and clear any server cache (from cache plugin, web server etc.) if present before testing the result.
>
>
>
Update:
=======
If you don't want to control paragraph gap with CSS padding, then there is a slightly different CODE you may try:
```
add_filter( 'the_content', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
add_filter( 'the_excerpt', 'wpse_257854_remove_empty_p', PHP_INT_MAX );
function wpse_257854_remove_empty_p( $content ) {
return str_ireplace( '<p> </p>', '<br>', $content );
}
```
This CODE, instead of removing the empty `p` tags, replaces them with line breaks `<br>`. So this way you can control paragraph gaps from within the editor without having empty `p` tags with ` `. |
257,892 | <p>I am trying to get post title by sql. My sql code is </p>
<pre><code>$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC ";
global $wpdb;
$result= $wpdb->get_results($query);
if ($result){
foreach($result as $post){
?><li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php echo $post->title; ?></a></li><?php
}
}else{
echo "Sorry, No Post Found.";
}
die();
</code></pre>
<p>Now the problem is I am getting title but the_permalink() is not working.</p>
| [
{
"answer_id": 257894,
"author": "fuxia",
"author_id": 73,
"author_profile": "https://wordpress.stackexchange.com/users/73",
"pm_score": 3,
"selected": true,
"text": "<p>I am not sure why you are using a custom query and not <code>get_posts()</code> or <code>WP_Query</code> as you should... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257892",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/101459/"
] | I am trying to get post title by sql. My sql code is
```
$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate
FROM wp_posts
WHERE wp_posts.post_status = 'publish'
ORDER BY wp_posts.post_date DESC ";
global $wpdb;
$result= $wpdb->get_results($query);
if ($result){
foreach($result as $post){
?><li><a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>">
<?php echo $post->title; ?></a></li><?php
}
}else{
echo "Sorry, No Post Found.";
}
die();
```
Now the problem is I am getting title but the\_permalink() is not working. | I am not sure why you are using a custom query and not `get_posts()` or `WP_Query` as you should.
Anyway, you need to get the post ID …
```
$query ="SELECT wp_posts.post_title AS title ,
wp_posts.post_content AS content,
wp_posts.post_date AS blogdate ,
wp_posts.ID AS ID
```
And then just pass this ID to `get_permalink()`:
```
get_permalink( $post->ID );
```
Similar for the title attribute:
```
the_title_attribute( [ 'post' => $post->ID ] );
``` |
257,899 | <p>I have a page called <code>mypage</code> and a custom query var called <code>mycustomvar</code>, I am trying to rewrite the following url:</p>
<pre><code>http://example.com/index.php?name=mypage&mycustomvar=someword
</code></pre>
<p>to</p>
<pre><code>http://example.com/mypage/someword
</code></pre>
<p>using</p>
<pre><code>add_rewrite_rule( '^mypage/([^/]+)/?', 'index.php?name=mypage&mycustomvar=$matches[1]', 'top' );
</code></pre>
<p>But all I get is:</p>
<pre><code>http://example.com/mypage/?mycustomvar=someword
</code></pre>
<p>showing in the url. I have also tried adding both</p>
<pre><code>add_rewrite_tag( '%mycustomvar%', '([^/]+)' );
</code></pre>
<p>as well as making sure that <code>mycustomvar</code> is added to my custom query vars via the <code>query_vars</code> filter</p>
<p>(and I have tried various combos with and without page name, and using <code>page</code> or <code>pagename</code> in place of <code>name</code>, all with no luck)</p>
| [
{
"answer_id": 257970,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 0,
"selected": false,
"text": "<p>UGH I (maybe) just figured it out. I didn't need my variable to have a name, just a location.</p>\n\n<p>So ch... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257899",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/11023/"
] | I have a page called `mypage` and a custom query var called `mycustomvar`, I am trying to rewrite the following url:
```
http://example.com/index.php?name=mypage&mycustomvar=someword
```
to
```
http://example.com/mypage/someword
```
using
```
add_rewrite_rule( '^mypage/([^/]+)/?', 'index.php?name=mypage&mycustomvar=$matches[1]', 'top' );
```
But all I get is:
```
http://example.com/mypage/?mycustomvar=someword
```
showing in the url. I have also tried adding both
```
add_rewrite_tag( '%mycustomvar%', '([^/]+)' );
```
as well as making sure that `mycustomvar` is added to my custom query vars via the `query_vars` filter
(and I have tried various combos with and without page name, and using `page` or `pagename` in place of `name`, all with no luck) | OK, let's first get some definitive clarification on the proper query vars.
Refer to [Post and Page parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) on the `WP_Query` codex page.
>
> name (string) - use post slug.
>
>
> pagename (string) - use page slug.
>
>
>
We can confirm this with `WP_Query`:
```
$args = array(
'name' => 'mypage'
);
$mypage = new WP_Query( $args );
echo '<pre>';
print_r( $mypage );
echo '</pre>';
```
which will produce:
```
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_name = 'mypage'
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
```
It's looking for `mypage` slug in the `post` post type. If we change this to `pagename`, it looks in the `page` post type.
The reason it *kind of* works on the main query with `name` is due to the [`redirect_guess_404_permalink`](https://codex.wordpress.org/Function_Reference/redirect_guess_404_permalink) function, which kicks in when the original request is a 404. It runs another query to find the closest match and redirect there, if something is found. This also results in any extra parameters getting stripped from the URL.
One important thing to note with hierarchical post types- if your page is a child of another page, you must set the `pagename` query var with the `parent/child` path, as different parents can have children with the same slug.
As for your question, changing the query var to `pagename` works with your original code in v4.7.2 and the Twenty Sixteen theme:
```
function wpd_mypage_rewrite() {
add_rewrite_tag(
'%mycustomvar%',
'([^/]+)'
);
add_rewrite_rule(
'^mypage/([^/]+)/?',
'index.php?pagename=mypage&mycustomvar=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_mypage_rewrite' );
```
Note that I used `add_rewrite_tag` here. You could *instead* use the [`query_vars` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars). The reason `add_rewrite_tag` works is that it internally adds the query var via the same filter.
Don't forget to [flush rewrite rules](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) after adding / changing rules. You can also do this by visiting the Settings > Permalinks page.
You can then `echo get_query_var( 'mycustomvar' );` in the template, and the value is output. |
257,907 | <p>I've a script that I run on each page on my WordPress blog, but it has different input each time.</p>
<p>I have for a example a hint button: The hint button needs to be different on each page.</p>
<pre><code>function answerbutton() {
document.getElementById("answer").innerHTML = 'Readers will see this text as a hint';
}
</code></pre>
<p>What I do now is copy the script to a location and change the value. And load the script from a different location. </p>
<p></p>
<p><a href="https://domainname/page2/hint1" rel="nofollow noreferrer">https://domainname/page2/hint1</a></p>
<p>What I'd like to do is have the script grab some sort of text box on the page editor page. I can use a different input on all pages yet it loads the same text.</p>
<p>I had something in mind like this: </p>
<pre><code><textarea =id"textarea">
function answerbutton() {
document.getElementById("answer").innerHTML = 'ID="textarea"';
}
</code></pre>
<p>But I cannot get it to work.. my javascript skill is zero.
Could someone help me to the right way?
Or give me 'hints'?<br>
Is there a WordPress plugin that can do this for example?</p>
<p>This is what I added to the loop? I guess the index.php:</p>
<pre><code><?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(__('(more...)'));
$hint1_of_this_page = get_post_meta( get_the_ID(), 'hint1', true );
$hint2_of_this_page = get_post_meta( get_the_ID(), 'hint2', true );
$hint3_of_this_page = get_post_meta( get_the_ID(), 'hint3', true );
$hint4_of_this_page = get_post_meta( get_the_ID(), 'hint4', true );
$answerbutton_of_this_page = get_post_meta( get_the_ID(), 'answerbutton', true );
$correctanswervalidate = get_post_meta( get_the_ID(), 'correctanswervalidate', true );
?></p>
<hr> <?php endwhile; else: ?>
</code></pre>
<p>Thhis is what I added to the footer.php:</p>
<pre><code> <script type="text/javascript">
function answerbutton() {
document.getElementById("answer").innerHTML = '<?php echo $answerbutton_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton() {
document.getElementById("hint1").innerHTML = '<?php echo $hint1_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton2() {
document.getElementById("hint2").innerHTML = '<?php echo $hint2_of_this_page; ?>';
}
</script>
</code></pre>
<p>and this is how I use the custom field:
<a href="https://i.stack.imgur.com/sIhHP.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/sIhHP.png" alt="enter image description here"></a></p>
| [
{
"answer_id": 257970,
"author": "Stephen",
"author_id": 11023,
"author_profile": "https://wordpress.stackexchange.com/users/11023",
"pm_score": 0,
"selected": false,
"text": "<p>UGH I (maybe) just figured it out. I didn't need my variable to have a name, just a location.</p>\n\n<p>So ch... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257907",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114176/"
] | I've a script that I run on each page on my WordPress blog, but it has different input each time.
I have for a example a hint button: The hint button needs to be different on each page.
```
function answerbutton() {
document.getElementById("answer").innerHTML = 'Readers will see this text as a hint';
}
```
What I do now is copy the script to a location and change the value. And load the script from a different location.
<https://domainname/page2/hint1>
What I'd like to do is have the script grab some sort of text box on the page editor page. I can use a different input on all pages yet it loads the same text.
I had something in mind like this:
```
<textarea =id"textarea">
function answerbutton() {
document.getElementById("answer").innerHTML = 'ID="textarea"';
}
```
But I cannot get it to work.. my javascript skill is zero.
Could someone help me to the right way?
Or give me 'hints'?
Is there a WordPress plugin that can do this for example?
This is what I added to the loop? I guess the index.php:
```
<?php if (have_posts()) : while (have_posts()) : the_post(); ?>
<h1><?php the_title(); ?></h1>
<p><?php the_content(__('(more...)'));
$hint1_of_this_page = get_post_meta( get_the_ID(), 'hint1', true );
$hint2_of_this_page = get_post_meta( get_the_ID(), 'hint2', true );
$hint3_of_this_page = get_post_meta( get_the_ID(), 'hint3', true );
$hint4_of_this_page = get_post_meta( get_the_ID(), 'hint4', true );
$answerbutton_of_this_page = get_post_meta( get_the_ID(), 'answerbutton', true );
$correctanswervalidate = get_post_meta( get_the_ID(), 'correctanswervalidate', true );
?></p>
<hr> <?php endwhile; else: ?>
```
Thhis is what I added to the footer.php:
```
<script type="text/javascript">
function answerbutton() {
document.getElementById("answer").innerHTML = '<?php echo $answerbutton_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton() {
document.getElementById("hint1").innerHTML = '<?php echo $hint1_of_this_page; ?>';
}
</script>
<script type="text/javascript">
function hintbutton2() {
document.getElementById("hint2").innerHTML = '<?php echo $hint2_of_this_page; ?>';
}
</script>
```
and this is how I use the custom field:
[](https://i.stack.imgur.com/sIhHP.png) | OK, let's first get some definitive clarification on the proper query vars.
Refer to [Post and Page parameters](https://codex.wordpress.org/Class_Reference/WP_Query#Post_.26_Page_Parameters) on the `WP_Query` codex page.
>
> name (string) - use post slug.
>
>
> pagename (string) - use page slug.
>
>
>
We can confirm this with `WP_Query`:
```
$args = array(
'name' => 'mypage'
);
$mypage = new WP_Query( $args );
echo '<pre>';
print_r( $mypage );
echo '</pre>';
```
which will produce:
```
SELECT wp_posts.*
FROM wp_posts
WHERE 1=1
AND wp_posts.post_name = 'mypage'
AND wp_posts.post_type = 'post'
ORDER BY wp_posts.post_date DESC
```
It's looking for `mypage` slug in the `post` post type. If we change this to `pagename`, it looks in the `page` post type.
The reason it *kind of* works on the main query with `name` is due to the [`redirect_guess_404_permalink`](https://codex.wordpress.org/Function_Reference/redirect_guess_404_permalink) function, which kicks in when the original request is a 404. It runs another query to find the closest match and redirect there, if something is found. This also results in any extra parameters getting stripped from the URL.
One important thing to note with hierarchical post types- if your page is a child of another page, you must set the `pagename` query var with the `parent/child` path, as different parents can have children with the same slug.
As for your question, changing the query var to `pagename` works with your original code in v4.7.2 and the Twenty Sixteen theme:
```
function wpd_mypage_rewrite() {
add_rewrite_tag(
'%mycustomvar%',
'([^/]+)'
);
add_rewrite_rule(
'^mypage/([^/]+)/?',
'index.php?pagename=mypage&mycustomvar=$matches[1]',
'top'
);
}
add_action( 'init', 'wpd_mypage_rewrite' );
```
Note that I used `add_rewrite_tag` here. You could *instead* use the [`query_vars` filter](https://codex.wordpress.org/Plugin_API/Filter_Reference/query_vars). The reason `add_rewrite_tag` works is that it internally adds the query var via the same filter.
Don't forget to [flush rewrite rules](https://codex.wordpress.org/Function_Reference/flush_rewrite_rules) after adding / changing rules. You can also do this by visiting the Settings > Permalinks page.
You can then `echo get_query_var( 'mycustomvar' );` in the template, and the value is output. |
257,925 | <p>I found that Woocommerce is disabling autosave, maybe for good reason, but I'd like to have it turned on and see if it presents an issue. This is what I found in the __construct in their post type class, from wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php....</p>
<pre><code>// Disable Auto Save
add_action( 'admin_print_scripts', array( $this, 'disable_autosave' ) );
</code></pre>
<p>Then further down I see this function....</p>
<pre><code>/**
* Disable the auto-save functionality for Orders.
*/
public function disable_autosave() {
global $post;
if ( $post && in_array( get_post_type( $post->ID ), wc_get_order_types( 'order-meta-boxes' ) ) ) {
wp_dequeue_script( 'autosave' );
}
}
</code></pre>
<p>I tried commenting out the wp_dequeue_script call above just to test if that script was enqueued would it work and still does not autosave. But I'd rather not as it is in the core Woocommerce and subject to updates. How can I re-enable without altering the plugin? Or does anyone have any experience as to why I should not?</p>
<p>The way I am testing is by adding this to the save_post hook:</p>
<pre><code>add_action( 'save_post', 'save_product_meta' );
function save_product_meta( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
error_log("DOING AUTOSAVE for " . $post_id);
return $post_id;
}
</code></pre>
<p>In WordPress admin, I get the log entry while letting a normal post sit on screen without saving, but not when a shop_order type post is created.</p>
| [
{
"answer_id": 257949,
"author": "superwinner",
"author_id": 113690,
"author_profile": "https://wordpress.stackexchange.com/users/113690",
"pm_score": 0,
"selected": false,
"text": "<p>I kinda managed to fix it, don't know if it's the proper way, this is in case of sortable fields, using... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257925",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/83280/"
] | I found that Woocommerce is disabling autosave, maybe for good reason, but I'd like to have it turned on and see if it presents an issue. This is what I found in the \_\_construct in their post type class, from wp-content/plugins/woocommerce/includes/admin/class-wc-admin-post-types.php....
```
// Disable Auto Save
add_action( 'admin_print_scripts', array( $this, 'disable_autosave' ) );
```
Then further down I see this function....
```
/**
* Disable the auto-save functionality for Orders.
*/
public function disable_autosave() {
global $post;
if ( $post && in_array( get_post_type( $post->ID ), wc_get_order_types( 'order-meta-boxes' ) ) ) {
wp_dequeue_script( 'autosave' );
}
}
```
I tried commenting out the wp\_dequeue\_script call above just to test if that script was enqueued would it work and still does not autosave. But I'd rather not as it is in the core Woocommerce and subject to updates. How can I re-enable without altering the plugin? Or does anyone have any experience as to why I should not?
The way I am testing is by adding this to the save\_post hook:
```
add_action( 'save_post', 'save_product_meta' );
function save_product_meta( $post_id ) {
if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
error_log("DOING AUTOSAVE for " . $post_id);
return $post_id;
}
```
In WordPress admin, I get the log entry while letting a normal post sit on screen without saving, but not when a shop\_order type post is created. | The reason for this is that the widget will run its update logic on `keydown` *and* also on `change` for a given `input` element. See <https://github.com/WordPress/wordpress-develop/blob/4.7.2/src/wp-admin/js/customize-widgets.js#L891-L907>
There are some tradeoffs made when widgets were added to the customizer to bring these PHP-driven interfaces into a JS-driven context. It wasn't perfect and so this is part of the reason behind the [JS Widgets](https://github.com/xwp/wp-js-widgets/) feature plugin, to modernize how custom widgets are implemented in the customizer.
If you want to really just listen for when a widget actually changes its state, you can listen for the control's underlying `setting` change instead. The setting will only be updated once after a given `keydown` and subsequent `change` event. |
257,942 | <p>I've Developed Plugin for using all WordPress Themes. Now depending on Themes requirements I need to change some files on some files. But I don't wants to touch my Plugin.
I've used <pre>add_theme_support('jeweltheme-core');</pre>
I've copied Plugins files and Folders the same way on Plugin. I need to Edit "Widget" files. I cann't find any way to resolve this problem.</p>
<p>Example:
We overrides "WooCommerce" Templates using "templates" directory copying on our Theme and renamed it to "woocommerce". I want exact like this solution. </p>
<p>Thanks</p>
| [
{
"answer_id": 258098,
"author": "Doug Belchamber",
"author_id": 39013,
"author_profile": "https://wordpress.stackexchange.com/users/39013",
"pm_score": 2,
"selected": false,
"text": "<p>If you've written the plugin, then I'd suggest you add something like this:</p>\n\n<pre><code> // ... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257942",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/85724/"
] | I've Developed Plugin for using all WordPress Themes. Now depending on Themes requirements I need to change some files on some files. But I don't wants to touch my Plugin.
I've used
```
add_theme_support('jeweltheme-core');
```
I've copied Plugins files and Folders the same way on Plugin. I need to Edit "Widget" files. I cann't find any way to resolve this problem.
Example:
We overrides "WooCommerce" Templates using "templates" directory copying on our Theme and renamed it to "woocommerce". I want exact like this solution.
Thanks | I've made my solution like this:
```
function jeweltheme_core_get_template_path($template){
$located = '';
$template_slug = rtrim( $template, '.php' );
$template = $template_slug . '.php';
$this_plugin_dir = WP_PLUGIN_DIR.'/'.str_replace( basename( __FILE__), "", plugin_basename(__FILE__) );
if ( $template ) {
if ( file_exists(get_stylesheet_directory() . '/jeweltheme-core/' . $template)) {
$located = get_stylesheet_directory() . '/jeweltheme-core/' . $template;
} else if ( file_exists(get_template_directory() . '/jeweltheme-core/' . $template) ) {
$located = get_template_directory() . '/jeweltheme-core/' . $template;
} else if ( file_exists( $this_plugin_dir . $template) ) {
$located = $this_plugin_dir . $template;
}
}
return $located;
}
``` |
257,955 | <p>I'm using <code>Wordpress Settings API</code>. Everything works as it should except this <code>select</code> dropdown. When I select an option, the value echoed is correct but in the dropdown it displays the default first value i.e <code>6</code> and not the selected one. Where am I going wrong?</p>
<pre><code> public function someplugin_select() {
$options = get_option( 'plugin_252calc');
echo $options; //shows the correct value selected
$items = array();
for ($i=6; $i <=10; $i+= 0.1)
{
$items[] = $i;
}
echo '<select id="cf-nb" name="cf-nb">';
foreach ( $items as $item )
{
echo '<option value="'. $item .'"';
if ( $item == $options ) echo' selected="selected"';
echo '>'. $item .'</option>';
}
echo '</select>';
}
</code></pre>
| [
{
"answer_id": 257959,
"author": "Roel Magdaleno",
"author_id": 99204,
"author_profile": "https://wordpress.stackexchange.com/users/99204",
"pm_score": 0,
"selected": false,
"text": "<p>I went through this, and I could tell that there's a WP function called <code>selected</code>, which y... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257955",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/447/"
] | I'm using `Wordpress Settings API`. Everything works as it should except this `select` dropdown. When I select an option, the value echoed is correct but in the dropdown it displays the default first value i.e `6` and not the selected one. Where am I going wrong?
```
public function someplugin_select() {
$options = get_option( 'plugin_252calc');
echo $options; //shows the correct value selected
$items = array();
for ($i=6; $i <=10; $i+= 0.1)
{
$items[] = $i;
}
echo '<select id="cf-nb" name="cf-nb">';
foreach ( $items as $item )
{
echo '<option value="'. $item .'"';
if ( $item == $options ) echo' selected="selected"';
echo '>'. $item .'</option>';
}
echo '</select>';
}
``` | The reason your `$item == $option` condition is always failing is because of the way PHP compares floats!
Try the following instead:
```
echo "<option value='$item'" . selected (abs ($item - $options) <= 0.01, true, false) . ">$item</option>" ;
```
See [Comparing floats](http://php.net/manual/en/language.types.float.php#language.types.float.comparison) for more info. |
257,957 | <p>When I change the redirect https in my .htaccess the site returns the message "Too many redirects" loop. </p>
<p>This is the modified .htaccess</p>
<pre><code>RewriteCond %{HTTPS} off
RewriteRule (.*)$ https://www.mywebsite.it/$1 [L,R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
</code></pre>
<p>I also added in the wp-config.php: </p>
<pre><code>define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
</code></pre>
| [
{
"answer_id": 257960,
"author": "Poofy",
"author_id": 114069,
"author_profile": "https://wordpress.stackexchange.com/users/114069",
"pm_score": -1,
"selected": false,
"text": "<p><p>\ndo you want to push all the traffic to https?<p>\ni have ssl installed on my site, and i use this code ... | 2017/02/25 | [
"https://wordpress.stackexchange.com/questions/257957",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/54283/"
] | When I change the redirect https in my .htaccess the site returns the message "Too many redirects" loop.
This is the modified .htaccess
```
RewriteCond %{HTTPS} off
RewriteRule (.*)$ https://www.mywebsite.it/$1 [L,R=301]
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress
```
I also added in the wp-config.php:
```
define('FORCE_SSL_ADMIN', true);
define('FORCE_SSL_LOGIN', true);
``` | Adding redirect to htaccess in the way that you have done will not work without adjudicating the site url to be https as well. If it is http, you will get endless redirect due to wordpress detecting that you are trying to access a non canonical URL (the https), and will try to redirect you to the canonical one, which is based on the site url, which is http, and then the htacess will redirect to https again only for wordpress to redirect to http, and so on. |
257,978 | <p>I have created a page template and custom post type 'pa' that I want to display on the page template. I have the template created, also made <code>archive-pa.php</code>, <code>single-pa.php</code><br>
My template: <code>page-pa.php</code> contains this: </p>
<pre><code><?php
/*
Template Name: Personal Assistants
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php $loop = new WP_Query( array( 'post_type' => 'pa', 'posts_per_page' => 6 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
stuff here
<?php endwhile; wp_reset_query(); ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
</code></pre>
<p>This will only show whatever text I put where 'stuff here' is. As I am new to this I have no idea on how I should display the actual posts; I need some more php queries here to display the posts like it would a normal blog? I found the get_ queries, I have no idea how to construct it - all I can work out is a bit of a hack where I use the permalink as a custom link menu item but I do also want to create a custom search, and categories sidebar too. Any help would be much appreciated!</p>
| [
{
"answer_id": 257960,
"author": "Poofy",
"author_id": 114069,
"author_profile": "https://wordpress.stackexchange.com/users/114069",
"pm_score": -1,
"selected": false,
"text": "<p><p>\ndo you want to push all the traffic to https?<p>\ni have ssl installed on my site, and i use this code ... | 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/257978",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114208/"
] | I have created a page template and custom post type 'pa' that I want to display on the page template. I have the template created, also made `archive-pa.php`, `single-pa.php`
My template: `page-pa.php` contains this:
```
<?php
/*
Template Name: Personal Assistants
*/
get_header(); ?>
<div id="primary" class="content-area">
<main id="main" class="site-main" role="main">
<?php $loop = new WP_Query( array( 'post_type' => 'pa', 'posts_per_page' => 6 ) ); ?>
<?php while ( $loop->have_posts() ) : $loop->the_post(); ?>
stuff here
<?php endwhile; wp_reset_query(); ?>
</main><!-- #main -->
</div><!-- #primary -->
<?php
get_sidebar();
get_footer();
```
This will only show whatever text I put where 'stuff here' is. As I am new to this I have no idea on how I should display the actual posts; I need some more php queries here to display the posts like it would a normal blog? I found the get\_ queries, I have no idea how to construct it - all I can work out is a bit of a hack where I use the permalink as a custom link menu item but I do also want to create a custom search, and categories sidebar too. Any help would be much appreciated! | Adding redirect to htaccess in the way that you have done will not work without adjudicating the site url to be https as well. If it is http, you will get endless redirect due to wordpress detecting that you are trying to access a non canonical URL (the https), and will try to redirect you to the canonical one, which is based on the site url, which is http, and then the htacess will redirect to https again only for wordpress to redirect to http, and so on. |
258,007 | <p>Adding alt tag information to every product photo is a lot of work. We always just copy and paste our product title into the image alt tags.</p>
<p>I figured since all the information is there; there must be a way to do this automatically.</p>
<p><strong>Question:</strong> How do you apply a woocommerce product's TITLE as all the ALT TAGS for images used with that product.</p>
<p>Any help is much appreciated!</p>
| [
{
"answer_id": 258009,
"author": "Richard Webster",
"author_id": 101457,
"author_profile": "https://wordpress.stackexchange.com/users/101457",
"pm_score": 4,
"selected": true,
"text": "<p>This is what you need, taken from - <a href=\"https://stackoverflow.com/questions/27087772/how-can-i... | 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258007",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/110570/"
] | Adding alt tag information to every product photo is a lot of work. We always just copy and paste our product title into the image alt tags.
I figured since all the information is there; there must be a way to do this automatically.
**Question:** How do you apply a woocommerce product's TITLE as all the ALT TAGS for images used with that product.
Any help is much appreciated! | This is what you need, taken from - <https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail>
```
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes( $attr, $attachment ){
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);
// Get post type to check if it's product
$type = get_post_field( 'post_type', $parent);
if( $type != 'product' ){
return $attr;
}
/// Get title
$title = get_post_field( 'post_title', $parent);
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
``` |
258,013 | <p>I'm trying to echo <strong>all</strong> of my custom taxonomies, but this only prints out the first one:</p>
<pre><code>$skill_list = wp_get_post_terms($post->ID, 'skill', array('fields' => 'names'));
echo 'skill-' . $term->slug;
</code></pre>
<p>Does anyone have an idea of what I've done wrong?</p>
| [
{
"answer_id": 258009,
"author": "Richard Webster",
"author_id": 101457,
"author_profile": "https://wordpress.stackexchange.com/users/101457",
"pm_score": 4,
"selected": true,
"text": "<p>This is what you need, taken from - <a href=\"https://stackoverflow.com/questions/27087772/how-can-i... | 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258013",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/91093/"
] | I'm trying to echo **all** of my custom taxonomies, but this only prints out the first one:
```
$skill_list = wp_get_post_terms($post->ID, 'skill', array('fields' => 'names'));
echo 'skill-' . $term->slug;
```
Does anyone have an idea of what I've done wrong? | This is what you need, taken from - <https://stackoverflow.com/questions/27087772/how-can-i-change-meta-alt-and-title-in-catalog-thumbnail-product-thumbnail>
```
add_filter('wp_get_attachment_image_attributes', 'change_attachement_image_attributes', 20, 2);
function change_attachement_image_attributes( $attr, $attachment ){
// Get post parent
$parent = get_post_field( 'post_parent', $attachment);
// Get post type to check if it's product
$type = get_post_field( 'post_type', $parent);
if( $type != 'product' ){
return $attr;
}
/// Get title
$title = get_post_field( 'post_title', $parent);
$attr['alt'] = $title;
$attr['title'] = $title;
return $attr;
}
``` |
258,026 | <p>I am trying to build a plugin that will replace one file from the theme. It will be plugin for certain theme that has a file placed in includes folder to the path would be: </p>
<p>wp-content/theme/includes/example-file.php</p>
<p>This example-file.php is loaded in header and footer also via <code>include</code></p>
<p>I want to make a plugin that would overwrite example-file.php so that theme includes that file from my plugin and not the includes folder from theme. </p>
<p>How is that possible, what would be the best way to do this?</p>
| [
{
"answer_id": 258032,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h1>WordPress way (recommended):</h1>\n\n<p>In your plugin, use the WordPress <code>theme_file_path</code> filter... | 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258026",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/81451/"
] | I am trying to build a plugin that will replace one file from the theme. It will be plugin for certain theme that has a file placed in includes folder to the path would be:
wp-content/theme/includes/example-file.php
This example-file.php is loaded in header and footer also via `include`
I want to make a plugin that would overwrite example-file.php so that theme includes that file from my plugin and not the includes folder from theme.
How is that possible, what would be the best way to do this? | WordPress way (recommended):
============================
In your plugin, use the WordPress `theme_file_path` filter hook to change the file from the plugin. Use the following CODE in your plugin:
```
add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );
function wpse_258026_modify_theme_include_file( $path, $file = '' ) {
if( 'includes/example-file.php' === $file ) {
// change path here as required
return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';
}
return $path;
}
```
Then you may include the file in your theme using the [`get_theme_file_path`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) function, like this:
```
include get_theme_file_path( 'includes/example-file.php' );
```
Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.
Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification.
Controlling Page Template from Plugin:
======================================
If you are looking for controlling page templates from your plugin, then you may [check out this answer](https://wordpress.stackexchange.com/a/257674/110572) to see how to do it.
PHP way:
========
If you are including the `wp-content/theme/<your-theme>/includes/example-file.php` file using simple `include` call with **relative path** inside header, footer templates like the following:
```
include 'includes/example-file.php';
```
then it's also possible to replace it with the plugin's version of `includes/example-file.php` file using PHP `set_include_path()` function.
Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path:
```
set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );
```
After that, for any `include` with relative path in `header.php`, `footer.php` etc. PHP will look for the file in your plugin's directory first.
>
> However, this method ***will not work*** if you include the file using absolute path in your header, footer etc.
>
>
> |
258,048 | <p>I am working with twenty fourteen theme.
I want to customize the full-width template for my needs, to make it wider on specific pages.
so I copied it into a sub folder in my child theme.</p>
<p>how do I embed styling that will affect this template ONLY?</p>
<p>tried this, but it doesnt work: <a href="http://www.transformationpowertools.com/wordpress/real-full-width-page-template-twentyfourteen" rel="nofollow noreferrer">http://www.transformationpowertools.com/wordpress/real-full-width-page-template-twentyfourteen</a></p>
<p>p.s: I am not a developer :(</p>
| [
{
"answer_id": 258032,
"author": "Fayaz",
"author_id": 110572,
"author_profile": "https://wordpress.stackexchange.com/users/110572",
"pm_score": 4,
"selected": true,
"text": "<h1>WordPress way (recommended):</h1>\n\n<p>In your plugin, use the WordPress <code>theme_file_path</code> filter... | 2017/02/26 | [
"https://wordpress.stackexchange.com/questions/258048",
"https://wordpress.stackexchange.com",
"https://wordpress.stackexchange.com/users/114256/"
] | I am working with twenty fourteen theme.
I want to customize the full-width template for my needs, to make it wider on specific pages.
so I copied it into a sub folder in my child theme.
how do I embed styling that will affect this template ONLY?
tried this, but it doesnt work: <http://www.transformationpowertools.com/wordpress/real-full-width-page-template-twentyfourteen>
p.s: I am not a developer :( | WordPress way (recommended):
============================
In your plugin, use the WordPress `theme_file_path` filter hook to change the file from the plugin. Use the following CODE in your plugin:
```
add_filter( 'theme_file_path', 'wpse_258026_modify_theme_include_file', 20, 2 );
function wpse_258026_modify_theme_include_file( $path, $file = '' ) {
if( 'includes/example-file.php' === $file ) {
// change path here as required
return plugin_dir_path( __FILE__ ) . 'includes/example-file.php';
}
return $path;
}
```
Then you may include the file in your theme using the [`get_theme_file_path`](https://developer.wordpress.org/reference/functions/get_theme_file_path/) function, like this:
```
include get_theme_file_path( 'includes/example-file.php' );
```
Here, if the file is matched in the plugin's filter hook, then the plugin version of the file will be included, otherwise the theme version will be included.
Also, this way, even if the plugin is disabled, the theme will work with its own version of the file without any modification.
Controlling Page Template from Plugin:
======================================
If you are looking for controlling page templates from your plugin, then you may [check out this answer](https://wordpress.stackexchange.com/a/257674/110572) to see how to do it.
PHP way:
========
If you are including the `wp-content/theme/<your-theme>/includes/example-file.php` file using simple `include` call with **relative path** inside header, footer templates like the following:
```
include 'includes/example-file.php';
```
then it's also possible to replace it with the plugin's version of `includes/example-file.php` file using PHP `set_include_path()` function.
Generally speaking, to include a file with relative path, PHP looks for the file in the current directory. However, you can manipulate it so that PHP looks for it in another path first. In that case, use the following PHP CODE in your plugin's main PHP file to include the plugin's directory into PHP's default include path:
```
set_include_path( plugin_dir_path( __FILE__ ) . PATH_SEPARATOR . get_include_path() );
```
After that, for any `include` with relative path in `header.php`, `footer.php` etc. PHP will look for the file in your plugin's directory first.
>
> However, this method ***will not work*** if you include the file using absolute path in your header, footer etc.
>
>
> |